Wednesday 4 April 2018

'this' Pointer

We know that pointer is a variable which holds address of some other variable an we can access the data of another variable using pointer technique.

'this' is special type of pointer which holds the address of objects which invokes the member function of the class.

Whenever any object calls its member function, 'this' pointer is automatically set and contains the address of that object. In other words , whenever a member function gets called , an address of the object get passed to the function and this address gets collected in the 'this' pointer.

Hence 'this' pointer acts as an implicit argument to all the member function of the class and it is automatically passed to the member function when member function of class is called.

In operator overloading , we have been implicitly using the pointer 'this' to the member function.

When a unary operator is overloaded using a member function , we pass no argument to the function. When a binary operator is overloaded using a member function , we pass only one argument to the function and other argument is implicitly passed using pointer 'this'

#include<conio.h>
#include<iostream.h>
class abc
{
int a;
public:
void accept(int a1)
{
this->a=a1;
}
void display( )
{
cout<<"\n\tAddress of calling object is--->"<<this;
cout<<"\n\tValue of a is--->"<<this->a;
}
};
void main( )
{
abc A1;
clrscr( );
cout<<\n\tAddress of object is--->"<<&A1;
A1.accept(10);
A1.display( );
getch( );
}

Output:-
Address of object is--->0⤫8f9afff4
Address of calling object is--->0⤫8f9afff4  
Value of a is--->10

One important application of 'this' pointer is to return the object it points to.

The Statement 
return *this

inside a member function will return the object that invokes the function. This statement assumes importance when we want to compare two or more objects inside a member function and return the invoking object as a result.

#include<conio.h>
#include<iostream.h>
#include<string.h>
class person
{
char name[20];
int age;
public:
person(char nm[20],float ag)
{
strcpy(name,nm);
age=ag;
}
person *great(person *x)
{
if(x->age>=age)
return x;
else
return this:
}
void display( )
{
person p1("Irawen",101);
person p2("Pirawen",102);
clrscr( );
person *p=p1.great(&p2);
p->display( );
getch( );
}


Output:-
Name is--->Irawen              Age is--->101

Function Returning Pointer Object

We know that function can return any data type. In the same way we can return pointer variable that is user defined pointer variable or system defined pointer variable from the function.

The general syntax:
returntype * functionname(Argument_list)
{

}

Here returntype is the data type of the value which is returned by the function and functionname follows the usual rule of naming the identifiers.

Write a program to implement the concept of returning pointer object from function.

#include<conio.h>
#include<iostream'h>
class abs
{
int a;
public:
void accept(int a1)
{
a=a1;
}
abc *display(abc *B2)
{
abc *ab;
ab=B2;
cout<<"\n\tAddress of object accepted as argument--->"<<ab;
cout<<"\n\tValue of a is--->"<<ab->a;
return ab;
}
};
void main( )
{
abc ab1;
abc *B1;
clrscr( );
ab1.accept(10);
B1=ab1.display(&ab1);
cout<<"\n\tAddress of returning object--->"<<B1;
getch( );
}


Output:-
Address of object accepted as argument--->0⤫8f7bfff4
Value of a is--->10
Address of returning object--->0⤫8f7bfff4

Array of Pointers to Objects

We can create an array of objects using pointers. For this we can use following syntax.

classname *pointer_var[size];

WAP to demonstrate array of pointers to objects

#include<conio.h>
#include<iostream.h>
class emp
{
char name[20];
float age;
public:
void getdata( );
void putdata( );
};
void emp::getdata( )
{
cout<<"\n\nEnter name and age of employee";
cin>>name>>age;
}
void emp::putdata( )
{
cout<<"\n\n\t"<<Name is--->"<<name<<"\tAge is--->"<<age;
}
void main( )
{
emp lct[3];
emp *lect[3];
int i;
for(i=0;i<3;i++)
{
lect[i]=&lct[i];
}
for(i=0;i<3;i++)
{
cout<<"\n\tEnter Details of Lecturer"<<(i+1);
lect[i]->getdata( );
}
cout<<"\n\tInformation about of employee";
for(i=0;i<3;i++)
{
lect[i]->putdata( );
}
getch( );
}


Output:-
Enter Details of Lecturer 1
Enter name and age of employee Irawen 101
Enter Details of Lecturer 2
Enter name and age of employee Pirawen 102
Enter Details of Lecturer3
Enter name and age of employee Ntirawen 103
Information about of employee
Name is---> Irawen        Age is--->101
Name is--->Pirawen       Age--->102 
Name is--->Ntirawen     Age--->103

Pointer To Object

As we create a simple object of class similarly we can create object of the pointer type of class.

For Example if we have a class with the name item, then we can create an object for item class as
item x;

Whenever item is a class and x is an object of item class, similarly we can define object of the type pointer as item *ptr;

There are two ways to access the members of class using pointers
 1. The members of class can be accessed by using the arrow operator in the similar way as it is used in the structure variable.
 pointer_var->class_member;
  2. Another way is (*pointer_var).class_member;
      
  In this notation parenthesis is necessary since dot has a higher precedence over the indirection operator(*).


#include<conio.h>
#include<iostream.h>
class max
{
int m,n;
int largest(void)
{
if(m>n)
{
return m;
}
else
{
return n;
}
}
public:
void getdata( )
{
cout<<"\n\tEnter any two nos--->";
cin>>m>>n;
}
void putdata( )
{
cout<<"\n\tLargest no is--->"<<largest( );
}
};
void main( )
{
clrscr( );
max *obj;
obj->getdata( );
(*obj).putdata( );
getch( );
}

Output:-
Enter any two nos---> 34 89
Largest no is---> 89

Pointers to Strings

A string is an array of characters terminated by a special character called as a null character.

Pointer to the string is a pointer which is initialized to the base address of the first location in string.

Syntax for declaring a pointer to string.

Datatype *pointer_variable;
Ex : char *ptr;

To initialize the pointer to the address of the string , assign the pointer to the name of string or to the address of the first element of the string.

char str[10]="Irawen";

char *ptr;

ptr=str;    OR       ptr=&str[0];

WAP to find the length of string using pointer

#include<conio.h>
#include<iostream.h>
void main( )
{
char str[10], *ptr;
int cnt=0;
clrscr( );
cout<<"\n\n\tEnter Any String";
cin>>str;
ptr=&str[0];
while(*ptr!='\0')
{
cnt++;
ptr++;
}
cout<<"\n\n\tLength of the Given String is--->"<<cnt;
getch( );
}

Output:-
Enter Any String Irawen
Length of the Given String is--->6

WAP to copy one string into another string and print both the strings on output screen using pointers to strings.

#include<conio.h>
#include<iostream;h>
void main( )
{
char str1[20], str2[20];
char *ptr1, *ptr2;
clrscr( );
cout<<"\n\n\tEnter First String";
cin>>str1;
ptr1=&str1[0];
ptr2=&str2[0];
while(*ptr1!='\0')
{
*ptr2=*ptr1;
ptr1++;
ptr2++;
}
*ptr2='\0';
cout<<"\n\n\tEnter String is--->"<<str1;
cout<<"\n\n\tCopied String is--->"<<str2;
getch( );
}

Output:-
Enter First String Irawen
First String is--->Irawen
Coiped String is--->Irawen

WAP to concat two strings by using pointers to strings.

#include<conio.h>
#include<iostream.h>
void main( )
{
char str1[20], str2[10], *ptr1, *ptr2;
clrscr( );
cout<<"\n\n\tEnter the First String";
cin>>str1;
cout<<"\n\n\tEnter the Second String";
cin>>str2;
ptr1=&str1[0];
ptr2=&str2[0];
while(*ptr1!='\0')
{
ptr1++;
}'
while(*ptr2!='\0')
{
*ptr1=*ptr2;
ptr1++;
ptr2++;
}
*ptr1='\0'
cout<<"\n\n\tConcatenated String is--->"<<str1;
getch( );
}

Output:-
Enter the First String Ira
Enter the Second String wen
Concatenated String is--->Irawen

WAP to reverse the given string using pointers

#include<conio.h>
#include<iostream.h>
void main( )
{
char str1[10], *ptr1;
int len=0;
clrscr( );
cout<<"\n\n\tEnter the String";
cin>>str1;
ptr1=&str1[0];
while(*ptr1!='\0')
{
len=len+1;
ptr1++;
}
len--;
ptr1--;
cout<<"\n\n\tReverse String is--->";
while(len>0)
{
cout<<*ptr1;
ptr1--;
len--;
}
getch( );
}

Output:-
Enter the String irawen
Reverse String is--->newari

Tuesday 3 April 2018

Pointer in Arrays

Consider the declaration
int b[5];
int *ptr;
The pointer to array is given as below
ptr=&b[0];
which is same as
ptr=b;
If the pointer is incremented to the next data elements , then address of the incremented value of the pointer will be same as the value of the next element.

ptr=&b[0]            *ptr=b[0]
ptr+1=&b[1]        *(ptr+1)=b[1]
ptr+2=&b[2]        *(ptr+2)=b[2]
ptr+3=&b[3]        *(ptr+3)=b[3]

The expression-
  value[i] is same as (value+i)
that is
b[i] ==*(b+i)
b[0] ==*(b+0)
b[1] ==*(b+1)
b[2] ==*(b+2)
b[3] ==*(b+3)

WAP to initialize and display five elements from array by using pointer to array.

#include<conio.h>
#include<iostream.h>
void main( )
{
int a[5]={10,20,30,40,50};
int *ptr, i;
clrscr( );
ptr=&a[0];
cout<<"\n\n\tElements in array are--->";
for(i=0;i<5;i++)
{
cout<<" "<<*ptr;
ptr++;
}
getch( );
}


Output :-
Element in array are---> 10 20 30 40 50

WAP to search  an element from array using pointers to array

#include<conio.h>
#include<iostream.h>
void main( )
{
int a[5];
int *ptr, i, f=0, item;
clrscr( );
ptr=&a[0];
cout<<"\n\n\tEnter Five elements";
for(i=0;i<5;i++)
{
cin>>*ptr;
ptr++;
}
cout<<"\n\n\tEnter Element to search";
cin>>item;
ptr=&a[0];
for(i=0;i<5;i++)
{
if(*ptr==item)
{
cout<<"\n\n\tElement is searched in array at"<<" "<<i+1<<"th location";
f=1;
break;
}
ptr++;
}
if(f==0)
cout<<"\n\n\tElement is not searched in array";
getch( );
}

Output:-
Enter Five element 12 23 34 45 56

Enter Element to search 56

Element is searched in array at 5 th location

WAP to insert an element at location of array by using pointer to array.

#include<conio.h>
#include<iostream.h>
void main( )
{
int a[10], i, *ptr1,n,loc,ele;
clrscr( );
cout<<"\n\n\tEnter Size of the Array";
cin>>n;
ptr1=&a[0];
cout<<"\n\n\tEnter Element in the Array";
for(i=0;i<n;i++)
{
cin>>*ptr1;
ptr1++;
}
cout<<"\n\n\tEnter Location to insert in to array";
cin>>loc;
cout<<"\n\n\tEnter Element to insert into Array";
cin>>ele;
ptr1--;
for(i=n-1;i>=0;i--)
{
if(i==loc-1)
{
*(ptr1+1)=*ptr1;
*ptr1=ele;
}
*(ptr1+1)=*ptr1;
ptr1--;
}
ptr1=&a[0];
cout<<"\n\n\tElement in the Array after Insertion--->";
for(i=0;i<n+1;i++)
{
cout<<" "<<*ptr1;
ptr1++;
}
getch( );
}

Output:-
Enter Size of the Array 5
Enter Element in the Array 12 23 34 45 56
Enter Location to insert in to array 3
Enter Element to insert into Array 90
Element in the Array after Insertion is---> 12 12 23 90 45 56

WAP to delete an element from an array from the specified location using pointers to array.

#include<conio.h>
#include<iostream.h>
void main( )
{
int a[10],i,*ptr1,n,loc;
clrscr( );
cout<<"\n\n\tEnter Size of the Array";
cin>>n;
ptr1=&a[0];
cout<<"\n\n\t Enter the Elements in the Array";
for(i=0;i<n;i++)
{
cin>>*ptr1;
ptr1++;
}
cout<<"\n\n\t Enter the Location of element to be deleted";
cin>>loc;
ptr1=&a[loc];
for(i=loc-1;i<n;i++)
{
*ptr1=*(ptr1+1);
ptr1++;
}
ptr1=&a[0];
cout<<"\n\n\tElements in Array after deletion is--->";
for(i=0;i<n-1;i++)
{
cout<<" "<<*ptr1;
ptr1++;
}
getch( );
}

Output:-
Enter Size of the Array 5
Enter the Elements in the Array 12 23 34 45 56
Enter the location of element to be deleted 3
Elements in Array after deletion is---> 12 23 34 56

Pointers to Functions

1. Cpp allows functions to be referenced by a pointer.
2. A pointer to a function must be declared to be a pointer to the datatype returned by the functions like void , int , float and so on....
3. In addition , the argument type of the function must also be specified when a pointer is declared.
4. The argument declaration is a list of a formal argument separated by commas and enclosed in parenthesis.
5. The general Syntax of a pointer to a function is
    Returntype (*variable) (list of parameters);
   Ex : void (*ptr) (float a, float b, float c);
   In the above declaration , a pointer to a function returns void and takes formal arguments of two float and one int.
 Ex : float (*ptr) (char a, double b, int c, float d)
 In the above declaration , a pointer to a function returns a floating point value and takes the formal argument of char , double , int and float type.
6. After the declaration of pointer to a function , the address of the function must be assigned to a pointer.


WAP to find sum of three numbers and average using pointer to function.

#Include<conio.h>
#include<iostream.h>
void calavg(int a, int b, int c);
void (*ptr)(int a, int b, int c);
void main( )
{
int a1, b1, c1;
clrscr( );
cout<<"\n\tEnter Any three Values";
cin>>a1>>b1>>c1;
ptr=&calavg;
(*ptr)(a1,b1,c1);
getch( );
}
void calavg(int a, int b, int c)
{
int sum;
float avg;
sum=a+b+c;
avg=sum/3.0;
cout<<"\n\n\tSum of three nos is--->"<<sum;
cou<<"\n\n\tAverage is--->"<<avg;
}

Output:-
Enter Any three Values 2.23  45
Sum of three nos is--->80
Average is--->26.66666

WAP to demonstrate how a pointer to a function is declared to perform simple arithmetic operation addition, subtraction, multiplication and division of two nos.

#include<conio.h>
#include<iostream.h>
void calop(int a, int b);
void (*ptr)(int a, int b)
void main( )
{
int a1,b1;
clrscr( );
cout<<"\n\n\tEnter Any two nos";
cin>>a1>>b1;
ptr=&calop;
(*ptr)(a1,b1);
getch( );
}
void calop(int a1,int b1)
{
cout<<"\n\n\tAddition is---><<(a1+b1);
cout<<"\n\n\Subtraction is--->"<<(a1-b1);
cout<<\n\n\tMultiplication is--->"<<(a1*b1);
cout<<"\n\n\tDivision is---><<(a1/b1);
}

Output:-
Enter Any two nos 12  6
Addition is--->18
Subtraction is--->6
Multiplication is--->72
Division is--->2

Pointers and Functions

1. Pointers are very much used in function and declaration.
2. Sometimes with the use of pointer , a complex function can be easily represented and accessed.
3. The use of pointers in a function definition may be classified into two groups.
     Call by Value
     Call by Reference

Call By Value:-

 1.In a call by value , whenever a portion of program invokes a function with a formal arguments , then control is transferred from main function to calling function and value of actual argument is copied to argument of function.
 2. While calling a function , when copy of formal argument is sent to arguments of the called function then it is known as call by value.
 3. In a call by value, when a control is transferred back from called function to the calling function of the program then altered values are not transferred back.

WAP for implementation of 'call by value' concept.

#include<conio.h>
#Include<iostream.h>
void main( )
{
int x,y;
clrscr( );
x = 12;
y = 13;
cout<<"\n\n\tValue of x--->"<<x<<"\t"<<"Value of y--->"<<y;
funct(x,y);
cout<<"\n\n\tValue of x--->"<<x<<"\t"<<"Value of y--->"<<y;
getch( ); 
}
void funct(int a, int b)
{
a = a*a;
b = b*b;
}

Output:-
Value of x--->12     Value of y--->13
Value of x--->12     Value of y--->13


Call By Reference:-

 1. When a function is called by a portion of a program , the address of actual arguments are copied on to formal arguments though they may be referred by different variable name.
 2. While calling a function, when the address or reference of actual arguments are sent to the called function then it is known as call by reference.
 3. The content of that address can be accessed freely either within a function or within a calling routine.
 4. In a call by reference when the address of actual arguments are sent then these address are stored within the pointer arguments of called function.
 5. Thus the use of pointers as function arguments permits the corresponding data item to be altered globally from within the function.
 6. Any change that is made to the data item will be recognized in both functions and calling portion of the program.

WAP to implement the concept of call by reference.

#include<conio.h>
#include<iostream.h>
void main( )
{
int x,y;
clrscr( );
x = 12;
y = 13;
cout<<"\n\n\tValue of x--->"<<x<<"\t"<<"Value of y--->"<<y;
funct(&x,&y);
cout<<"\n\n\tValue of x--->"<<x<<"\t"<<"Value of y--->"<<y;
getch( ); 
}
void funct(int *p1, int *p2)
{
*p1 = *p1 **p1;
*p2 = *p2**p2;
}

Output:-
Value of x is--->12           Value of y is--->13
Value of x is--->144          Value of y is--->169

WAP to exchange the values of two variable using call by value.

#include<conio.h>
#Include<iostream.h>
void exchange(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
cout<<"\n\n\tAfter Exchange Value of A is--->"<<a<<"\tValue of B is--->"<<b;
}
void main( )
{
int a=12,b=14;
clrscr( );
cout<<"\n\n\tBefore Exchange Value of A is--->"<<a<<"\tValue of B is--->"<<b;
exchange(a,b);
getch( );
}

Output:-

 Before Exchange Value of A is--->12       Value of B is--->14
 After Exchange Value of A is--->14          Value of B is--->12

WAP to exchange the value of two variables using call by reference

#include<conio.h>
#include<iostream.h>
void exchange(int *a, int *b)
{
int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}
void main( );
{
int a=12,b=14;
clrscr( );
cout<<"\n\n\tBefore Exchange Value of A is--->"<<a<<"\tValue of B is--->"<<b;
exchange(&a,&b); 
cout<<"\n\n\tAfter Exchange Value of A is--->"<<a<<"\tValue of B is--->"<<b;
getch( );


Output:-
 Before Exchange Value of A is--->12       Value of B is--->14
 After Exchange Value of A is--->14          Value of B is--->12


Pointers

A pointer is a variable which holds the memory address of another variable.

Advantage of pointer :
 1. It supports dynamic allocation and de allocation of memory segments.
 2. It allows creation of data structure such as linked list, stacks, queues, trees and graphs.
 3. With the help of pointer , variable can be swapped without physically moving them.
 4. It allows to pass variable , arrays , function , strings an structure as a function argument.
 5. Pointer allows to return structure variable from functions.

A pointer variable of two parts:
 1. The Pointer operator
 2. The Address operator

Pointer Operator :
 1. A pointer variable can be represented by a combination of *(Asterisk) with a variable.
 2. If a variable of integer data type is declared with *(Asterisk) then if means the variable is of type 'pointer to integer'.
 3. int *ptr
     When ptr is a pointer variable which holds the address of an integer data type variable.
 4. All pointer variable must be declared before it is used in a program like any other variable.
 5. When a pointer variable is declared , the variable name must be preceded by an asterisk(*).
 6 The general format of declaration is
     Datatype *pointervariable;
     Ex : char *cptr;
            float *fptr;
            double *dptr;

The Address Operator :
 1. An address operator can be represented by the combination by the combination of '&'(ampersand) with the variable.
 2. The '&' is a unary operator the returns the memory address of its operand.
 3. ptr = &x;
      The meaning of this statement is 'ptr' is a pointer variable which receives the address of a variable 'x'.


WAP to display the content of a pointer

#include<conio.h>
#include<iostream.h>
void main( )
{
 int x;
int *ptr;
clrscr( );
cout<<"\n\tEnter Value of x";
cin>>x;
ptr=&x;
cout<<"\n\ntx--->"<<x"\t"<<"ptr is--->"<<ptr;
cout<<"\n\n\tx--->"<<x"\t"<<"*ptr is--->"<<*ptr;
getch( );
}

Output :-
  Enter Value of x15
 x--->15  ptr is--->0⤬8fc1fff4
 x--->  *ptr is--->15

WAP to assign the pointer variable to another pointer and display the content of both the pointer variable.

#include<conio.h>
#include<iostream.h>
void main( )
{
int x=12;
int *ptr1, *ptr2;
clrscr( );
ptr1=&x;
ptr2=ptr1;
cout<<"\n\n\tValue of x is--->"<<x;
cout<<"\n\n\tContent at ptr1 is--->"<<*ptr1;
cout<<"\n\n\tContent at ptr2 is--->"<<*ptr2;
getch( );
}

Output :-
 Value of x is--->12
 Content at ptr1 is--->12
 Content at ptr2 is--->12

WAP to display the content of the pointer variable using arithmetic operation.

#include<conio.h>
#include<iostream.h>
void main( )
{
int x,y;
int *ptr;
x=12;
ptr=&&x;
cout<<"\n\n\tValue of x is--->"<<x<<"\t"<<"Value at pointer is--->"<<*ptr;
y=*ptr+1;
cout<<"\n\n\tValue of y is--->"<<y<<"\t"<<"Value at pointer is--->"<<*ptr;
getch( );
}

Output :-
 Value of x is--->12                  Value at pointer is--->12
 Value of y is--->13                  Value at pointer is--->12

WAp to display the memory address of a variable using pointer before incrementation and decrementation and after incrementation and decrementation.

#include<conio.h>
#include<iostream.h>
void main( )
{
int x=12;
int *ptr1, *ptr2;
clrscr( );
ptr1=&x;
ptr2=&x;
cout<<"\n\n\tMemory Address before incrementation--->"<<ptr1<<endl;
cout<<"\n\n\tMemory Address before decrementation--->"<<ptr1<<endl;
ptr1++;
ptr2--;
cout<<"\n\n\tMemory Address after  incrementation--->"<<ptr1<<endl;
cout<<"\n\n\tMemory Address after decrementation--->"<<ptr1<<endl;
getch( );
}

Output :-
   Memory Address before incrementation--->0⤫8fd2fff4
   Memory Address before decrementation--->0⤫8fd2fff4
   Memory Address after incrementation--->0⤫8fd2fff6
   Memory Address before incrementation--->0⤫8fd2fff2


Monday 2 April 2018

Arrays

The C language provides a capability that enables the user to define a set of ordered data items as an array.

Suppose we had a set of grades that we wished to read into the computer and suppose we wished to perform some operations on these grades, we will quickly realize that we cannot perform such an operation until each and every grade has been entered since it would be quite a tedious task to declare each and every student grade as a variable especially since there may be a very large number.
    In C we can define variable called grades, which represents not a single value of grade but a entire set of grades. Each element of the set can then be referenced by means of a member called as index number of subscript.

Declaration of Arrays
  Like any other variable arrays must be declared before they are used. The general form of declaration is :
   type variables-name[50];
 The type specifies the type of the elements that will be contained in the arrays, such as int, float or char and the size indicates the maximum number of elements that cane stored inside the array. For example :
   float height[50];
 Declares the height to be an array containing 50 real elements. Any subscripts  0 to 49 are valid. In C the array elements index or subscript begins with number zero.
  So height [0] refers to the first element of the array. (For this reason, it is easier to think of it as referring to element number zero, rather than as referring to the first element).


Initialization of Arrays
  We can initialize the elements in the array in the same way as the ordinary variables when they are declared. The general form of initialization of arrays is :
   type array_name[size] = {list of values};
The values in the list care separated by commas, for example the statement
  int number[3] = {0,0,0};
Will declare the array size as a array of size 3 and will assign zero to each element.
   How to access the array element can be understood by the following program :
/* Program to count the number of positive and negative numbers*/

#include<stdio.h>
void main( )
{
int a[50], n, count_neg=0, count_pos=0,I;
printf("Enter the size of the arrays\n");
scanf("%d",&n);
printf("Enter the elements of the array\n");
for(I=0;I<n;I++)
scanf("%d",&a[I]);
for(I=0;I<n;I++)
{
if(a[I] < 0)
count_neg++;
else
count_pos++;
}
printf("There are %d negative numbers in the array\n",count_neg);
printf("There are %d positive numbers in the array\n",count_pos);
}

Multidimensional Arrays
  Often there is a need to store and manipulate two dimensional data structure such as matrices and tables. Here the array has two subscripts. One subscripts denotes the row and the other the column.
    The declaration of two dimension arrays is as follows :
       data_type array_name[row_size][column_size];
        int m[10][20];
Here m is declared as a matrix having 10 rows (numbered from 0 to 9) and 20 columns (numbered 0 through 19). The first element of the matrix is m[0][0] and the last row last column is m[9][19].


Elements of Multidimension Arrays
  A 2 dimensional array marks[4][3] is shown below. The first element is given by marks[0][0] contains 35.5 and second element is marks[0][1] and contains 40.5 and so on.


Initialization of Multidimensional Arrays

 Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces.

Example :
   int table[2][3] = {0,0,01,1,1};
Initializes the elements of first row to zero and second row to 1. The initialization is done row by row. The above statement can be equivalently written as
  int table[2][3] = { {0,0,0},{1,1,1}};
/* Example : Program to add two matrices & store the results in the  3rd matrix */

#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10][10], b[10][10], c[10][10], i, j, m, n, p, q;
clrscr( )
{
printf("enter the order of the matrix\n");
scanf("%d%d",&p, &q);
if(m= =p && n = = q)
{
printf("Matrix can be added\n");
printf("enter the elements of the matrix a");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter the elements of the matrix b");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("The matrix c is ");
 for(i=0;i<m;i++)
{
 for(j=0;j<n;j++)
printf("%d"\t,c[i][j]);
printf("\n");
}
}
getch( );
}

Union

Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structure union can be declared using the keyword union as follows :
  union item
  {
   int m;
   float p;
   char c;
   }
   code;

This declares a variable code to type union item. The union contains three members each with a different data type. However we can use only one of them at a time. This is because if only one location is allocated for union variable irrespective of time. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is-
 code.m
 code.p
 code.c
are all valid member variables.

Structure

Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data item of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types.
 structure definition:
 struct tag_name
 {
 data type member 1;
 data type member 2;
 ..................;
 ...................;
 };

Example :
  struct lib_books
  {
  char title[20];
  char author[15];
  int pages;
  float price;
  };

The keyword struct declares a structure to hold the details of four fields namely title, author pages and price. These are members of the structures.Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure.
         We can declare structure variables using the tag name anywhere in the program.

For example the statement,
  struct lib_books book1,book2,book3;
  declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books.The complete structure declaration might look like this

struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};
struct lib_books, book1, book2, book3;

Giving values to members
 As mentioned earlier the members themselves are not variables they should be linked to structure variable in order to make them meaningful members. The link between a member and a variable is established using the member operator'.' which is known as dot operator or period operator.
   For example :
    Book!.price
Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like

scanf("%s", book1.file);
scanf("%d",&book1.pages);
    OR
we can assign variables to the members of book1
strcpy(book1.title, "basic");
strcpy(book1.author, "Irawen");
book1.pages = 250;
book1.price = 28.50;

 

Sunday 1 April 2018

The case Control Structure

Switch Statement
 The switch statement cause a particular group of statements to be chosen from several available groups. The selection is based upon the current value of an expression that is include within the switch statement.

The form of switch statement is
 switch (integer expression)
 {
  case constant 1:
  do this;
  case constant 2 :
  do this;
  case constant 3 :
  do this;
  default:
  do this;
  }

Example:-
int main ( )
{
int num = 2;
switch (num +2)

case 1:
printf("case 1 : Value is : %d", num);
case 2:
printf("Case 1: Value is : %d", num);
case 3 :
printf("Default : Value is : %d", num);
default :
printf("Default : Value is : %d", num);
}
return 0;
}
   

The Break and Continue Statement

The Break Statement :-
   The keyword break allows us to jump out of a loop instantly without waiting to get back to the conditional test. When the keyword break is encountered inside any C loop, automatically passes to the first statement after the loop. For e.g. the following program is to determine whether a number is prime or not

 Logic : To test a number is prime or not, is to divide it successively by all numbers from 2 to one less than itself. If the remainder of any of the divisions is zero, the number is not a prime.

Following program implements this logic
  main( )
  {
   int num i;
   printf("Enter a number");
   scanf("%d",&num);
   i = 2;
   while (i <= num-1)
   {
     if(num% i = = 0)
      {
        printf("Not a prime number");
        break;
      }
     i++;
   }
   if(i == num)
   printf("Prime number");
 }

The Continue Statement:-
   The keyword continue allows us to take the control to the beginning of the loop bypassing the statements inside the loop which have not yet been executed. When the keyword continue is encountered inside any C loop control automatically passes to the beginning of the loop.

 For example
 main( )
 {
  int i,j;
  for(i=1; i<=2; i++)
  {
    for(j=1; j<=2; j++)
     {
       if(i = = j)
       continue;
       printf("%d%d", i,j);
      }
    }
  }

The output of the above program would be.........
 12
 21 

When the value of i equal to that of j, the continue statement takes the control to the for loop (inner) bypassing rest of the statement pending execution in the for loop (inner).

Loop Control Structures

These are three methods by way of which we can repeat a part of a program in C programming.
1. Using a for Statement
2. Using a while Statement
3. Using a do-while Statement

The While Loop (pre-test Loop)
   The general form of while is as shown below :
     initialize loop counter ;
     while (test loop counter using a condition)
     { 
         do this;
         and this;
         increment loop counter;
     }
The parentheses after the while contains so long as this condition remains true all statements within the body of the while loop keep getting executed repeatedly for e.g.
  /* calculate simple interest for 3 sets of p, n and r */
     main( )
     {
      int p, n, count;
      float r, si;
      count = 1;
      while(count <= 3)
       {
        printf("Enter values of p, n and r");
        scanf("%d%d%f", &p,&n,&r);
        si = p*n*r/100;
        printf("simple interest = Rs. %f" ,si);
        count = count +1;
       }
     }

The while construct consists of a block of code and condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loops check the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.
 For example, in the C programming language (as well as Java  and C++, which use the same syntax in this case), the code fragment
  x = 0;
  while <x < 5)
     {
         printf("x = %d\n", x);
         x++
     }
first checks whether x is less than 5, which it is, so then the {loop body} is entered, where the printf function is run and x is incremented by 1. After completing all the statements in the loop body, the condition, (x < 5), is checks again, and the loop is executed again, the process repeating until the variable x has the value 5.
  Note that it is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (such as a break statement) that controls termination of the loop.


The do-while Loop (Post-test loop)
  The do-while loop takes the following form
   do
   {
     this;
     and this;
     and this;
     and this;
   } while ( this condition is true);

There is a minor difference between the working of while and do-while loops. The difference is the place where the condition is tested. The while tests the condition before executing any of the statements within the while loop. As against this the do-while tests the condition after having executed the statements within the loop. 
        
                           The do while construct consists of a block of code and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Contrast with the while loop, which tests the condition before the code within the block is executed
   
         It is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure(such as a break statement) that allows termination of the loop.
            Some languages may use a different naming convention for this type of loop. For example, the Pascal language has a "repeat until" loop, which continues to run until the control expression is true (and then terminates) - whereas a "do-while" loop runs while the control expression is true (and terminates once the expression becomes false).

The for loop
  The general form of for statement is as under :
    for(initialize counter; test counter, increment counter)
    {
      do this;
      and this;
      and this;
    }

Now let us write the simple interest problem using the for loop .

 /* Calculate simple interest for 3 sets of p, n and r */
  main( )
  {
    int p,n,count;
    float r, si;
    for(count=1; count <=3; count = count + 1)
     { 
       printf("Enter values of p, n and r");
       scanf("%d%d%f",&p, &n, &r);
       si = p*n*r / 100;
       printf("Simple interest = Rs. %f" , si);
      }
    }
  

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (115) C (77) C# (12) C++ (82) Course (62) Coursera (179) coursewra (1) Cybersecurity (22) data management (11) Data Science (91) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (747) Python Coding Challenge (208) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses