Basics of Pointers :-
Definition :-
The pointer is nothing but an address. The pointers are useful for indirect access. The pointers are useful for the implementation of call by address.
Declaration of pointer variable –
The general syntax of declaring pointer variable is as follows:-
datatype * pointername
for e.g.
int * p ;
float * q ;
char * r ;
In the above declaration the p will act as pointer to integer, the ‘q’ will act as pointer to float and the ‘r’ will act as pointer to char. In other words the p will store address of integer the ‘q’ will store address of float and the ‘r’ will store address of char.
Referencing and De-referencing :-
The address of operator (&) is used for referencing and the indirection operator (*) is used for. De-referencing. To understand the concept of referencing and de-referencing let us consider the following example.
# include
void main ( )
{
int x = 7 ;
int * p ;
p = & x
cout << * p << “ is stored at address ” << p << ‘ \n ’ ;
}
1) In the above pgm the p is declared as pointer to integer.
2) Consider the statement, p = & x ; In this statement. We are using address of operator i.e & due to this statement the address of x is copied in to p. In other words the p will store address of x i.e. p will act as pointer to x i.e. p will act as reference to x. This process is called as referencing. This is because it is possible to access x with its reference i.e. address i.e. pointer i.e. p.
3) In the cout statement we are printing the value of * p. The operator * is nothing but indirection operator. The indirection operator operates on address i.e. reference and gives value stored at that address. Since p stores the address of x, the value of * p is nothing but the value of x. thus we can refer x indirectly as * p and hence the indirection operator. We can also say that by applying the indirection operator on the pointer p i.e. reference p we are getting the original value of x hence this
concept is called as de-referencing. Hence the operator * is called as de-referencing operator.
Write the output of the following program:-
# include
void main ( )
{
Int x = 7, y ;
int * p, * q ;
P = & x ;
q = & y;
* q = * p + 100 :
cout ‘\t’ ‘<< * p << ‘\n’ ;
cout << y << ‘\t’ << * q << ‘\n’ ;
Pointer to pointer :-
The general syntax of declaring pointer is as follows.
dataype * * pointer name
The e.g. will be as follows
int ** p ;
In the above example the p is pointer to pointer integer. In other words the p stores address of address of integer.
Write the output of the following pgm
# include
void main ( )
{
int x = 7 ;
int * p ;
int * * q ;
p = & x ;
q = & p ;
cout << x << “ is stored at ” << p << ‘ \n ’ ;
cout << * p << “ is stored at ” << p << ‘ \n ’ ;
cout << * * q << “ is stored at ” << * q << ‘ \n ’ ;
cout << * q << “ is stored at ” << q << ‘ \n ’ ;
}
Call by value / Pass by value / Parameter passing by value –
# include
void main ( )
{
int x = 7, y = 5 ;
void swap ( int, int ) ;
cout << “Before exchange = ” ;
cout << “ x = ” << x << “ , ” << “ y = ” << y << ‘ \n ’ ;
swap ( x, y ) ;
cout << “After exchange = ” ;
cout << “ x = ” << x << “ , ” << “ y ” << y << ‘\n’ ;
}
void swap( int p, int q)
{
int temp ;
temp = p ;
p = q ;
q = temp ;
}
Output :-
Before exchange
x = 7, y = 5
After exchange
x = 7, y = 5
When the swap ( ) is called, then the values of actual parameters x & y are passed and copied into formal parameters i.e. p and q. Hence the concept is referred as call by value or pass by value. The actual parameters and formal parameters occupy separate memory locations and hence exchange taking place in p and q will not cause changes in x and y. Thus call by value is useful for one-way communication through parameters.
Call by Address / call by pointer / call by reference:-
# include
void main ( )
{
int x = 7, y = 5 ;
void swap ( int *, int *)
cout << “ Before exchange = ” ;
cout << “ x = ” << x << “ , ” << “ y = ” << y << ‘ \n ’ ;
swap (&x, &y) ;
cout << “After exchange = ” ;
cout << “ x ” < } Void swap ( int * p , int * q ) { int temp ; temp = * p ; * p = * q; * q = temp; } Output: - Before exchange x = 7, y = 5 After exchange x = 5, y = 7 1) When the swap ( ) is called. Then the address of x & y i.e. in other words reference of x & y are passed as parameters. Hence the concept is called as call by reference or call by address or pass by reference or pass by address. When the swap ( ) is called, the address of x and y are copied in to pointer variable named as p and q. The logic within the swap ( ) exchanges the value of variables which are being pointed by p and q. Thus with the help of reference p and q and by de-referencing them, the values of x and y itself are exchanged. Thus call be address i.e. call by reference is useful for two way communication. Call by Alias // Call by Reference // Pass by Reference / Pass by Alias :- # include void main ( ) { int x =7, y=5 ; void swap( int & , int &) ; cout << “ Before exchange = ” ; cout << “ x = ” << x << “ y = ” << y << ‘ \n ’ ; swap ( x, y) ; cout << “After exchange = ” ; cout << x = “ << x << ” , “ , ” << “ y = ” << y << ‘ \n ’ ; } void swap ( int & p , int & q ) { int temp ; temp = p ; p = q ; q = temp ; } O/P :- Before exchange x = 7 , y = 5 After exchange x = 5 , y = 7 When the swap ( ) is called then x & y are passed as parameters and the formal parameters p and q will act as their alias. Hence the concept is called as call by alias or pass by alias. The p and q will act as other names of x and y. in other words we can say that p and q acts as references of x and y. hence the concept is also called as call by reference or pass by reference. One dimensional Arrays and Pointers : - One dimensional array name is written without subscript is nothing but pointer to the 0th element of the array or I other words address of the 0thelement of the array. Consider the following example: int a [ 50 ] ; Note 1 :- a ↔ & a [ 0 ] a + 0 ↔ & a [ 0 ] a + 1 ↔ & a [ 1 ] a + 2 ↔ & a [ 2 ] . . . . . . . a + i ↔ & a [ i ] Note 2 :- * ( a + i ) ↔ a [ i ] Write the out put of the following pgm : # include void main ( ) { int a [5] = {10, 20, 30, 40, 50} ; int i ,* y ; y = 0; for ( i =0 , i<5 ; i + + ) cout << y [ i ] << ‘ \t ’ ; } Out put : 10 20 30 40 50 In the above pgm, y acts as another name of array a. Write the out put of the following pgm :- # include void main ( ) { int a [ 5 ] = { 10, 20, 30, 40, 50 } ; int i ; for ( i = 0 , i < 5 ; i + + ) cout << i [ a ] << ‘ \n ’ ; } Out put : 10 20 30 40 50 * Example of two dimensional array as parameter of function. 1) Write a menu driven pgm that will provide options for addition subtraction. Multiplication of matrices and transpose of a matrix. The pgm should give facility for repeated execution till user enters the option quit. WAP with the help of modular programming approach. # include # include void main ( ) { int a [ 10 ] [ 10 ] , b [ 10 ] [10] , c [ 10 ] [ 10 ] ; int m1, n1, m2, n2, option ; void readmat ( int [ ] [ 10 ] , int , int ) void printmat ( int [ ] [ 10 ] , int , int ) void multmat ( int [ ] [ 10 ] , int [ ] [ 10 ] , int + [ ] [ 10 ] , int , int , int ) void transpose ( int [ ] [ 10 ] , int [ ] [ 10 ] int , int ) void addmat ( int [ ] [ 10 ] , int [ ] [ 10 ] , int [ ] [ 10 ] , int , int ) void subtract ( int [ ] [ 10 ] , int [ ] [ 10 ] , int [ ] [ 10 ] , int , int ) ; do { clrscr ( ) ; cout << “1 : addition\n” ; cout << “2 : subtraction\n” ; cout << “3 : multiplication\n” ; cout << “4 : transpose\n” ; cout << “5 : quit \n” ; cout << “Enter your option =” ; cin >> option ; if ( option > = 1 && option < = 3 ) { cout << “Enter order of first matrix =” ; cin >> m1 >> n1; cout << “Enter order of second matrix =” ; cin >> m2 >> n2; cout << “Enter element of first matrix =” ; readmat ( a , m1 , n1 ) ; cout << “Enter element of second matrix =” ; readmat ( b , m2 , n2 ) ; switch ( option ) { case 1 : if ( m1 = = m2 && n1 = = n2 ) { addmat ( a , b , c , m1 , n1 ) ; printmat ( c , m1 , n1 ) ; } else cout << “ order mismatch \n ” ; break ; case 2 : if ( m1 = = m2 && n1 = = n2 ) { submat ( a , b , c , m1 , n1 ) ; printmat ( c , m1 , n1 ) ; } else cout << “ order mismatch \n ” ; break ; case 3 : if ( m1 = = m2 ) { multmat ( a , b , c , m1, n2, n1 ) ; printmat ( c , m1, n2 ) ; } else cout << “ order mismatch \n ” ; break ; } else if ( option = = 4 ) { cout << “ Enter order of matrix = ” ; cin >> m1 >> n1 ; cout << “ Enter element = ” ; readmat ( a , m1 , n1 ) ; transpose ( a , b , m1 , n1 ) ; printmat ( b , m , m1 ) ; } getch ( ) ; } //closing curly brackets of do while ( option ! = 5 ) ; } void readmat ( int p[ ] [ 10 ] , int x , int y ) { int i , j ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) cin >> p[ i ] [ j ] ; } void printmat ( int p[ ] [ 10 ] , int x , int y ) { int i , j ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) cout << p [ i ] [ i ] << ‘ \t ’ : cout << ‘ \n ’ ; } } void transpose ( int p[ ] [ 10 ] , int q[ ] [ 10 ] , int x , int y ) { int i , j ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) q[ j ] [ i ] = p[ i ] [ j ] ; } void multmat ( int p[ ] [ 10 ] , int q[ ] [ 10 ] , int r [ ] [ 10 ] , int x , int y , int = ) { int i , j , k ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < x ; j + + ) r[ i ] [ j ] = 0 ; for ( k = 0 ; k < z ; k + + ) r[ i ] [ j ] = r[ i ] + [ j ] + p[ i ] [ k ] * q [ k ] [ j ] ; } void addmat ( int p[ ] [ 10 ] , int q[ ] [ 10 ] , int r [ ] [ 10 ] , int x , int y ) { int i , j ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) r[ i ] [ j ] = p[ i ] [ j ] + q[ i ] [ j ] ; } void submit (int p[ ] [ 10 ] , int q[ ] [ 10 ] , int r [ ] [ 10 ] , int x , int y ) { int i , j ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) r[ i ] [ j ] = p[ i ] [ j ] + q[ i ] [ j ] ; } } ( A x B )T = BT x AT The pgm should have following functions. → # include # include void main ( ) { int a [ 10 ] [ 10 ] , b [ 10 ] [10] , c [ 10 ] [ 10 ] ct [ 10 ] [ 10 ], bt [ 10 ] [ 10 ] , at [ 10 ] [10] , mt [ 10 ] [ 10 ] ; int m1, n1, m2, n2 ; void readmat ( int [ ] [ 10 ] , int , int ) ; void printmat ( int [ ] [ 10 ] , int , int ) ; void transpose ( int [ ] [ 10 ] : int [ ] [ 10 ] int , int ) void multmat ( int [ ] [ 10 ] , int [ ] [ 10 ] , int [ ] [ 10 ] int , int ) int equal ( int [ ] [ 10 ] , int [ ] [ 10 ] , int , int ) clrscr ( ) ; cout << “Enter order of first matrix =” ; cin >> m1 >> n1 ; cout << “Enter order of second matrix =” ; cin >> m2 >> n2 ; if ( n1 = = m2 ) { cout << “Enter element of first mat =” ; readmat ( a, m1, n1 ) cout << “Enter element of second mat =” ; readmat ( b, m2, n2 ) multmat ( a, b, c, m1, n2, n1 ) ; transpose ( c, ct, m1, n2 ) ; transpose ( b, bt, m2, n2 ) ; transpose ( a, at, m1, n1 ) ; multmat ( bt, at, mt, n2, m1, n1 ) ; cout << “ L.H.S. \n ” ; printmat ( ct, n2, m1 ) ; cout << “ R.H.S. \n ” ; printmat ( mt, n2, m1 ) ; if equal ( ct, mt, n2, m1 ) cout << “ property proved \n ” ; } else cout << “ Order mismatch \n ’ : getch ( ) ; } void readmat( int p[ ] [ 10 ] , int x , int y ) { int i, j ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) cin >> p [ i ] [ j ] ; } void printmat ( int p[ ] [10] , int x , int y ) { int i, j ; for ( i = 0 ; i < x ; i + + ) { for ( j =0 ; j < y ; j + + ) cout << p [ i ] [ j ] << ‘ \t ’ ; cout << ‘ \n ’ ; } } void transpose ( int p[ ] [10] , int q[ ] [10] , int x, int y ) { int i, j ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) q [ j ] [ i ] < p[ i ] [ j ] ; } void multmat ( int p[ ] [ 10 ] , int q[ ] [ 10 ] , int r[ ] [ 10 ] , int x , int y , int z ) ; } int i, j , k ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) { r [ i ] [ j ] = 0 ; for ( k = 0 ; k < z ; k + + ) r [ i ] [ j ] = r [ i ] [ j ] + p [ i ] [ k ] * q [ k ] [ j ] ; { int equal ( int p[ ] [ 10 ] , int q[ ] [ 10 ] , int x , int y ; { int i, j, count = 0 ; for ( i = 0 ; i < x ; i + + ) for ( j = 0 ; j < y ; j + + ) if ( p [ i ] [ j ] = = q[ i ] [ j ] ) count + + ; if ( count = = x * y ) return 1 ; else return 0 ; } Two Dimensional Array And Pointers Two dimensional array name written with out subscript is nothing but the pointer to pointer to the element in the 0th row and 0th column. Consider the following example. int a [ 3 ] [ 4 ] ; * Example of one dimensional array as parameter to function : IMP : - a [ 0 ] → 0th element of an array a. a → address of pointer to the 0th element of an array a. a) void main ( ) { int a[ 100 ] ; int i , n, x, ans ; int search ( int [ ] , int , int ) ; clrscr ( ) ; cout << “ How many elements = ” ; cin >> n ; cout << “ Enter elements = ” ; for ( i = 0 ; i < n ; i + + ) cin >> a [ i ] ; cout << “Enter the element to be searched” ; cin >> x ; ans = search ( a, n, x ) ; if ( ans = = 0 ) ; cout “ is not present ” ; else cout “ is present ” << ans << “times \n ” ; getch ( ) ; } int search ( int p[ ] , int n, int x ) { int i , count = 0 ; for ( i = 0 ; i < n ; i + + ) if ( p [ i ] = = x ) count + + ; return count ; } b) void main ( ) { int a [100] ; int i, n, x, ans ; int search (int *, int, int) ; clrscr ( ) ; cout << “How many element” ; cin > n ; cout << “Enter element =” ; for ( i = o; i < n; i + +) cin >> *( a + i) ; cout << “Enter element to be searched =” ; cin >> x ; ans = search (a, n, x) ; if (ans = = 0) cout << x << “is not present in” ; else cout << x << “is present << count <<” times \n” ; getch ( ) ; } int search (int * p, int n, int x) { int i, count = 0 ; For ( i =0; i < n; i + +) If (* ( p + i) = = x) count + + ; return count ; } 2) Write a function that accepts that accepts one dimensional array of not more than 100 integers and it should also accept the element to be searched. The function should return the position of the first occurrence of that element in the array. If the element is not present then it should return –1. Write a suitable main function that will search the element in the array using the above function use pointer notation. # include # include void main ( ) { int a [100] ; int i, n, x, ans ; int search ( int *, int , int ) clrscr ( ) ; cout << “Enter the element = ” ; for ( i = 0 ; i < n ; i + + ) cin >> * (a + i) ; cout << “Enter element to be searched =” ; cin >> x ; ans = search ( a, n, x) ; if ( and = = –1) cout << x << “is not present \n” ; else cout << x << “is present at position” << ans << ‘\n’ ; getch ( ) ; } int search ( int * p, int n, int x ) { int i = 0 ; while ( i < n & & * (p + i) ! = x) i + + ; if ( i < n ) return 1 ; else return – 1 ; } 3) Write a function that accepts a string and returns the answer indicating whether that string is palindrome or not write a suitable main function. # include # include # include # include void main ( ) { char str [80] ; int ans ; int palindrome ( char [ ] ) ; clrscr ( ) ; cout << “Enter a string =” ; gets (str) ; ans = palindrome (str) ; if ( ans = = 1) cout << “It is palindrome \n” ; else cout << “It is palindrome \n” ; getch ( ) ; } int palindrome ( char [ ]) { int i, n; flag = 1 , n = strlen (s) ; for ( i = 0 ; i < n/2 & & flag ; i + + ) if ( s [ i ] ! = s [ n – 1 – i ] ) flag = 0 ; return flag ; } ARRAY OF POINTERS :- The general syntax of declaring one dimensional array of pointers is as follows. datatype * arrayname [ size ] For e.g. int * a [ 5 ] ; In the above example, a is an array of 5 pointers and all the pointers are pointer to integer. a [ 10 ] a [ 1 ] a [ 2 ] a [ 3 ] a [ 4 ] The general syntax of declaring two dimensional array of pointers is as follows. datatype * arrayname [rowsize] [columsize] for e.g. float * b [ 3 ] [ 4 ] In above example, b is an array of 3 rows and 4 columns and all the 12 elements are pointers and those are pointers to floating point data.
Arrays:
Array is nothing but group of elements where all the elements are of same type.
The two broad categories of the array are
1) One dimensional array
2)Multi-dimensional array.
1) One-dimensional Array -
Consider the following example
a = 1
0
-4
3
7
i) In the above example, we have formed group of five integers and the ‘a’ acts as group name. To access individual elements of this group, we have to specify subscript along with the array name.
ii) The subscript is also called as Index. The elements in the above array are accessed as a [o], a [1], a [2], a[3] and a [4]. Thus the subscript values will range from 0 to 4.
iii) To access any element in the array only one subscript is sufficient and hence the array ‘a’ is called as one dimensional array.
iv) Declaration of one dimensional array :-
The general syntax of declaring one dimensional array is as follows.
datatype arrayname [size]
for e.g. int a [5] ;
Using the above declaration we declare to the compiler that a is an array of 5 elements are of type int. In response to this declaration, the compiler will allocate a space of 10 successive bytes in memory. The subscript values will range from 0 to 4 and the array elements will be accessed as a [o], a [1], a [2], a [3], and a [4]. In general if one dimensional array is of size ‘n’ then the subscript values will range from 0 to n –1.
v) Initialization while declaration of one dimensional array -
the array elements can be initialized at the time of declaration. Consider the following examples.
int a [5] = { 10, 20, 30, 40, 50};
int b [5] = { 10, 20, 30};
int c [5] = { 0, 20, 30};
int d [5] ;
static int e [5];
int f [ ]
int f [ ] = { 10, 20, 30 };
2) Two dimensional Array:
Consider the following example :
|
0 |
1 |
2 |
3 |
0 |
12 |
–7 |
4 |
8 |
1 |
23 |
31 |
19 |
15 |
2 |
14 |
2 |
9 |
28 |
- In the above example, we have a group of 12 integers in the tabular form of 3 rows and 4 columns and the group name is b. in the above example if we want to access the element 19 then it will accessed as b [ 1 ] [ 2 ].
Since we specify two subscripts to access the particular element of the array it is called as two dimensional array.
II. Declaration of two dimensional array.
The general syntax of declaring two dimensional array is as follow :
Data type array name (row-size) (column-size).
For e.g. int b(3) (4).
- Due to the above declaration, we declare to the compiler that ‘b’ is a two dimensional array of figures of 3 rows and 4 columns. In response to the declaration the compiler will allocate a space of 24 successive bytes in memory.
- The array elements will be stored in the memory row-wise. The first sub-script is always a row sub-script and the second sub-script is always column sub-script.
- In the above example the values of row sub-script will range from 0 to 2 and the values of the column sub-script will range from 0 to 3.
In general if the two dimensional array is of m rows and n columns then the values of row sub-script will vary from 0 to m-1 and the values of column sub-script will vary from 0 to n-1.
- WAP that accepts one dimensional array of not more than 100 integers. The program should also accept one more element say
- x. The pgm should find out and print how many times the element x is present in the given array.
→ # include
# include
void main ( )
{
int a[100] ;
int i,n,x,count=0 ;
clrscr ( ) ;
cout << “How many element = ”
cin >> n ;
cout << “Enter all element = ” ;
for ( i=0; i cin >> a[i] ; cout << “Enter element to be searched = ” ; cin >>x ; for ( i=0 ; i if ( a[i] = = x ) count + + ; cout << x << “ is not present \n” ; else cout “ is present “< getch ( ) ; } Example 2: → void main ( ) { int a [ 100 ] int i, n, j, temp ; clrscr ( ) ; cout << “ How many elements = ” ; cin >> n ; cout << “Enter all element = ” ; for ( i = 0 ; i < n ; i + + ) cin >> a [ i ] ; for ( i = n – 1 ; i > 0 ; i – – ) for ( j = 0 ; j < i ; j – – ) if ( a [ j ] > a [ j + 1 ] ) temp = a [ j ] ; a [ j ] = a [ j + 1 ] ; a [ j + 1 ] = temp ; } cout << “ sorted away in ” ; for ( i = 0 ; i < n ; i + + ) cout << a [ i ] << ‘ ’ ; getch ( ) ; }
Fundamental Of Functions:-
There are number of fundamentals associated with the functions. To understand these fundamentals let us consider the following example.
# include
void main ( )
{
int x, y, z;
int add (int, int); // function prototype
cout << “Enter two integers=”;
cin >> x >>y;
z = add (x, y);
cout << “Answer=” << z << ‘\n’;
}
return ptg;
}
1.Function Declaration or function prototype:-
consider the following statement
int add (int, int);
Using he above line we declare to the compiler that add ( ) is a function that accepts two integers and returns one integer.
2. Function call:-
z = add (x, y);
Using this statement we are calling the function while call in the function the values of x and y are passed and are copied into p and g resply. The function will add these vales and will return the answer of addition. The returned answer will be assigned to z and will then be printed using cout.
3.Function header, body and definition:-
Consider the following example.
int add (int p, int q )
{
return p + q ;
}
The first line in the above example is called as Function Header. The general syntax of the function header is given as,
return-type function name (optional list of parameters)
The code of the function enclosed with the pair of curly brackets is called as function body. The function header and the Function Definition.
4. Actual Parameters:-
The parameters which are used in the function call are called as actual parameters. For e.g. x & y are actual parameters.
5. Formal parameters:-
The parameters which are used in the function header are called as formal parameters. For e.g. p and q are formal parameters.
Note: Sometimes another pair of terms is used and that is Arguments and parameters instead o using the terms Actual parameters and formal parameters respectively.
CONCLUSION:-
1 When the function is called, the values of actual parameters are copied into the corresponding formal parameters.
2 The number of actual parameters and formal parameters must be same.
3 The actual parameters and the corresponding formal parameters must be same type.
4 In the above points we can use the terms Arguments and parameters instead of Actual parameters and formal parameters, resply.
1.Write a function that accepts three integers and returns the highest out of them. Write a pgm that will accept 9 integers from user and will print the highest out of them using the given function.
→ # include
# include
void main ( )
{
int a, b, c, d, e, f, g, h, i, m1, m2, m3, m ;
int max(int, int, int);
clrscr ( );
cout << “Enter 9 integer =”;
cin >> a >> b >> c >> d >> e >> f>> g >> h >> i;
m1 = max (a, b, c); // find out highest out of 1st three int
m2 = max (d, e, f); // find out highest out of next three int
m3 = max (m1, m2, m3); // find out ultimate highest
cout << “Highest =” << m << ‘\n’;
getch ( );
}
int max (int x, int y, int z)
{
if ( x > y && x > 2)
return x;
else
if (y > x & y >z )
return y;
else
return z;
}
2) Write a function that accepts one integer and calculates and returns its factorial. Write a suitable main function to accept the values of n and r from user and will calculate and print the value of ncr using above function.
# include
# include
void main( )
{
int n.r;
unsigned long int nf. rf, nrf;
unsigned long int fact (int) // Function declaration
clrscr( );
cout << “Enter two negative integer =”;
cin >>n >>r;
nf = Fact (n) // calculate n;
rf = Fact (r) // calculate r;
nrf = Fact (n-r) // calculate (n-r);
cout << “Answer = “<< (nF / rf) * nrf << ‘in’;
getch ( ) ;
}
unsigned long int Fact (int x)
{
int i ;
unsigned long int F = 1 ;
for (i = 1; i < = x; i + +)
F = f *i ;
return f ;
}
3. Write a Function that accepts three digit integer numbers. The function should return the answer indicating whether the number is Armstrong number or not. Write a suitable main function that will print the entire three digits Armstrong numbers using the above function.
→ # include
# include
void main ( )
{
int i, ans;
int armstrong (int); // Function declaration clrscr ( );
cout << “following are three digit Armstrong numbersin”;
for (I = 100; I < = 999; i++)
{
ans = armstrong (i) // Function call
if (ans = = 1)
cout << i ;
}
getch ( ) ;
}
int armstrong (int n)
{
int x, y, z, w ;
x = n/100 ;
w = n % 100 ;
y = w/10 ;
z = w % 10 ;
if (x * x* x + y * y * y + z * z* z = = n)
return 1 ;
else
return 0 ;
}
The variable declared in the pgm will have certain storage class. The storage classes that are used in c++ one namely auto, static, register and extern.
1) Auto and static storage class:-
Consider the following pair of pgms
void main ( ) void main ( )
{ int i ; { int i ;
void Fun ( ); void fun ( );
For (i = 1;i<=5; i ++) for (i =1; i<=5; i + +)
fun ( ); fun( );
} }
void fun ( ) void fun ( )
{ {
auto int x = 1 ; static int x = 1 ;
cout << x << ‘\t’ ; cout << x << ‘\t’ ;
x++ ; x++ ;
} }
Explanation for Pgm – I :-
In pgm I the storage class of x is auto. When the function fun ( ) called for the first time then the compiler will allocated space of 2 bytes for x and will initialize it with the value 1. The allocation will take place automatically.
The value of ‘x’ i.e. 1 will be printed and then it will be incremented 2. The Function call will then deallocate the ‘x’ along with its value automatically and the control will return back to the main ( ).
The function fun ( ) will be called again. The compiler will then re-allocate the ‘x’ automatically and will re-initialize its value with 1. The value of ‘x’ i.e 1 will be printed and then x will become 2. The function will be finished and then the ‘x’ will be deallocated automatically along with its value. The process will be repeated and the o/p will be
1 1 1 1 1
Explanation for Pgm – II:-
In pgm – 2 the storage class of ‘x’ is static. When the function fun ( ) is called for the first time then the compiler will allocate space of 2 bytes For ‘x’ and will initialize it with the value 1.
The value of ‘x’ i.e. 1 will be printed and then it will be incremented to 2. The function call will then be finished.
However the ‘x’ will not be deallocated from the memory because its storage class is static. The control will then return back to the main ( ).
The function fun ( ) will be called again. The Function will not re-initialize the value of ‘x’ by 1. This is because the concept is initialization while declaration. Whereas the ‘x’ is already declared and it is there in the memory. Hence the existing value of ‘x’ i.e 2 will be printed and then the ‘x’ i.e 2 will be printed and then the ‘x’ will be incremented to 3 and the function call gets finished. The process will be repeated and the O/P will be,
1 2 3 4 5
Points to Note:-
1) In both the above pgm, the storage class of the variable ‘i’ was auto by default.
2) Both the auto and static storage class variables are stored in primary memory of computer (RAM).
3) The life span of the auto-variable is from the time at which the function containing that variable is called to the time at which that function call gets finished.
4) The life span of the static variable is from the time at which the function containing that variable is called to the time at which the main function i.e. the pgm execution gets finished.
3.Register Storage Class:-
1) When the storage class of the variable is given as register then it will be stored in one of the general purpose registers within the processor. If none of the processors registers is free then the variable will be stored in primary memory just like auto and static variable.
2) Consider the Following example.
Register int x;
If any register within the processor is free then the variable ‘x’ will be stored within the register otherwise it will be stored in primary memory and then it will just act as variable with auto storage class. The register storage class will be used with the variables that require frequent calculations. Since these variables stored within the preprocessor only, those will be accessed much faster and thus the execution time will reduce.
4.Extern Storage Class:-
1) Consider the following example.
# include
int x=123 ;
Void main ( )
{
int y=45 ;
cout << x << ‘ ‘<< y << ‘\n’ ;
}
In the above pgm, the ‘y’ is a local variable of main ( ) and its storage class is auto by default. The variable ‘X’ is external variable, whose storage class is static by default. In addition to that the storage class of variable ‘x’ is extern. This is because it is defined external to the function. The output of the pgm will be 123 45.
* SCOPE OF INDENTIFIERS / SCOPE OF VARIABLES:
The Scope of the variable or identifier PS nothing but the area in which that variable or identifier can be used.
Consider the following example
# include
int x:
void main ( )
extern int q ;
void abc ( ),def ( ), pqr ( ) ;
. . . .
. . .
} int z ;
void abc ( )
{
int p;
. . . .
} int q ;
void def ( )
{
int r ;
. . .
. . . .
}
void pqr ( )
{ int s ;
. . .
. . . .
}
The following table shows the details of all possible variables used in the above pgm.
Variable Storage class Scope
name and type
x extern main ( ), abc ( ), def ( ), pqr ( )
y auto and local main ( )
z extern abc ( ), def ( ), pqr ( )
p auto and local abc ( )
q extern def ( ), pqr ( ), main( )
r auto and local def ( )
s auto and local pqr ( )
* RECURSION:
1) Recursion is the process in which the problem is specified in terms of itself.
2) To implement recursion the function should call itself. The function calling itself is called as recursive function.
3) Every invoke of the recursive function will give the partial solution and will call the next invoke of itself to get the further solution.
4) There must be some condition by which the recursion process will be stopped, otherwise it can lead to an infinite process.
5) When recursion is used then all the partial solutions must be combined to obtain the final solution.
6) For e.g. factorial of 3 can be described as follows.
Fact (3)
3 * Fact (2)
2 * Fact (1)
1 x Fact (o)
Following are the control structures that are used in C + + :
A) Decision Making Statements:-
1.if statement
2.if-else statement
3.switch statement
B) Looping statements:-
1.for statement
2.while statement
3.do-while statement
C) Miscellaneous statement:-
1.break statement
2.continue statement
3.goto statement
if statement –
1.The general syntax of if statement is given as follows
if (conditional expression)
2.If the conditional expression results in value true then the statement part will be executed. If the conditional expression results in value false then the statement part will not be executed.
3.The statement can be any valid C + + statement.
4. Example
if (m > = 40)
cout << “pass\n”;
if-else statement-
1.The general syntax of if-else statement is given as follows.
if (conditional expression)
statement 1;
else
statement 2;
2 .If the conditional expression results in value true then the statement 1 will executed and if the conditional expression results in value false then the statement 2 will be executed.
3.The statement can be any valid C + + statement.
4.example 1 :-
if (m>=40)
cout << “pass\n”;
else
cout << “Fail\n”;
Example 2 :-
if (m < 40)
{
cout << “Better luck next time\n”;
}
else
{
cout <<”Pass\n”;
cout<< “Congratulations \n”;
}
Nested if – else statements:-
1. When if- statement or if – else statement itself acts as statement part of the other if or if – else statement then that results into nested if-else statement.
2.There is no limit for the depth of nesting.
3.The nested if-else statement can result into number of combinations.Consider the following example that shows one particular combination of the nested if-else statement.
4. Example :-
if (case 1)
if (case 2)
S1;
else
S2;
else
if (case 3)
S3;
else
S4;
Explanation :-
case 1 case 2 case 3 executed statements
False False False S4
False False True S3
False True False S4
False True True S3
True False False S2
True False True S2
True True False S1
True True True S1
Note : When we have a complicated Nested if else without any curly brackets, then to understand which else is associated with which if, we can apply the following logic.
soln / logic :- Scan the Nested if else from top to bottom and search for the else. As soon as you get the else, associate it with the previous nearest and un- associated if.
1.Wap that accepts marks of a single subject out of 100. The pgm should print the class of a student.
If marks > = 70 Then the class is distinction if marks > = 60 AND if marks < 70 Then the class is first class.
If marks > =50 and if marks < 60 then the class is second class
If marks > = 40 and if marks <50 the class is pass class.
If marks < 40 then the class is fail.
Ans:
# include
# include
void main ( )
{
int m ;
clrscr ( );
cout << “ Enter marks out of 100 =” ;
cin >> m;
if (c > = 70)
cout << “ Distinction \n” ;
else
if ( m > =60)
cout << “ First class \n”;
else if ( m > = 50)
cout << “ second class \n”;
else if ( m > = 40)
cout << “pass \n”;
else
cout << “ Fail \n”;
getch ( );
}
2) WAP that accepts three integers and finds out the highest of them.
→ # include
# include
void main ( )
{
int a, b, c;
clrscr( ) ;
cout << “ Enter the value of a, b, & c \n” ;
cin >> a >> b >> c;
if ( a = = b & & b = = c)
cout << “All numbers are equal” ;
else
{
if ( a > b & & a > c)
cout<< “Highest =” << a << ‘\n’;
else if (b > a & & b > c)
cout << “Highest =” << b << ‘\n’;
else
cout << “Highest = “<< c << ‘\n’;
}
getch ( );
}
3. WAP that accepts one positive integer and prints whether the number is divisible by 7 or not
# include
# include
void main ( )
{
int n;
clrscr ( ) ;
cout << “Enter the value of n”<< ‘\n’;
cin >> n;
if ( n% 7 = = 0)
cout << n << “ is divisible by 7\n”;
else
cout<< n << “is not divisible by 7\n”;
getch ( );
}
4. WAP that accepts a positive integer and prints whether it is ever number or not
# include
# include
void main ( )
{
int a ;
clrscr ( );
cout << “ Enter the value of a” ;
cin >> a;
if (a% 2 = =0)
cout << a << “ is a even number \n” ;
else
cout << a << “is a even number \n” ;
else
cout << a << “ is a odd number \n” ;
getch ( );
}
Switch statement :-
1.The general syntax of the switch statement is as follows.
switch (expression)
{
case 1 : statement 1 ; break ;
case 2 : statement 2 ; break ;
case 3 : statement 3 ; break ;
…………………
…………………
case n : statement n ; break;
deafault : statement p ;
}
Explanation :-
1. First of all the expression that is written within the switch will be solved to result into a singe value.
2. If the value of the expression matches with case 1 then the statement 1 will be executed and the corresponding break statement will take the control out of the switch statement.
3. If the value of the expression is not matching with case 1 then it will be compared with case 2 and if the match is found then the statement 2 will be executed and the corresponding break statement will take the control out of the switch statement.
4.If the value of the expression is not matching with case 2 then it will be compared with further cases. If the value of the expression does not match with any of the case then the default statement i.e. the statement p will be executed. Since, the default part is physically written at the end of the switch statement, the control will come out of the switch statement without writing the break statement with the default part.
Note :- The default part of the switch statement need not be written at the end of the switch . It means we can write it at the beginning of the switch or it can be written anywhere in between within the switch. Writing the default part within the switch statement is not compulsory.
example ;-
int a ;
cout < < “Enter one integer = ” ;
cin > > x ;
switch (x)
{
case 1 : cout << “3\n”; break ;
case 2 : cout << “6\n” ; break ;
case 3 : cout << “ 9\n” ; break ;
case 4 : cout << “12\n” ; break;
default : cout << “30\n” ; break ;
}
O/P
x 1 2 3 4 Anything other than 1 to 4
out put 3 6 9 12 30
1.WAP that accept a digit that represent reading on a die when thrown. If the digit is 1 or 3 or 5 then display the message “Odd Number”. If the digit is 2 or 4 or 6 then the message displayed should be “Even Number”. Otherwise the message should, be “Faulty Die”.
# include
# include
void main ( )
{
int x ;
clrscr ( );
cout << “Enter the value of x =” ;
cin >> x ;
{
case 1:
case 3 :
case 5: cout << “Odd Number” ; break;
case 2:
case 4:
case 6: cout << “Enter Number” ; break;
default : cout << “Faulty die” ;
getch ( ) ;
}
2 .WAP that accepts one alphabet and prints the colour name starting with that alphabet.
# include
# include
void main ( )
{
char x;
clrscr ( );
cout << “Enter one alphabet =”;
cin>> x ;
switch (x)
{
case r :
case R : cout<< “Red \n” : break;
case g :
case G : cout << “Gray, Green \n” ; break ;
case b :
case B : cout << “ Blue, Black \n” ; break ;
default : cout << “Unknown color” ;
}
getch ( );
}
3 . WAP that will ask user to enter one digit and depending on the digit entered by user the pgm should display the suitable message.
1. If the digit is 2 or 3 or 6 or 7 then the message should be “Good Morning”}
2. If the digit is 1 or 4 or 5 or 8 then the message should be “Good afternoon.
3. If the digit is 0 or 9 then the message should be “Good Evening”
4.If user enters anything other than 0 to 9 then the message should be “Good Night”
# include
# include
void main ( )
{
int x;
clrscr ( );
cout << “Enter the value of x”;
cin >> x;
switch (x)
{
case 2 :
case 3 :
case 6 :
case 7 : cout << “Good Morning\n ; break ;
case 1:
case 4:
case 5:
case 8: cout << “Good Afternoon”; break;
case 0:
case 9: cout << Good evening “; break;
default : cout << “Good Night”;
}
getch ( );
}
4. WAP that accepts option from user. The options can be ‘+’ or ‘–‘or ‘*’ ‘/’ . After accepting the option, the pgm should accept the two and should print the appropriate result depending on the option.
→
# include
# include
void main ( )
{
char option ;
int a , b ;
clrscr ( ) ;
cout << “Enter your option ( + - * /) =” ;
cin >>option ;
if ( option = = ‘ + ¦¦ option= = ‘_’ ¦¦option = = ‘*’ ¦¦ option = = ‘/’ )
{
cout <<”Enter two integer =” ;
cin >> x>> y ;
switch (option)
{
case ‘ +’ : cout << x + y << ‘/in’ ; break ;
case ‘-‘ : cout << x - y << ‘/in’ ; break ;
case ‘*‘ : cout << x * y << ‘/in’ ; break ;
case ‘/‘ : cout << float (x) / y << ‘/in’ ; break ;
}
}
else
cout << “Invalid option \n” ;
getch ( ) ;
}
5. WAP that accepts three numbers representing coefficients of a quadratic equation. Your pgm should print roots of the quadratic equation by considering all possibilities.
Logic : ax2 + bx + c = 0 ( a ≠ 0)
If b2 – 4ac > 0 roots are real & unequal
If b2 – 4ac = 0 roots are equal & real
If b2 – 4ac < 0 roots are imaginary & unequal
The quantity b2-4ac is called discriminate and denoted by D.
# include
# include
# include
void main ( )
{
int a, b, c, r1, r2;
cout << “Enter the values of a, b, c :” < cin >> a; cin>>b; cin>> c; if (( b* b – 4* a *c) >0) { r1=(–b + sqr + (b*b – 4*a*c)) / (2*a)) ; r2=(–b – sqr – (b*b – 4*a*c)) / (2*a)) ; cout << “One root is” << r1<< endl ; cout << “Second root is” << r2< } else If ((b*b – 4*a*c = + 0)) { r1= –b /(2*a); r2= – b/(c2*a); cout << “root1is” << r1endl; cout<< “root2is”<< r2endl; } else If ((b*b – 4*a*c) <0) { r1 = (– b + sqr + (b*b – 4*a*c)) / (2*a); r2 = (– b –sqr + (b*b – 4*a*c)) / (2*a); cout << “Root 1 is imaginary” << r1; cout << “Root 2 is imaginary” << r2; } getch( ) ; } Loops :- For Statement:- for (expression1; expression2; expression 3) statement; I.After executing the expression. The control comes back to the expression 2 and it will be executed. If the expression 2 is true again, then the statement part will be executed again and the control will go back to expression 3 again and it will be evaluated. The control will then be back to the expression 2. II.The above process will be repeated as long as the expression 2 is true and as soon as the expression 2 becomes false then the control will come out of the for loop. Example:- for (i = 1 ; i < = 4 ; i ++) cout << i << ‘\n’ o/p 1 2 3 4 5 While statement :- 1) The general syntax of the while loop or while statement is as follows. while (conditional expression) statement; 2) First of all, the control of execution will come to the conditional expression and it will be executed. If the conditional expression is false in the very first comparison then the control of execution will come out of the while loop without executing the statement part at all. 3) If the conditional expression results in value true then the statement part will be executed. After executing the statement part, the control of execution will be back to the conditional expression and it will be reevaluated. If it is true, again the statement part will be executed the control of execution will be back to the conditional expression again. 4) This process will be repeated as long as the conditional expression is true. As soon as, the conditional expression becomes false, the control of execution will come out of the while loop. Example :- 1) i = 1; output : 1 while (i < = 5) 2 { 3 cout << i << ‘\n’ ; 4 i + + ; 5 } 2) i = 1 output : 1 while (i < = 5) 2 cout << i + + << ‘\n’ ; 3 4 5 3) i = 5 ; output : 5 while (i > = 1) 4 { 3 cout << i << ‘\n’; 2 i – – ; 1 } 4) i = 5 ; while (i > = 1) cout << – – i << ‘\n’; Output :- 4 3 2 1 0 do–while statement :- 1) The general syntax of the do-while statement is as follows: do { statement 1; statement 2; . . . . . . . . . } while (conditional expression); 2) First of all, the control of execution will come to the statement part and it will be executed. After executing the statement part, the control of execution will come to the conditional expression and it will be checked. 3) If the conditional expression is false in the very first comparison then the control of execution will come out of the do-while loop. 4) If the conditional expression is true, then the control of execution will go back to the statement part and it will be executed again. After executing the statement part, again the conditional expression is checked. If the conditional expression is true again then the control will go back to the statement part. 5) The process will be repeated as long as the conditional expression is true. As soon as the conditional expression is false, the control of execution will come out of the do-while loop. Example :- i = 1; Output :- do 1 { 2 cout < 3 i + +; 4 } 5 while (i < = 5); Break statement:- 1 The break statement is used to take the control of execution abruptly out of the existing control structure. Thus, we can say that the break statement breaks the normal sequential flow. 2 The break statement can be used within a switch statement b For, while and do-while statement → break statement with in switch statement:- Refer the topic, switch statement for examples and programs. → break statement within the loop:- When the break statement within the loop gets executed then the control of execution will come out of the loop abruptly. Consider the following examples. example:- for(i =1;i < = 100; i++) if (i > 5) break; else cout << i ; output:- 1 2 3 4 5 Explanation:- When the value of i will become 6 then the break statement will executed and the control of execution will come out of the for loop abruptly. We can avoid the break statement in the above example and can still get the same output. Thus, the same output can be obtained with the better logic, as follows Better Logic:- for (i =1; i < = 5; i++) cout << i; Explanation:- When the value of i is 1, then the condition i%7!=o is true and hence the continue statement gets executed. Due to the execution of the continue statement, the control of execution will continue to the next iteration i.e. the expression 3 of the for loop i.e. i++ and thus the cout is skipped. Similar will be the action for all the values of i from 2 to 6. When the value of i will become 7, then the condition i%7!=0 will become false and hence the continue statement is not executed and the vale 7 is printed and the control of execution will go to the next iteration normally. The process will be repeated for the further iteration. During the process, all the multiples of 7 upto 100 will be printed. The same output can be obtained without using continues statement. The better logic to give the same output without using continues statement can be given as follows. for (i =1; i < = 100; i++) if (i % 7 = = 0) cout << i << ‘ ’ ; All the values for which the condition i % 7 = = 0 is true are printed i.e. all multiples of 7 upto 100 are printed 1 The continue statement is used within the loops. When the continue statement within the loop gets executed, then the control of execution will continue to the next iteration of the loop. All the further statements in the current iteration of the loop are skipped. 2 When the continue statement within the for-loop gets executed then the control of execution continues to the expression 3 of the for loop. 3 When the continue statement within the while loop gets executed then the control of execution continues to the conditional expression of the while loop. 4 When the continue statement within the do-while loop gets executed then the control of execution contributes to the conditional expression of the do-while loop. Example 1:- for (i =1; i < =100; i++) { if(i %7!=0)continue; cout << i << ‘ ’; } output:- 7 14 21 28 35 42 49 56 63 70 77 84 91 98 goto statement:- 1.The goto statement is used to `take the control of execution abruptly anywhere within any portion of the pgm. 2.The general syntax of the goto statement is as follows. goto label When the goto statement is executed then the control of execution will go to the labelled statement. consider the following example. fact = 1; i = 1; abc : fact = fact* i; i++; if (i < = n) goto abc; cout<< “Factorial of” << n << “ = ” << fact;
More Articles …
Page 3 of 21