Google Search

Saturday, October 24, 2015

How to create a session? How to set a value in session ? How to Remove data from a session?

Create session : session_start();
Set value into session : $_SESSION['USER_ID']=1;
Remove data from a session : unset($_SESSION['USER_ID'];

What is the difference between Session and Cookie?

What is the difference between Session and Cookie?
The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking

What's the difference between include and require?

What's the difference between include and require?
If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

Write a program to explain how array of objects may be created in java.

public static void main(String[] args) {
Student[] studentArray = new Student[7];
studentArray[0] = new Student();
studentArray[0].marks = 99;
System.out.println(studentArray[0].marks); // prints 99
modify(studentArray[0]);
System.out.println(studentArray[0].marks); // prints 100 & not 99
// code
}
public static void modify(Student s) {
s.marks = 100;
}

Application program and applet program.

An applet is client side program which is downloaded in client side and run in the browser. Applet program can not access network connection like opening socket ,writing to socket. A class extending java.awt.Applet class which has methods like init(), start(), stop(), destroy(),paint() overridden. And cannnot write to client side files i.e. hard disk.
An application runs standalone with a support of virtual machine. An application does not have nay restrictions as Applets have over network and file related activities.They are free to open sockets over a network read and write to a file.

What is abstract class? Explain need of abstract class with example.

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Let's look at an example of an abstract class, and an abstract method.
abstract class Bike{ 
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("Honda is a good bike..");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}

What is rule of accessibility at java?

We can have all the four access modifiers for class member variables and methods. However member access modifier rules get applied after the class level access rules. For example, if class is having default access, then it will not be visible in other packages and hence methods and variables of the class will also be not visible.
public keyword
If class member is “public” then it can be accessed from anywhere. The member variable or method is accessed globally. This is simplest way to provide access to class members, however we should take care in using this keyword with class variables otherwise anybody can change the values. Usually class variables are kept as private and getter-setter methods are provided to work with them.
private keyword
If class member is “private” then it will be accessible only inside the same class. This is the most restricted access and the class member will not be visible to the outer world. Usually we keep class variables as private and methods that are intended to be used only inside the class as private.
protected keyword
If class member is “protected” then it will be accessible only to the classes in the same package and to the subclasses. This modifier is less restricted from private but more restricted from public access. Usually we use this keyword to make sure the class variables are accessible only to the subclasses.

Discuss the significance of BITWISE operators in C programming language. Also, write an interactive C program to illustrate them.

Bitwise operators are special types of operators that are used in programming the processor. In processor, mathematical operations like: addition, subtraction, addition and division are done using the bitwise operators which makes processing faster and saves power.
C language supports the following bitwise operators.
| – Bitwise OR
& – Bitwise AND
~ – One’s complement
^ – Bitwise XOR
<< – left shift
>> – right shift
Though we are calling it as a bitwise operators, it always operate on one or more bytes i.e, it will consider the whole representation of the number when applying bitwise operators. By using some techniques, we can manipulate a single bit on the whole representation of the number as we will see in later sections
Bitwise OR – |
Bitwise OR operator | takes 2 bit patterns, and perform OR operations on each pair of corresponding bits. The following example will explain it.
1010
1100
--------
OR 1110
--------
The Bitwise OR, will take pair of bits from each position, and if any one of the bit is 1, the result on that position will be 1. Bitwise OR is used to Turn-On bits as we will see in later sections.
Bitwise AND – &
Bitwise AND operator &, takes 2 bit patterns, and perform AND operations with it.
1010
1100
-------
AND 1000
-------
The Bitwise AND will take pair of bits from each position, and if only both the bit is 1, the result on that position will be 1. Bitwise AND is used to Turn-Off bits.
One’s Complement operator – ~
One’s complement operator (Bitwise NOT) is used to convert each “1-bit to 0-bit” and “0-bit to 1-bit”, in the given binary pattern. It is a unary operator i.e. it takes only one operand.
1001
NOT
-------
0110
-------
Bitwise XOR – ^
Bitwise XOR ^, takes 2 bit patterns and perform XOR operation with it.
0101
0110
------
XOR 0011
------
The Bitwise XOR will take pair of bits from each position, and if both the bits are different, the result on that position will be 1. If both bits are same, then the result on that position is 0.
Left shift Operator – <<
The left shift operator will shift the bits towards left for the given number of times.
int a=2<<1;
Let’s take the binary representation of 2 assuming int is 1 byte for simplicity.
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 0 1 0
Now shifting the bits towards left for 1 time, will give the following result
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 1 0 0
Now the result in decimal is 4. You can also note that, 0 is added as padding the in the position 0.
If you left shift like 2<<2, then it will give the result as 8. Therefore left shifting 1 time, is equal to multiplying the value by 2.
Right shift Operator – >>
The right shift operator will shift the bits towards right for the given number of times.
int a=8>>1;
Let’s take the binary representation of 8 assuming int is 1 byte for simplicity.
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 1 0 0 0
Now shifting the bits towards right for 1 time, will give the following result
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 1 0 0
Now the result in decimal is 4. Right shifting 1 time, is equivalent to dividing the value by 2.
C Program:
‪#‎include‬ <stdio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}

Explain the steps involved in creating a distributed application using Remote Method Invocation (RMI).

Remote method invocation (RMI) allow a java object to invoke method on an object running on another machine. RMI provide remote communication between java program. RMI is used for building distributed application.
This is the 6 steps to write the RMI program:
1. Create the remote interface
2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application

Static variable and static method in java

static is a keyword in java and we can’t create a class or package name as static. Java static keyword can be used in four cases.
Java static variables: We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe. Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it with ClassName.variableName
//static variable example
private static int count;
public static String str;
public static final String DB_USER = "myuser";
Java static methods: Same as static variables, static methods belong to class and not to class instances. A static method can access only static variables of class and invoke only static methods of the class. Usually static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance; for example Collections class. Java Wrapper classes and utility classes contains a lot of static methods. The main() method that is the entry point of a java program itself is a static method.
//static method example
public static void setCount(int count) {
if(count > 0)
StaticExample.count = count;
}
//static util method
public static int addInts(int i, int...js){
int sum=i;
for(int x : js) sum+=x;
return sum;
}

Define a flowchart

A flowchart is a graphical representation of decisions and their results mapped out in individual shapes that were first developed by Herman Goldstine and John von Neumann in the 1940's. Flowcharts can provide a step-by-step diagram for mapping out complex situations, such as programming code or troubleshooting problems with a computer.
A flow chart is a graphical or symbolic representation of a process. Each step in the process is represented by a different symbol and contains a short description of the process step. The flow chart symbols are linked together with arrows showing the process flow direction.

C program example of "Function with no arguments and no return value."

‪#‎include‬<stdio.h>
void area(); // Prototype Declaration
void main()
{
area();
}
void area()
{
float area_circle;
float rad;
printf("\nEnter the radius : ");
scanf("%f",&rad);
area_circle = 3.14 * rad * rad ;
printf("Area of Circle = %f",area_circle);
}
Output:
Enter the radius : 3
Area of Circle = 28.260000

PROLOG Code for Fibonacci Numbers

fibo(1,0).
fibo(2,1).
fibo(N,F):-N>1,N1 is N-1, fibo(N1,F1), N2 is N-2, fibo(N2,F2), F is F1+F2.

PROLOG Code for GCD

gcd(A,B,G):- A=B, G is A.
gcd(A,B,G):- A>B, AB is A-B, gcd(AB,B,G).
gcd(A,B,G):- A<B, BA is B-A, gcd(A,BA,G).

PROLOG Code for Factorial

fact(0,1).
fact(N,F):-N>0,N1 is N-1,fact(N1,F1),F is N*F1.

C program of Multiple queue in a single dimensional array

‪#‎include‬<stdio.h>
#include<conio.h>
# define max 20
int insq (int queue[max], int qno, int rear[], int limit[], int *data) {
if (rear[qno] == limit[qno])
return(-1);
else {
rear[qno]++; //... rear[qno] = rear[qno] + 1;
queue[ rear[qno] ] = *data;
return(1);
} // else
} // insq
int delq (int queue[max], int qno, int front[], int rear[], int *data) {
if( front[qno] == rear[qno] )
return(-1);
else {
front[qno]++; //... front[qno] = front[qno] + 1;
*data = queue[ front[qno] ];
return(1);
} // else
} // delq
int getQueueNumber(int n) {
int qNo=0;
Inva:
printf("\n Enter a Logical Queue Number (1 to %d) : ", n);
scanf("%d", &qNo);
if (qNo<1 || qNo >n) {
printf(" Invalid Queue Number. Please try again.\n");
goto Inva;
}
return qNo;
}
void main() {
int queue[max], data;
int bott[10], limit[10], f[10], r[10];
int i, n, qno, size, option, reply;
printf("\n C Language program to implement the Multiple Queues \n");
printf("\n How Many Queues ? : ");
scanf("%d", &n);
size = max / n; //... Get Max. size for each Queue
//... Initialize bottom for each Queue
bott[0] = -1; //... Bottom of first Queue is -1
for(i = 1; i < n; i++)
bott[i] = bott[i-1] + size;
//... Initialize Limit of each Queue
for(i = 0; i < n; i++) //... Limit of i'th Queue is equal to bottom of i'th Queue + Size
limit[i] = bott[i] + size;
//... Initialize Front & Rear of each Queue
//... Initial value of Front & Rear of each Queue is same as its Bottom Value
for(i = 0; i < n; i++)
f[i] = r[i] = bott[i];
//... Process the Queues
do {
printf("\n\n C Language program to implement the Multiple Queues \n");
printf("\n 1. Insert in a Queue");
printf("\n 2. Delete from a Queue");
printf("\n 3. Print from a Queue");
printf("\n 3. Exit \n");
printf("\n Select proper option ( 1 / 2 / 3 / 4) : ");
scanf("%d", &option);
switch(option) {
case 1 : //... Insert
qno = getQueueNumber(n);
printf("\n Enter Data : ");
scanf("%d", &data);
reply = insq(queue, qno-1, r, limit, &data);
if( reply == -1)
printf("\n Queue %d is Full \n", qno);
else
printf("\n %d is inserted in a Queue No. %d \n", data, qno);
break;
case 2 : //... Delete
qno = getQueueNumber(n);
reply = delq(queue, qno-1, f, r, &data);
if( reply == -1)
printf("\n Queue %d is Empty \n", qno);
else
printf("\n %d is deleted from Queue No. %d \n", data, qno);
break;
case 3:
qno = getQueueNumber(n);
printf("\n Elements of Queue %d are as : ", qno);
if (f[qno-1]==r[qno-1]) {
printf("\n Queue is empty");
break;
}
for (i=f[qno-1]+1; i<=r[qno-1]; i++)
printf("%d\t", queue[i]);
printf("\n");
break;
case 4 :
break;
default:
printf("\n Invalid input. Please try again.");
} // switch
}while(option!=4);
} // main

C language that will accept a Graph as input and will generate its Minimum Cost Spanning Tree

‪#‎include‬<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
clrscr();
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
getch();
}

Windows Firewalls

A firewall is a network security system, either hardware- or software-based, that controls incoming and outgoing network traffic based on a set of rules. Acting as a barrier between a trusted network and other untrusted networks -- such as the Internet -- or less-trusted networks -- such as a retail merchant's network outside of a cardholder data environment -- a firewall controls access to the resources of a network through a positive control model. This means that the only traffic allowed onto the network defined in the firewall policy is; all other traffic is denied.
Packet firewalls
==============
The earliest firewalls functioned as packet filters, inspecting the packets that are transferred between computers on the Internet. When a packet passes through a packet-filter firewall, its source and destination address, protocol, and destination port number are checked against the firewall's rule set. Any packets that aren't specifically allowed onto the network are dropped (i.e., not forwarded to their destination). For example, if a firewall is configured with a rule to block Telnet access, then the firewall will drop packets destined for TCP port number 23, the port where a Telnet server application would be listening.
Stateful firewalls
=============
In order to recognize a packet's connection state, a firewall needs to record all connections passing through it to ensure it has enough information to assess whether a packet is the start of a new connection, a part of an existing connection, or not part of any connection. This is what's called "stateful packet inspection." Stateful inspection was first introduced in 1994 by Check Point Software in its FireWall-1 software firewall, and by the late 1990s, it was a common firewall product feature.
This additional information can be used to grant or reject access based on the packet's history in the state table, and to speed up packet processing; that way, packets that are part of an existing connection based on the firewall's state table can be allowed through without further analysis. If a packet does not match an existing connection, it's evaluated according to the rule set for new connections.
Application-layer firewalls
====================
As attacks against Web servers became more common, so too did the need for a firewall that could protect servers and the applications running on them, not merely the network resources behind them. Application-layer firewall technology first emerged in 1999, enabling firewalls to inspect and filter packets on any OSI layer up to the application layer.
The key benefit of application-layer filtering is the ability to block specific content, such as known malware or certain websites, and recognize when certain applications and protocols -- such as HTTP, FTP and DNS -- are being misused.
Firewall technology is now incorporated into a variety of devices; many routers that pass data between networks contain firewall components and most home computer operating systems include software-based firewalls. Many hardware-based firewalls also provide additional functionality like basic routing to the internal network they protect.
Proxy firewalls
===========
Firewall proxy servers also operate at the firewall's application layer, acting as an intermediary for requests from one network to another for a specific network application. A proxy firewall prevents direct connections between either sides of the firewall; both sides are forced to conduct the session through the proxy, which can block or allow traffic based on its rule set. A proxy service must be run for each type of Internet application the firewall will support, such as an HTTP proxy for Web services.

SPOOLING

Acronym for simultaneous peripheral operations on-line, spooling refers to putting jobs in a buffer, a special area in memory or on a disk where a device can access them when it is ready. Spooling is useful because devices access dataat different rates.
Spooling is a process in which data is temporarily held to be used and executed by a device, program or the system. Data is sent to and stored in memory or other volatile storage until the program or computer requests it for execution.

Duality Principle

The duality property of Boolean algebra state that all binary expressions remain valid when following two steps are performed:
Step 1 : Interchange OR and AND operators.
Step 2 : Replace all 1’s by 0’s and 0’s by 1’s.

Huntington Postulates

Adding a number to ‘0’ :
P1. Postulate:- x + 0 = x, next From duality of P1
P2. Postulate:- x * 1 = x
Sum of a number and its complement from a Set is ‘1’.
P3. Postulate:- x + x’= 1, next From duality of P3
P4. Postulate:- x * x’ = 0
From commutative property of binary numbers we have:-
P5. Postulate:- x + y = y + x
From duality of P5
P6. Postulate:- x * y = y * x
From distributive property of binary numbers we have:-
P7. Postulate:- x(y + z) = xy + xz
From duality of P7

Consensus theorem

Boolean algebra: XY + X'Z + YZ = XY + X'Z where YZ, the algebraically redundant term, is called the "consensus term", or its dual form (X + Y)(X' + Z)(Y + Z) = (X + Y)(X' + Z), in which case Y + Z is the consensus term. (Note: X+Y, X'+Z \vdash Y+Z is an example of the resolution inference rule (replacing the + with \vee and the prime with prefix \neg might make this more evident).)

Shannon Expansion Theorem

The Shannon Expansion Theorem is used to expand a Boolean logic function (F) in terms of (or with respect to) a Boolean variable (X), as in the following forms.

space.gif
F = X . F (X = 1) + X' . F (X = 0)

space.gif
where F (X = 1) represents the function F evaluated with X set equal to 1; F (X = 0) represents the function F evaluated with X set equal to 0.

space.gif
Also the following function F can be expanded with respect to X,

space.gif
F = X' . Y + X . Y . Z' + X' . Y' . Z

space.gif
= X . (Y . Z') + X' . (Y + Y' . Z)

space.gif
Thus, the function F can be split into two smaller functions.

space.gif
F (X = '1') = Y . Z'

space.gif
This is known as the cofactor of F with respect to X in the previous logic equation. The cofactor of F with respect to X may also be represented as F X (the cofactor of F with respect to X' is F X' ). Using the Shannon Expansion Theorem, a Boolean function may be expanded with respect to any of its variables. For example, if we expand F with respect to Y instead of X,

space.gif
F = X' . Y + X . Y . Z' + X' . Y' . Z

space.gif
= Y . (X' + X . Z') + Y' . (X' . Z)

space.gif
A function may be expanded as many times as the number of variables it contains until the canonical form is reached. The canonical form is a unique representation for any Boolean function that uses only minterms. A minterm is a product term that contains all the variables of F such as X . Y' . Z).

PROLOG Program for Merge sort

mergesort([],[]).
mergesort([A],[A]).
mergesort([A,B|R],S) :- 
split([A,B|R],L1,L2),
mergesort(L1,S1),
mergesort(L2,S2),
merge(S1,S2,S).
split([],[],[]).
split([A],[A],[]).
split([A,B|R],[A|Ra],[B|Rb]) :- split(R,Ra,Rb).
merge(A,[],A).
merge([],B,B).
merge([A|Ra],[B|Rb],[A|M]) :- A =< B, merge(Ra,[B|Rb],M).
merge([A|Ra],[B|Rb],[B|M]) :- A > B, merge([A|Ra],Rb,M).

HEAP SORT using C++

‪#‎include‬<stdio.h>
#include<conio.h>
int heapSize = 10;
void print(int a[])
{
for (int i = 0; i <= 9; i++)
{
printf(" %d - ",a[i]);
}
printf("\n");
}
int parent(int i)
{
if(i==1)
return 0;
if(i%2==0)
return ( (i / 2)-1);
else
return ( (i / 2));
}
int left(int i)
{
return (2 * i) + 1;
}
int right(int i)
{
return (2 * i) + 2;
}
void heapify(int a[], int i)
{
int l = left(i), great;
int r = right(i);
if ( (a[l] > a[i])&&(l < heapSize))
{
great = l;
}
else
{
great = i;
}
if ( (a[r] > a[great])&&(r < heapSize))
{
great = r;
}
if (great != i)
{
int temp = a[i];
a[i] = a[great];
a[great] = temp;
heapify(a, great);
}
}
void BuildMaxHeap(int a[])
{
for (int i = (heapSize - 1) / 2; i >= 0; i--)
{
heapify(a, i);
print(a);
}
}
void HeapSort(int a[])
{
BuildMaxHeap(a);
for (int i = heapSize; i > 0; i--)
{
int temp = a[0];
a[0] = a[heapSize - 1];
a[heapSize - 1] = temp;
heapSize = heapSize - 1;
heapify(a, 0);
}
}
void main()
{
int arr[] = {2, 9, 3, 6, 1, 4, 5, 7, 0, 8};
//int arr[
HeapSort(arr);
print(arr);
}

INSERTION SORT using C++

‪#‎include‬<stdio.h>
int fill_array(int a[], int size, int& n);
void insertion_sort(int a[], int size, int n);
void count_array(int a[], int counter[], int n);
int count = 0;
int main()
{
printf("\nThis program sorts numbers from lowest to highest.\n");
int a[100], n;
int counter[100] = {0};
fill_array(a, 100, n);
count_array(a, counter, n);
insertion_sort(a, 100, n);
printf("\n");
printf("\n");
printf("Numbers\t");
printf("Times \n");
for (int i = 0; i< n; i++)
{
printf("%d ",a[i]);
printf("%d",counter[i]);
}
printf("\n");
printf("\n");
printf("\nYou entered %d numbers",count);
return 0;
}
int fill_array(int a[], int size, int& n)
{
printf("\nEnter up to %d nonnegative whole numbers.\n",size);
printf("Mark the end of the list with a negative number.\n");
int next, i= 0;
scanf("%d",&next);
while ((next >= 0) && (i< size))
{
a[i] = next;
i++;
scanf("%d",&next);
count++;
}
n=i;
return count;
}
void insertion_sort(int a[], int size, int n)
{
int key,i;
for (n=1; n<size; n++)
{
key=a[n];
i=n-1;
while(a[i]>key && i>=0)
{
a[i+1]=a[i];
i--;
}
a[i+1]=key;
}
}
void count_array(int a[], int counter[], int n)
{
for(int i=0; i<n; i++)
{
for(int j=0;j<n;j++)
{
if(a[i]==a[j])
counter[i]++;
}
}
}

Standard vs Canonical Forms

Standard form: In a standard form we don’t have to compulsorily write all the literals in all the terms of an expression.
e.g. f = xyz + y + x
f = x’y’z’ + x’yz
f= xy + x’y’
Canonical form: In a canonical form we have to compulsorily write all the literals in all the terms of an expression.
e.g. xyz+x’y’z+x’y’z’
xy+yz+x’y’ (for 2 variables)
x+y (for 1 variable)
xyz+xyz’
but xy + x & xyz+x’yz+xz are not a canonical term (as in last terms of both expressions we don’t have all the literals)
We can represent the expressions using min terms or max terms but we first convert standard form of expression to canonical form and then we write the expression in terms of min or max terms
Q- f= xyz+xy’
f=xyz+xy’.1 = xyz + xy’. (z+z’) = xyz + xy’z + xy’z’ = m7 + m5 + m4 = ∑(4, 5, 7)

Linear Searching using C Programming

‪#‎include‬<stdio.h>
#include<conio.h>
void main()
{
int a[15],i,n;
int ele,temp=0,pos=0;
clrscr();
printf("\nEnter the term: ");
scanf("%d",&n);
printf("\nEnter the array elements: ");
for (i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the element to be search: ");
scanf("%d",&ele);
// searching for the element
for (i=0; i<n; i++)
{
if (a[i]==ele)
{
temp=1;
pos=i;
}
}
if (temp==1)
{
printf("Element found %d , position==%d",ele,pos);
}
else
{
printf("Element not found\n");
}
getch();
}

Bubble Sorting using C programming

‪#‎include‬<stdio.h>
#include<conio.h>
int main( )
{
int a[100];
int i, j, temp, n ;
printf("\nHow many numbers you want to sort : \n");
scanf("%d",&n);
printf("Enter %d number values you want to sort\n", n);
for(j=0; j<n; j++)
{
scanf("%d",&a[j]);
}
for(j=1;j<n;j++)
{
for(i=0; i<n-j; i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <n ; i++ )
printf ( "%d\t", a[i] ) ;
getch();
}

C program to check whether a number is prime or not.

‪#‎include‬ <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}

String Palindrome Checking using C Programming

‪#‎include‬<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[20];
int flag=0,i,l;
clrscr();
printf("enter any string\n");
gets(st);
l=strlen(st);
for(i=0;i<l/2;i++)
if(st[i]!=st[l-1-i])
{
flag=1;
break;
}
if(flag==0)
printf("String is Palindrom");
else
printf("String is not palindrom\n");
getch();
}

Defined a class to represent a bank account with data member : name of the depositor,account number,type of account,balance and member functions : deposit_amount and withdraw_amount. show name and balance.Write a program to test this

‪#‎include‬<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
class bank_account
{
char name_of_the_depositor[25];
int account_number;
char type_of_account[15];
int balance;
int count;
public:
void cnt(void){count=0;}
void deposit_amount(void);
void withdraw_amount(char name,char acc,int w);
};
void bank_account::deposit_amount(void)
{
cout<<"\nEnter the name of the depositor : ";
fflush(stdin);
gets(name_of_the_depositor);
//cin>>name_of_the_depositor;
cout<<"\n\nEnter the account number : ";
cin>>account_number;
cout<<"\n\nType of account : ";
cin>>type_of_account;
cout<<"\n\nDeposit amount : ";
cin>>balance;
count++;
cout<<"\n";
cout<<"\nCONGRATULATION..!!Informations are saved.\n";
cout<<"\n\n\nDatabase : ";
cout<<"\n----------\n";
for(int i=0;i<count;i++)
{
cout<<"\nName : ";
cout<<name_of_the_depositor;
cout<<"\n\nAccount number : ";
cout<<account_number;
cout<<"\n\nType of account : ";
cout<<type_of_account;
cout<<"\n\nDeposited amount : ";
cout<<balance;
cout<<"\n\n";
}
}
/*void bank_account::withdraw_amount(char name,char acc,int w)
{
int i;
for(i=0;i<count;i++)
{
if((name_of_the_depositor[i]==name)&&(account_number[i]==acc))
{
balance[i]=balance[i]-w;
cout<<"\n\nName of the depositor : "<<name_of_the_depositor[i];
cout<<"\n\nAfter withdrawal,now the balance is : "<<balance[i];
}
cout<<"\n\n";
}
}*/
int main()
{
bank_account b[50];
//b.cnt();
int ch,num,acc,w,i;
char name;
clrscr();
while(ch!=0)
{
cout<<"\n*====================BANK DATABASE===================*\n";
cout<<"\n Press 1 to deposit amount";
cout<<"\n Press 2 to withdraw amount";
cout<<"\n Press 0 to exit from menu";
cout<<"\n\nEnter your choice : ";
cin>>ch;
switch(ch)
{
case 1: cout<<"\n\n\nEnter the following datas to deposit amount :";
cout<<"\n---------------------------------------------\n";
for(i=0;i<50;i++)
b[i].deposit_amount();
break;
case 2: cout<<"\n\n\nEnter the name & account no. to withdraw amount : ";
cout<<"\n-------------------------------------------------\n";
cout<<"\nEnter name : ";
cin>>name;
cout<<"\n\nEnter account number : ";
cin>>acc;
cout<<"\n\nEnter the amount you want to withdraw : ";
cin>>w;
cout<<"\n\n";
b[i].withdraw_amount(name,acc,w);
break;
case 0: cout<<"\n Exit";
break;
default: cout<<"\n Sorry.......Invalid choice.Try again";
}
}
return 0;
}

Mastermind for beginners

// Note : Results
// 2 = correct position, correct number
// 1 = wrong position, correct number
// 0 = wrong position, wrong number

‪#‎include‬ <iostream.h>
int guess[4], given[4];
int x,y,n,lup,lup1;
int checking[4];
int main()
{
x = 0;
// user will give the correct combination
for (lup=1;lup<5;lup++)
{
cout<<"Enter given for " <<lup<< " place \t";
cin>>given[x];
x++;
}
lup1 = 1;
// user will guess the correct combination
for (y=0;y<4;y++)
{
cout<< "Enter guess for "<< lup1<<"\t";
cin>> guess[y];
// program will compare the "guess" with all the combination
if (guess[y] == given[y])
{
// guess is both correct in position and number
checking[y] = 2;
}
else
{
for (x=0;x<4;x++)
{
if(guess[y]== given[x])
{
//guess is just correct in number but position is wrong
checking[y] = 1;
}

}
}

lup1++;
// display the results
}
cout << "results:" <<"\n";
for (n=0;n<4;n++)
{
cout <<checking[n]<<"\t";
}
cout<<endl;
return 0;
}

FORTRAN Program of Fibonacci Numbers

c Fobonacci sequence
integer f1,f2,f3
f1=1
f2=1
write(*,*)'To display fibonacci numbers.'
write(*,*)'Enter the number of terms to be displayed:'
read(*,*)n
write(*,*)'The fibonacci sequence is : '
IF(n.EQ.1)THEN
write(*,10)f1
10 format(1x,I6)
ELSE
write(*,10)f1
write(*,10)f2
DO 20 i=3,n
f3=f1+f2
write(*,10)f3
f1=f2
f2=f3
20 continue
ENDIF
STOP
END

FORTRAN Program of Fibonacci Numbers

*INTITIALIZE
M = 0
N = 0
J = 0
I = 0
K = 0
DONE = 1
VALID = 1
*LOOP UNTIL USER CHOOSES TO QUIT
DO WHILE(DONE .GT. 0)
*DISPLAY MENU UNTIL VALID ENTRY IS ENTERED
DO WHILE (VALID .GT. 0)
*PRINT MENU
PRINT *,'MATRIX CALCULATOR'
PRINT *,'PLEASE MAKE A SELECTION'
PRINT *,'1) MATRIX ADDITION'
PRINT *,'2) MATRIX SUBTRACTION'
PRINT *,'3) MATRIX MULTIPLICATION'
PRINT *,'4) MATRIX TRANSPOSE'
PRINT *,'5) QUIT PROGRAM'
READ (*,*) SELECTION
*VALID ENTRY CHECK
IF (SELECTION .GT. 5 .OR. SELECTION .LT. 1) THEN
PRINT *,'PLEASE ENTER A VALID SELECTION'
ELSE
VALID= -1
END IF
*END WHEN VALID ENTRY IS ENTERED
END DO
*QUIT?
IF (SELECTION .EQ. 5) THEN
DONE = -1
ELSE
*OTHERWISE CONTINUE
*GET DIMENTIONS INPUT
PRINT *,'PLEASE ENTER THE DIMENTIONS'
PRINT *,'ENTER IN M:'
READ (*,*) M
PRINT *,'ENTER IN N:'
READ (*,*) N
*GET IN MATRIX
PRINT *, 'PLEASE ENTER IN MATRIX A'
DO J=1, M
DO I=1, N
PRINT *, 'ENTER IN VALUE I, I', J, I
READ(*,*) A(M,N)
END DO
END DO
PRINT *, 'PLEASE ENTER IN MATRIX B'
DO J=1, M
DO I=1, N
PRINT *, 'ENTER IN VALUE I, I', J,I
READ(*,*) B(M,N)
END DO
END DO
*PERFORM DESIRED CALCULATION
SELECT CASE(SELECTION)
*CASE 1
CASE (1)
PRINT *,'MATRIX ADDITION'
DO J=1,M
DO I=1,N
SUM(J,I)=A(J,I)+B(J,I)
END DO
END DO
*PRINT ADDITION RESULT
PRINT *,'ADDITION RESULT'
DO J=1, M
DO I=1, N
WRITE (*,*) SUM(J,I)
END DO
END DO
*CASE 2
CASE (2)
PRINT *,'MATRIX SUBTRACTION'
DO J=1,M
DO I=1,N
SUM(J,I)=A(J,I)-B(J,I)
END DO
END DO
*PRINT SUBTRACTION RESULT
PRINT *,'SUBTRACTION RESULT'
DO J=1, M
DO I=1, N
WRITE (*,*) SUM(J,I)
END DO
END DO
*CASE 3
CASE (3)
PRINT *,'MATRIX MULTIPLICATION'
DO J=1, M
DO I=1, N
DO K=1, N
SUM(J,I) = SUM(J,I)+A(J,K)*B(I,J)
END DO
END DO
END DO
*PRINT MULTIPLICATION RESULT
DO J=1, M
DO I=1, N
WRITE (*,*) SUM(J,I)
END DO
END DO
*CASE 4
CASE (4)
PRINT *,'MATRIX TRANSPOSE'
DO J=1, M
DO I=1, N
B(I,J) = A(J,I)
END DO
END DO
*PRINT TRANSPOSE RESULT
PRINT *, 'MATRIX A RESULT'
DO J=1, M
DO I=1, N
WRITE (*,*) A(J,I)
END DO
END DO
PRINT *, 'MATRIX B RESULT'
DO J=1, M
DO I=1, N
WRITE (*,*) B(J,I)
END DO
END DO
CASE DEFAULT
PRINT *,'SOMETHING HAS GONE WRONG'
END SELECT
*USER SELECTED TO QUIT
END IF
END DO
PRINT *, 'PROGRAM HAS ENDED'
*END PROGRAM
STOP
END

C program to shutdown or turn off computer

***C programming code for Windows XP:
‪#‎include‬ <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Do you want to shutdown your computer now (y/n)\n");
scanf("%c", &ch);
if (ch == 'y' || ch == 'Y')
system("C:\\WINDOWS\\System32\\shutdown -s");
return 0;
}
***C programming code for Windows 7:
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("C:\\WINDOWS\\System32\\shutdown /s");
return 0;
}
***C programming code for Ubuntu Linux:
#include <stdio.h>
int main() {
system("shutdown -P now");
return 0;
}

C program to change Background Color

‪#‎include‬<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
outtext("Press any key to change the background color to GREEN.");
getch();
setbkcolor(GREEN);
getch();
closegraph();
return 0;
}

C program for toggling of Characters of a string, like ComPuter-> output : cOMpUTER

‪#‎include‬<stdoi.h>
int main()
{
char name[100];
int loop;
printf("Enter any Sting: ");
fgets(name,sizeof(name),stdin);
for (loop=0; name[loop] !=0; loop++)
{
if(name[loop]>='A' && name[loop]<='Z')
name[loop]=name[loop]+32;
else if(name[loop]>='a' && name[loop]<='z')
name[loop]=name[loop]-32;
}
printf("\nConvert case of character : %s",name);
return 0;
}

C program to create a directory/folder

‪#‎include‬<stdio.h>
#include<conio.h>
#include<process.h>
#include<dir.h>
void main() {
int check;
char *dirname;
clrscr();
printf("Enter a directory path and name to be created (C:/name):");
gets(dirname);
check = mkdir(dirname);
if (!check)
printf("Directory created\n");
else
{
printf("Unable to create directory\n");
exit(1); }
getch();
system("dir/p");
getch();
}

The 3 Myths of Learning Programming Languages

Myth 1: Programming Languages are the ‘Languages of Computers’
A quick Google search reveals that people are saying things like this…
How do I get fluent in Python?
These people apparently think that learning a language like Python means…
learning to ‘speak to the computer’,
learning to ‘think like a computer’, and
becoming ‘fluent’ in a language not ‘native’ to them.
They’re wrong.
In fact, the vast majority of the time, programming languages are designed exclusively for people like you and me.
Here’s why…
In the context of computer science, there are low-level programming languages and high-level programming languages.
A low-level language like assembly language actually does speak to a computer directly – performing a long series of processor operations, one byte at a time.
But assembly language is only the 19th most used programming language in the world today. The vast majority of modern programmers write only in high-level languages like Python.
Here is the Collins English Dictionary definition of ‘high-level language':
a computer programming language that resembles natural language or mathematical notation…
High-level languages resemble natural language, and use concepts like mathematics and logic, because they are designed to be easy for humans to understand, not computers.
Learning one of these high-level languages doesn’t mean learning to ‘speak to a computer’. The whole reason they exist is so that we don’t have to.
So if high-level languages are designed to be easy for us to understand, what does one actually look like? Continue reading to see an example…
Myth 2: Programming Languages are Foreign and Hard to Read
If you were to attempt to read some text written in a language foreign to you, you may be faced with…
a different alphabet to the one you’re familiar with,
unfamiliar grammar rules and syntax,
and most dauntingly, a whole new set of words you’ve never seen.
But if you were to read some high-level programming language code, you’d be faced with none of those things.
Let me prove it to you…
Take a look at this code written in a programming language called SQL:
INSERT INTO Table
VALUES ('1', 'SQL', 'Programming language')
For the purpose of this example, let’s assume your primary tongue is English, and we’ll compare that to SQL.
Firstly, the alphabet is most certainly not foreign. All the characters used can be found on a standard Roman alphabet keyboard.
Secondly, look at the grammar rules and syntax. While there’s a bit of deviance, ‘insert into table’ is familiar and readable. As an English speaker, you’d have little trouble figuring out the meaning of the code.
Lastly, look at the words. Every word there is pre-existing in the English language. No foreign words, no difficult pronunciations, no scratching your head working out the meaning of each word.
Granted, programming languages do invent abbreviations – such as regex (regular expression) and varchar (variable character), just to name a few.
But at the end of the day, the full ‘lexicon’ of a programming language is derived entirely from a real-world language – whether that be English or any other tongue.
This is why programming languages aren’t languages at all. In fact, you could say programming languages are really more like dialects than languages.
Learning your first programming language now doesn’t seem so hard as learning a real-world language. And as you’ll see next, it doesn’t take as long either…
Myth 3: Programming Languages Take Years to Learn
To learn a foreign language, you need to learn…
the vocabulary (so that you have the words to express your ideas),
the grammar (to be able to string them together into sentences), and
the ability to read, listen, pronounce and speak.
That’s a lot.
So it comes as no surprise that it can range from 23 weeks up to 1.7 years, and beyond, for an average native English speaker to pick up a new foreign language.
Learning a programming language would probably take just as long, if not longer – if they truly were designed with computers in mind, and were foreign and hard to read.
But we already know that’s not true…
Learning the commands and functions of a programming language (the equivalent of learning the vocabulary of a real-world language) is made a lot easier by the fact that programming languages use the same words as an existing language (almost always English).
Assuming you speak this language, that’s a huge chunk of learning time eliminated.
Similarly, learning to read the language is not such a big deal. All the words will be familiar to you, and as we’ve seen, deciphering programming language code is not that hard.
Learning the syntax of a programming language (the equivalent of learning the grammar of a real-world language) isn’t quite so easy – but remember that high-level programming languages are designed to be easily understood, so it’s not ridiculously hard either.
Finally, the challenges of learning how to listen, pronounce and speak are literally non-existent. I don’t know about you, but I’ve never heard anyone speak out loud in a programming language.
So as you can see, there’s not nearly as much to learn in a programming language as there is in a real-world language. And less to learn means less time needed to learn.
In fact, there are stories online of people who have learnt a programming language and achieved results in mere months, even as little as 12 weeks.
Years? I don’t think so.
Bottom Line…
Programming languages are easy to read, quick to learn and designed with people like you in mind.
So why not make today the day you finally learn your first programming language? After all, now you have no excuses left!

C Program to mask password text with *

‪#‎include‬ <stdio.h>
#include <conio.h>
void main()
{
char pasword[10],usrname[10], ch;
int i;
clrscr();
printf("Enter User name: ");
gets(usrname);
printf("Enter the password <any 8 characters>: ");
for(i=0;i<8;i++)
{
ch = getch();
pasword[i] = ch;
ch = '*' ;
printf("%c",ch);
}
pasword[i] = '\0';
/*If you want to know what you have entered as password, you can print it*/
printf("\nYour password is :");
for(i=0;i<8;i++)
{
printf("%c",pasword[i]);
}
}

get double error and warnings in c

#include <stdio.h>
 int main(void) {
double f = 5000000000.0;  //double precision constant created because of “.”
double g = 5000000000; //constant is integer or long integer but 2,147,483,647 is the maximum!
printf("f=%lf\n", f);
printf("g=%lf\n", g);
return 0;
}

o/p:

f=5000000000.000000
 g=705032704.000000 // OVERFLOW

Simple Human Face in C Graphics Programming

‪#‎include‬<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"");
setbkcolor(WHITE);
setcolor(RED);
ellipse(320,240,160,380,60,80);
/*Hairs*/
arc(322,215,400,140,80);
ellipse(377,186,270,438,10,28);
arc(379,184,169,265,30);
ellipse(267,186,438,270,10,28);
arc(269,184,265,361,30);
ellipse(326,184,180,360,26,20);
/*Eye brows*/
arc(296,256,89,130,40);
arc(292,260,80,120,40);
line(298,215,298,219);
arc(334,256,405,92,40);
arc(339,260,420,100,40);
line(330,215,330,221);
circle(312,214,3);
setfillstyle(SOLID_FILL,RED);
floodfill(312,214,RED);
/*Eyes*/
ellipse(286,235,0,360,10,4);
ellipse(340,235,0,360,10,4);
circle(286,235,2);
circle(340,235,2);
/*Nose*/
ellipse(300,220,270,0,10,40);
ellipse(325,220,180,270,10,40);
ellipse(305,260,100,285,8,7);
ellipse(320,260,255,70,8,7);
arc(314,260,228,689,10);
/*Lips*/
ellipse(315,290,0,360,20,7);
line(295,290,335,290);
/*Ears*/
ellipse(255,234,0,330,4,20);
ellipse(385,234,220,170,4,20);
settextstyle(1,HORIZ_DIR,3);
setcolor(BLUE);
outtextxy(255,350,"HUMAN FACE");
getch();
closegraph();
}

C smiling face animation

‪#‎include‬<graphics.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int gd = DETECT, gm, area, temp1, temp2, left = 25, top = 75;
void *p;
initgraph(&gd,&gm,"C:\\TC\\BGI");
setcolor(YELLOW);
circle(50,100,25);
setfillstyle(SOLID_FILL,YELLOW);
floodfill(50,100,YELLOW);
setcolor(BLACK);
setfillstyle(SOLID_FILL,BLACK);
fillellipse(44,85,2,6);
fillellipse(56,85,2,6);
ellipse(50,100,205,335,20,9);
ellipse(50,100,205,335,20,10);
ellipse(50,100,205,335,20,11);
area = imagesize(left, top, left + 50, top + 50);
p = malloc(area);
setcolor(WHITE);
settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2);
outtextxy(155,451,"Smiling Face Animation");
setcolor(BLUE);
rectangle(0,0,639,449);
while(!kbhit())
{
temp1 = 1 + random ( 588 );
temp2 = 1 + random ( 380 );
getimage(left, top, left + 50, top + 50, p);
putimage(left, top, p, XOR_PUT);
putimage(temp1 , temp2, p, XOR_PUT);
delay(100);
left = temp1;
top = temp2;
}
getch();
closegraph();
return 0;
}

C program to check whether a Matrix is magic Square or not. What is Magic Square?

A magic square is a simple mathematical game developed during the 1500. Square is divided into equal number of rows and columns. Start filling each square with the number from 1 to num ( where num = No of Rows X No of Columns ). You can only use a number once. Fill each square so that the sum of each row is the same as the sum of each column. In the example shown here, the sum of each row is 15, and the sum of each column is also 15.
In this Example : The numbers from 1 through 9 is used only once. This is called a magic square.
‪#‎include‬<stdio.h>
#include<conio.h>
int main() {
int size = 3;
int matrix[3][3]; // = {{4,9,2},{3,5,7},{8,1,6}};
int row, column = 0;
int sum, sum1, sum2;
int flag = 0;
printf("\nEnter matrix : ");
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++)
scanf("%d", &matrix[row][column]);
}
printf("Entered matrix is : \n");
for (row = 0; row < size; row++) {
printf("\n");
for (column = 0; column < size; column++) {
printf("\t%d", matrix[row][column]);
}
}
//For diagonal elements
sum = 0;
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++) {
if (row == column)
sum = sum + matrix[row][column];
}
}
//For Rows
for (row = 0; row < size; row++) {
sum1 = 0;
for (column = 0; column < size; column++) {
sum1 = sum1 + matrix[row][column];
}
if (sum == sum1)
flag = 1;
else {
flag = 0;
break;
}
}
//For Columns
for (row = 0; row < size; row++) {
sum2 = 0;
for (column = 0; column < size; column++) {
sum2 = sum2 + matrix[column][row];
}
if (sum == sum2)
flag = 1;
else {
flag = 0;
break;
}
}
if (flag == 1)
printf("\nMagic square");
else
printf("\nNo Magic square");
return 0;
}
Output :
Enter matrix : 4 9 2 3 5 7 8 1 6
Entered matrix is :
4 9 2
3 5 7
8 1 6
Magic square
1
2
3
4
5
6
Enter matrix : 4 9 2 3 5 7 8 1 6
Entered matrix is :
4 9 2
3 5 7
8 1 6
Magic square
Note :
Sum of Row1 = Sum of Row2 [Sum of All Rows must be Same]
Sum of Col1 = Sum of Col2 [Sum of All Cols must be Same]
Sum of Left Diagonal = Sum of Right Diagonal
1
2
3
Sum of Row1 = Sum of Row2 [Sum of All Rows must be Same]
Sum of Col1 = Sum of Col2 [Sum of All Cols must be Same]
Sum of Left Diagonal = Sum of Right Diagonal