Saturday 2 September 2017

EASY NOTES ON C LANGUAGE PART 3

 







NOTES FOR C LANGUAGE PART 3

 

 

 

 

How can we pass single dimension numeric array to function?
Let us see the technique:
#include<stdio.h>
#include<conio.h>
#define size 5
void main()
{
int a[size]={3,2,1,5,7};
void print(int a[]);  /* we can write void print(int []); or we can write void print(int [5]);
or we can write void print(int a[size]); */
int sum(int []);
int s;
print(a); /* call of function */
s=sum(a);/* call of function */
printf(“\n sum=%d”,a);
getch();
}
void print(int x[])      /* note no semicolon here */
{
 int i=0;
 printf(“\n the values are:”);
 for(i=0;i<size;i++)
   printf(“\n %d”,x[i]);
}
int sum(int a[])      /* note no semicolon here  */
{
 int i,tot=0;
 printf(“\n the values are:”);
 for(i=0;i<size;i++)
   tot=tot+a[i];
 return tot;  
}
explanation: print function uses loop to print value of elements of array if  name of parameter in function header line is ‘x’ then printing will be done using x[i]. if we had used name of parameter in function header line as ‘a’ then printing will be done using a[i].
sum function when called gets total of the values of elements of array and stores it in variable tot. ‘return’ statement passes value of variable tot to function main. main function receives value in sum and prints value of sum.

How can we pass single dimension character array or string  to function?
Let us see the technique:
#include<stdio.h>
#include<conio.h>
#define size 20
void main()
{
char a[size];
void input(char a[]);
void print(char []);
input(a); /* call of function */
print(a); /* call of function */
getch();
}
void print(char x[])      /* note no semicolon here */
{
 printf(“\n the string is:”,x);
}
void input(char a[])      /* note no semicolon here  */
{
 printf(“\n enter a string:”);
gets(a);
}
explanation: input function inputs value for character array that is string. Since it is a single dimension character array therefore loop is not required. print function when called prints the string stored by input function when called.

Write a function to accept 10 characters and display whether each input character is digit, uppercase letter or lower case letter.
#include<stdio.h>
#include<conio.h>
void main()
{
 void disp();
disp();
getch();
}
void disp()
{
 int m;
char c;
for (m=1;m<=10;m++)
 {
 printf(“enter character %d”,m);
scanf(“%c”,&c);
if (c>=65 && c<=90)
   printf(“\n uppercase letter”);
else if (c>=97 && c<=122)
 printf(“\n lower case letter”);
else if (c>=48 && c<=57)
  pritf(“\n digit”);
else
 printf(“\n it is neither an alphabet nor digit”);
}
}

How can we pass double dimension numeric array to function?
Let us see the technique:
#include<stdio.h>
#include<conio.h>
#define row 3
#define col 3
void main()
{
int a[row][col],b[row][col],c[row][col];
void input(int a[][col]); /* specifying col is must here, row is optional, variable name is optional here */
void print(int [][col]); /* specifying col is must here, row is optional, variable name is optional here */
void add(int c[][col],int a[][col],int b[][col]); /* specifying col is must here, row is optional, variable name is optional here */
input(a); /* get input for array a , note during call simply a is written not bracket is there */
input(b); /* get input for array b */
add(c,a,b); /* add contents of array a and b to c */
print (c);
getch();
}
void  input(int a[][col])      /* note no semicolon here, variable name is compulsory */
{
  int i,j;
  printf(“\n enter %d values\n”,row*col);
  for(i=0;i<row;i++)
     for(j=0;j<col;j++)
           scanf(“%d”,&a[i][j]);
}

void print(int a[][col])      /* note no semicolon here  */
{
  int i,j;
  printf(“\n values of array \n”);
  for(i=0;i<row;i++)
    { for(j=0;j<col;j++)
       printf(“\t%d”,a[i][j]);
      printf(“\n”);
  }
}
void add(int c[][col],int a[][col],int b[][col])
{
  int i,j;
  for(i=0;i<row;i++)
     for(j=0;j<col;j++)
          c[i][j]=a[i][j]+b[i][j];
}
explanation: input function inputs value for numeric double dimension array a and b. when function is called and parameter is passed is array ‘a’ then whatever values are entered by user are stored in array a. when function is called and parameter is passed is array ‘b’ then whatever values are entered by user are stored in array ‘b’ because array is always passed by reference. Function add when called stores addition of corresponding element of array a and b into corresponding elements of ‘array c’. finally print function prints contents of array c.

How can we pass double dimension character array or array of strings to function?/write program to sort a given list of names.
Let us see the technique:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define row 5
#define col 20
void main()
{
char a[row][col];
void input(char a[][col]); /* specifying col is must here, row is optional, variable name is optional here */
void print(char [][col]); /* specifying col is must here, row is optional, variable name is optional here */
void sort(char [][col]); /* specifying col is must here, row is optional, variable name is optional here */
input(a); /* get input for array a , note during call simply a is written not bracket is there */
sort(a); /* sort contents of array a which are strings */
print (a);
getch();
}
void  input(char a[][col])      /* note no semicolon here, variable name is compulsory */
{
  int i;
  /* since it is double dimension character array therefore we will use one loop which will be for change row */
printf(“\n enter %d strings\n”,row);
  for(i=0;i<row;i++)
       scanf(“%s”,a[i]);
}

void print(char a[][col])      /* note no semicolon here  */
{
  int i,j;
 printf(“\n %d strings\n”,row);
  for(i=0;i<row;i++)
     printf(“\n%s”,a[i]);
 }
void sort(char c[][col])
{
  int i,j;
  char t[col];  /* used for swapping the strings */
  for(i=0;i<row-1;i++)
     for(j=0;j<row-1-i;j++)
          if(strcmp(a[j],a[j+1])>0)
           {
              strcpy(t,a[j]);
              strcpy(a[j],a[j+1]);
              strcpy(a[j+1],t);
           }
 }
explanation: input function inputs value for double dimension character array a. when function is called and parameter is passed array ‘a’ then whatever values are entered by user are stored in array a. Function sort when called sorts the strings stored by input function and print function prints the sorted string.

What are the different categories of functions?
Function can be of four categories:
1.     return and argument
2.     no return and argument
3.     no return and no argument
4.     return and no argument.
Let us understand each category with example of addition of two nos. using function.
1.     return and argument
#include<stdio.h>
#include<conio.h>
void main()
{
 int a,b,c;
 int add(int,int);
 printf(“\n enter two values:”);
 scanf(“%d %d”,&a,&b);
 c=add(a,b);
 printf(“\n addition=%d”,c);
 getch();
}
int add(int x,int y)
{
 int z;
z=x+y;
return z;
}
2.     no return and argument
#include<stdio.h>
#include<conio.h>
void main()
{
 int a,b;
 void add(int,int);
 printf(“\n enter two values:”);
 scanf(“%d %d”,&a,&b);
 add(a,b);  /* c=add(a,b); is not valid because function does not return a value */
getch();
}
void add(int x,int y)
{
 int z;
z=x+y;
printf(“\n result of addition=%d”,z);
}
3.     no return and no argument
#include<stdio.h>
#include<conio.h>
void main()
{
 void add(); /* or void add(void); */
 add();   /* function call */
 getch();
}
void add(void)   /* or void add() */
{
 int a,b,c;
 printf(“\n enter two values:”);
 scanf(“%d %d”,&a,&b);
 c=a+b;
 printf(“\n result of addition=%d”,c);
}
4.     return and no argument
#include<stdio.h>
#include<conio.h>
void main()
{
 int c;
 int add(); /* or int add(void); */
 c=add();
 printf(“\n addition=%d”,c);
 getch();
}
int add(void)   /* or void add() */
{
 int a,b,c;
 printf(“\n enter two values:”);
 scanf(“%d %d”,&a,&b);
 c=a+b;
 return c;
}

Compare  different categories of functions?
Comparison is show in following table:
Return and argument
No return and argument
No return and no argument
Return and no argument

Input of variables are done in calling function.
Input of variable are done in calling function.
Input of variables are done in called function.
Input of variables are done in called function.

Output of result is shown in calling function.
Output of result  is shown in called function.
Output of result  is shown in called function.
Output of result  is shown in calling function.

Processing is done in called function.
Processing is done in called function.
Processing is done in called function.
Processing is done in called function.

Differentiate actual and formal parameter.
actual parameter/argument : actual parameter is used inside function call statement. no. of actual parameters passed must match as specified in function declaration and function definition’s header line. value of actual argument can not be changed by called function unless passed by reference/address/pointer.
formal/dummy parameter/argument: formal parameter is that which appears in function declaration or in function definition’s function header line. in function declaration name of parameter is optional whereas in function definition’s headerline name of variable is compulsory.

Differentiate function declaration and function definition.
Function declaration
Function definition

Function declaration specifies no. of arguments and data types of parameters.
Function definition specifies no. of arguments and data types of argument. function definition must match with function declaration in terms of no. of arguments and data type.

Function declaration can be omitted if function definition appears before function use.
Function definition can not be omitted.

Function declaration is similar to function definition’s function header line but is terminated by semicolon.
Function definition’s function header line never terminates by semicolon.

Function declaration does not contain function body.
Function definition contains function body.


 What do you mean by recursion?
Expressing an entity in terms of itself is known as recursion. When function calls itself at least once the function is called recursive function. Recursive function contains a function call statement  to call itself normally kept inside if-else construct. Putting function call inside if-else construct allows termination of recursive function call after some time.
While defining a recursive function we must take care of these two points
* Each time a function calls itself it must be closer, in some sense to a solution.
* There must be a decision criterion for stopping recursive function call otherwise it will execute till the           stack overflows.

Example calculating factorial using recursion:
#include<stdio.h>
#include<conio.h>
void main()
{
 int n;
 long f;
 long fact(int);
 printf(“\n enter a value to know factorial”);
 scanf(“%d”,&n);
 f=fact(n);
 printf(“\n factorial=%ld”,f);
 getch();
}
long fact(int n)
{
 if (n<=1)
     return n;
 else
     return n* fact(n-1);
}

Example Generating fibonacci sequence.
#include<stdio.h>
#include<conio.h>
void main()
{
  int num,f1=0,f2=1;
  void fib(int,int,int);
  printf(“\n how many terms to generate:”);
  scanf(“%d”,&num);
  fib(f1,f2,num);
  getch();
}
void fib(int f1,int f2,int num)
{
  if (num!=0)
     {
        printf(“\t %d”,f1);
        fib(f2,f1+f2,num-1);
     }
}

Example to evaluate  x – x to the power 3/ factorial 3+x to the power 5/factorial 5….
#include<conio.h>
#include <stdio.h>
int main(void)
{
   float x,s;
   int n;
   float sin(float,float,int,int );
   printf("\n enter value of x and n");
   scanf("%f %d",&x,&n);
   s=sin(x,x,1,n);
   printf("\nvalue=%f,%f",s,g);
   getch();
}

float sin(float term,float x,int i,int n)
{
 float p;
 if (i<=n)
  {
  printf("\n %f",term);
  p= term+sin(-term*x*x/((2*i)*(2*i+1)),x,i+1,n);
  }
 return p;
}

Compare iteration and recursion./Write short notes on recursion and Iteration.
Iteration
Recursion

Initialization: the loop variable is initialized along with other predefined variables.
Initialization: the variable in the form of arguments are passed on the function.

Decision: The loop variable is compared, and based on the outcome, the loop is executed if condition is true. The test performed in loop variable may not be the only condition; other relational expression may also participate in the decision.
Decision: the argument values are used to determine whether further recursive calls are necessary.

Computation: the necessary computation is performed within the loop.
Computation: the necessary computation is performed using the local variable and the parameters at the current depth.

Update: the decision parameter is updated and a transfer is made to the next iteration.
Update: the update is done so that the variables can be used for further recursive calls.

How can we use variable length argument list?
There are some functions which can accept variable length argument list for example printf, scanf etc. variable length argument list allow passing varying no. of variable while making function call.
Consider an example:
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>   /* for variable no. of argument list */
void main()
{
 void print(const char start[],…);
 print(“First call”,”Hello”,1,”World”,2,NULL);
 print(“Second call”,”Good”,10,”Morning”,20,”to all”,30,NULL);
 getch();
}
void print(const char start[],…)
{
 va_list arg_list;
 int i;
char *s;
printf(“\n %s\n”,start);
va_start(arg_list,start);
while(s)
{
  s=va_arg(arg_list,char *);
  i=va_arg(arg_list,int);
  if(s)
     printf(“%s %d”,s,i);
}
va_end(va_list);
}
explanation:
* va_list is defined in stdarg.h and is an array used in obtaining the arguments that come in place of the
ellipsis(…).
* va_start initializes the va_arg of data type va_list.
* va_arg is the one which actually extracts the argument values.
* the first parameter must be present since its name is to passed to va_start.
* va_end releases memory allotted during call of va_start.

How do we access command line parameter and environment variables/explain argc and argv?
#include <stdio.h>
#include<conio.h>
void main(int argc,char * argv[])
{
 int i;
 printf(“\n no. of command line arguments is %d“,argc);
 for(i=0;i<argc;i++)
       printf(“\n command line parameters are %s”,argv[i]);
 getch();
}
save the file with name my.c ,compile the program then go to dos prompt and type
c:\tcc\my teena meena and press enter.
no. of command line arguments is 3
command line parameters are c:\tcc\my.exe
command line parameters are  teena
command line parameters are  meena
explation: arugment count variable contains 3 because name of command(my),teena,meena gives total argument count 3. argv[0] contains name of command, argv[1] contains teena,argv[2] contains meena.
Name of argument can be any in place of argc, or argv.

Using command line argument convert uppercase string to lowercase and lowercase string to uppercase
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main(int argc,char *argv[])
{
if(strcmp(argv[1],strlwr(argv[1])==0)
  printf(“\n lower case changed to upper case as %s”,strupr(argv[1]));
else
printf(“\n upper case changed to lower case as %s”,strlwr(argv[1]));
getch();
}

Scope and Extent

Define extent or lifetime of a variable.
Every variable in a program has some memory associated with it. Memory for variables is allocated and released at different points in the program. The period of time during which memory is associated with a variable is called the extent or life time of a variable

Define scope or accessibility of a variable.
scope of a variable can be defined as the region over which the variable is visible(accessible) or valid.
Scope can be local or global.
Local:
Let us see an example:
#include<conio.h>
#include<stdio.h>
void main()
{
 int i=10;
 void display();
 printf(“\n value of i in main=%d”,i);
 display();
 printf(“\n value of j in display=%d”,j); /* will result in compilation error */
 getch();
}
void display()
{
  int j=50;
  printf(“\n value of  i in main %d”,i); /* will result in compilation error */
  printf(“\n value of j in main %d”,j);
 }
explanation: variable i is declared in main therefore it is accessible in main only, similary j is declared in display it is accessible in j only.
Variables declared inside curly brace are local to the brace and are not accessible outside the brace.
Global:
Let us see an example:
#include<conio.h>
#include<stdio.h>
int gb=10;
void main()
{
 void display();
 printf(“\n value of global gb  in main=%d”,gb);
 gb=20;  /* alteration of global variable  by main */
 display();
 printf(“\n value of global gb in main after alteration made  by display=%d”,gb); /* will result in compilation error */
getch();
}
void display()
{
  printf(“\n value of  global variable before alteration made by display= %d”,gb);
  gb=40;
}
Output:
value of global gb  in main=10
value of  global variable before alteration made by display= 20
value of global gb in main after alteration made  by display=40
explanation: variable gb is not declared inside brace of any function and is accessible by every function as long as they do not contain a local variable with name similar to global variable( in this case we have to use scope resolution operator :: to modify/access value of global variable).
Variables declared not inside any curly brace are global.

Differentiate global and local variables/ What are different types of scope available?
Global
Local

Global variable contains default value(if not initialized, assigned or scanned) zero.
Local variable contains default value(if not initialized, assigned or scanned) garbage for auto storage class, zero for static storage class, garbage for register storage class.

Global variables are not declared inside curly brace.
These are declared inside curly brace.

Every function can access and alter value of global variable except in the case a local variable with same name as that of global does not exist otherwise we would be needed to use :: operator .
We can access/alter value of local variable inside the brace where it is declared.

Memory associated for global variable is up to termination of program.
Memory is associated for local variable till the execution of statement inside the brace where the variable is declared.

Global variables declared as static int a=10;  not inside any brace can be accessed in single file known as static global variable having file scope whereas global variable declared as int a=10; known as global variable can be accessed inside any file if program consists of many files linked together.
Local variables can be with block scope means local variables can be accessed across the brace where these are declared and inside the nested blocks if variables with same name do not exists in nested block.

If a global variable with name ‘a’ exists and local variable with name ‘a’ exists how can we access value of global variable?/program to demonstrate local variable and block scope
We need to use :: operator known as scope resolution operator.
#include<stdio.h>
#include<conio.h>
int g=10;
void main()
{
  int g=15;
      {
         int g=20; /* nested block */
         printf( “\n %d”,g);
         printf(“\n %d”,::g);
      }
  printf(“\n %d”,g);
  printf(“\n %d”,::g);
  getch();
}
 output:
20
10
 15
10
explanation: ::g will always refer to global variable. If int g=20;  were not declared inside the nested block the print would have been 15 10 15 10.

What do you mean by storage class?
Storage class of a variable defines extent/lifetime(period of time during which memory is associate with variable), default value, place of memory allocation and scope/accessibility.
They are following types:
1.     auto
2.     static
3.     register
4.     extern

Explain auto variable.        
All variables declared within a function are auto by default. The extent of a variable is defined by its scope. Variables declared auto can only be accessed only with the function or the nested block within which they are declared. They are created when the block is entered into and destroyed when it exited.

Explain static variable.
C defines another class of variables called static variables. Static variable are of two types:
1. static : variables that are declared within a function (function static variables). These variables retain their values from the previous call, i.e., the values which they had before returning from the function.
2. file static variable : these variable are declared outside any function using the keyword static. File static variables are accessible only in the file in which they are declared. This case arises when multiple files are used to generate one executable code.
1. function with static variables:
void main()
{
 void display();
 display();
 display();
 display();
}
void display()
{
 static int a=0;
 printf(“\n count =%d”,a);
 a++;
}
output will be 0 1 2
let us see one more example of printing of Fibonacci series.
#include<stdio.h>
#include<conio.h>
void main()
{
 int n,i;
 void printfib();
 printf(“\n how many terms of Fibonacci series to print”);
 scanf(“%d”,&n);
 for(i=1;i<=n;i++)
       printfib();
 getch();
}

void printfib()
{
 static int t1=0,t2=1,t;
 printf(“\n %d”,t1);
 t=t1+t2;
 t1=t2;
 t2=t;
}
explanation: first call causes initialization of variables t1 to 0, t2 to 1 and t3 to zero(due to static).after the first function call to printfib the value of the variables t1 and t2 are both changed to one and retained for use in the next  call and so on. Static variables are initialized only once first time the function is called.

Write short notes on register variables.
Register variable occupy memory allocation in cpu’s register which are faster than RAM thus resulting faster program execution. Therefore best suited for loop counter. Default value is garbage and scope is limited to block scope. No. of cpu’s register is limited and if busy register variable will change to auto variable without any message. Moreover cpu’s register is built on some fixed no. of bits if register is built on 16 bits than we can declare variables of int, char data type as register.
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
register  int i;
for(i=1;i<=1000;i++)
       printf(“\n %d”,i);
 getch();
}

Write short notes on extern variables/extern storage class.
Global variable are not declared inside any brace. Every function can access its value and can alter it. If local variable with same name as that of global exists we have to use scope resolution (::) operator to access global variable.
When global variable is declared later but used earlier then we have to use extern keyword.
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
 extern int i;       /* indicates a variable i declared global appears later */
 printf(“\n %d”,i);
 getch();
}
int i=10;
Pointers

What is pointer?
Pointer is a variable that stores address of a variable.

How a pointer can be initialised?
e.g. int a, *b=&a;
char *b=”ramesh”;

What do you mean by addressing?
Addressing is a technique used to access the contents of one or more memory locations.
There are two types of addressing technique:
1.     relative: it consist of base(segment) and offset address and is useful to access memory outside 64kb of memory.
2.     absolute: all relative address is first translated to absolute address prior to physically accessing the memory and is useful to access memory within 64 kb limit.

What are the uses of pointers?
Usages are as follows:
1.     accessing array of elements.
2.     passing arguments to functions by reference(i.e arguments can be modified).
3.     passing arrays and strings to functions.
4.     creating data structures such as linked list, trees, graphs and so on.
5.     obtaining memory from the system dynamically to create dynamic array.
6.     program using pointer runs faster due to direct dealing with memory.
thus pointer provide flexibility in programming.

How to use address operator?
/* program to demonstrate address of operator, dereferencing operator and  pointer declaration */
Address operator ‘&’ gives memory location of variable.
Dereferencing operator ‘*’ gives value of variable whose address is stored in pointer.

Let us see by an example.
#include<stdio.h>
#include<conio.h>
void main()
{
 int a=10;
 int *b;
 b=&a;
/*  or   int *b=&a;     */
/*  or    int a=10, *b=&a;    */
printf(“\n value of a=%d”,a);
printf(“\n value of a=%d”,*b);

printf(“\n address of a=%u”,&a);
printf(“\n address of a=%u”,b);

a=50;
printf(“\n value of a=%d”,a);
printf(“\n value of a=%d”,*b);

printf(“\n address of a=%u”,&a);
printf(“\n address of a=%u”,b);

*b=200;
printf(“\n value of a=%d”,a);
printf(“\n value of a=%d”,*b);

printf(“\n address of a=%u”,&a);
printf(“\n address of a=%u”,b);

getch();
}
explanation: if address of a is 100 (suppose) then b=&a; will store this memory location 100 as value in variable b. if it is required to access value of variable a we can use *b,  here * is known as dereferencing operator. All variables can be accessed directly by variable name are through pointer.
An assignment statement a=50; will change value of variable a to 50 directly and assignment *b=200 will change value of variable a to 100 indirectly (through pointer).
Address of variable ‘a’ will remain same.

What do you mean by call by reference(demonstration of pointer and function)?
When address of actual argument is passed to a function, the function can change value of actual argument know as call by reference or call by address.
Let us see an example (example is of pointer and function )
#include<stdio.h>
#include<conio.h>
void main()
{
 int a=3,b=4;
 void swap(int *,int *);
 printf(“\n before call of function swap value of a=%d,b=%d”,a,b);
 swap(&a,&b);
 printf(“\n after call of function swap value of a=%d,b=%d”,a,b);
 getch()
}
void swap(int *x,int *y)
{
  int t;
   t=*x;
  *x=*y;
  *y=t;
}
output:
before call of function swap value of a=3,b=4
after call of function swap value of a=4,b=3
clearly called function is able to modify the value of actual argument.

What do you mean by void pointer?
Normally a pointer to integer is able to store address of integer variable. A pointer to float is able to store address of float variable and so on. But what if, we want a generic pointer which can store address of integer, address of float and so on? The solution lies in use of void pointer.
void pointer is special type of pointer which can store address of variable of any data type. When it is required to access value of variable(address of which stored in void pointer) we need  type  casting. Let us understand:
#include<stdio.h>
#include<conio.h>
void main()
{
 int a=10;
 float b=20;
 char c=’a’;
 void *p;
 p=&a; /* pointer to void stored address of integer variable */
 printf(“\n value of int a=%d and address=%u”,(int *)p,p);

p=&b; /* pointer to void stored address of integer variable */
 printf(“\n value of float b=%f and address=%u”,(flaot *)p,p);

p=&c; /* pointer to void stored address of integer variable */
printf(“\n value of char c=%c and address=%u”,(char *)p,p);

getch();
}
clearly before accessing value of variable whose address void pointer contents type casting is necessary.




What is the valid Pointer arithmetic operation?
Followings are valid pointer arithmetic operation:-
int a,b,*p,*q;
p=-q;    /* illegal use of pointer */
p<<=1;  /* means dividing a pointer by 2 (a constant) is illegal*/
p=p-b;  /* valid pointer can be subtracted by a constant */
p=p+b;  /* valid pointer can be added by a constant */
p=(int *)p-q;  /* pointers can be subtracted */
p=p-q-a;  /* non portable pointer conversion */
p=(int *)p-q –a /* valid */
p=p+q; /*invalid , two pointers can not be added */
p=p+q+a; /* invalid */
p=p/q;  /* invalid */
p=p*a;    /* invalid */
p=p/q;   /* invalid */
p=p/b   /* invalid */
p=a/p;  /* invalid */
p++;   /* valid */
p-- ;  /* valid */

What do you mean by pointer in mathematical expression.
It means that pointer can be used in mathematical expression  to refer the value of variable indirectly. #include<stdio.h>
#include<conio.h>
void main()
{
 int a=10,b=20,c;
 int *p,*q;
 p=&a;
 q=&b;
 c=*p**q+10/2;
 printf(“\n value of c=%d”,c);
 getch();
}
output of above program will be 205 due to c=10*20+10/2;

What do you mean by pointer to pointer.
Pointer to pointer is a variable which can store address of another pointer.
Usages:
1.     when it is required to pass 2d array to function.
2.     when it is required to change value of a pointer by called function we need to pass the address of pointer and the formal parameter must be pointer to pointer.
Let us see an example:
#include<stdio.h>
#include<conio.h>
void main()
{
 int a=10;
 int * b;
 int **c;
 b=&a;
 c=&b;
 printf(“\n value of a=%d address=%u”,a,&a);
 printf(“\n value of a=%d address=%u”,*b,b);
 printf(“\n value of a=%d address=%u”,*c,**c);

 printf(“\n value of b=%u address of b=%u”,b,&b);
 printf(“\n value of b=%u address=%u”,*c,c);

 printf(“\n value of c=%u address=%u”,c,&c);
 getch();
}

How can we use pointer and array.
#include<stdio.h>
#include<conio.h>
void main()
{
  int a[5]={3,1,5,2,4};
  int i;
  /* routine to print array using pointer notation */
  for(i=0;i <5;i++)
      printf(“%d ”,*(a+i));
  getch();
}
explanation: a[i] is equivalent to *(a+i), &a[i] is equivalent to (a+i);

How can we pass array to function or describe accessing array inside function?
#include<stdio.h>
#include<conio.h>
void main()
{
 void sort(int *a,int n); /*  pointer a to hold the array and n to process the no. of elements */
 int a[100],n,i;
 printf(“\n how many elements <max 100>”);
 scanf(“%d”,&n);
 printf(“\n enter %d values”,n);
 for (i=0;i<n;i++)
    scanf(“%d”,(a+i));  /*   &a[i] is same as  (a+i)   */
 sort(a,n);
 for(i=0;i<n;i++)
      printf(“\n %d”,*(a+i));
 getch();
}
void sort(int *a,int n)
{
 int i,j,temp;
  for(i=0;i<n-1;i++)
     for(j=0;j<n-1-i;j++)
          {
             if( *(a+j) > *(a+j+1) )
                {
                   temp=*(a+j);
                   *(a+j)=*(a+j+1);
                   *(a+j+1)=temp;
                }
            }
}
explanation: in the above example main() declares an array of capacity 100. user is given a change to enter no. of elements he wants to use out of 100. Whatever user gives gets stored in n. array is passed to called function sort with no. of elements n, to process. Inside sort function bubble sort technique of sorting is used to sort the element of array. Sorting of array results in sorting of array inside main because array is always passed by reference. When we passed the array, base address of array is stored in pointer a in formal parameter of function main.

How can we access 2d array using poiter notation(pointer and two dimensional array)?
An element a[i][j] of two dimensional array is equivalent to *(*(a+i)+j). &a[i][j] is equivalent to (*(a+i)+j). let us understand with an example.
#include<stdio.h>
#include<conio.h>
void main()
{
 int a[2][3]={1,2,3,4,5,6};
 for(i=0;i<2;i++)
   {
    for(j=0;j<3;j++)
         printf(“\t%d”,*(*(a+i)+j));
    printf(“\n”);
   }
getch();
}

What do you mean by array of pointers?
Just as we can have an array of integer, array of floats so we can have array of pointers.
#include<stdio.h>
#include<conio.h>
void main()
{
 int *a[3];  /* a is an array of pointer  */
 int b=10;c=20,d=30;
 a[0]=&b;
 a[1]=&c;
 a[2]=&d;
 printf(“\n value of b=%d, value of c=%d, value of d=%d”,*a[0],*a[1],*a[2]);
 getch();
}

Write program to sort strings using pointer exchange.
Or
How to pass array of pointers to functions/program to sort list of names using pointers/program to demonstrate array of pointers/How array of pointers to character can represent collection of strings?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> /* for malloc library function */
void main()
{
 char *name[5];
void sortbyptr(char **,int); /* function prototype */
int i;
printf(“\n enter 5 names”);
for(i=0;i<5;i++)
  {
  name[i]=(char *)malloc(20);
 scanf(“%s”,name[i]);
}
sortbyptr(name,5);
printf(“\n names in sorted order “);
for(i=0;i<5;i++)
  {
  printf(“%s”,name[i]);
}
}
void sortbyptr(char **a,int n)
{
 char *t;
int i,j;
for(i=0;i<n-1;i++)
  for(j=0;j<n-1-i;j++)
  {
  if (strcmp(a[j],a[j+1])>0)
   {
   t=a[j];  a[j]=a[j+1]; a[j+1]=t;
}
}
}
explanation: before reading string in array of pointer to character we need to allocate memory of each pointer element, after memory allocation we can read string using scanf.

What is the difference between pointer to character and character array?
Character array
Pointer to character

Name of array denotes address of first element (a[0]’s address) this address is known as base address and is a pointer constant or constant pointer. If array is declared as char a[20]=”raman”; then we can not write any  statement like  a++, a-- ,a=a+2 etc. which will modify ‘a’.
If a pointer to character ‘b’ holds a string “raman” we can increment/decrement pointer to character b therefore b++,b=b+2 etc. are valid statements.


if declared char a[20]=”raman”; it will take 20 bytes which is wasting of memory because it requires just 6 elements to hold string “raman” in which null character is also counted. So better technique is char a[]=”raman” which will take just 6 elements.
char *b=”raman” will take just 6 bytes


To assign new string to array ‘a’ declared as char [20]=”raman” we need strcpy function as follows
strcpy(a,”teena”); we must not assign string having no. of characters more than 19 counting for null. character. We can not write statement
a=”teena”;
To assign new string to pointer to character b we need
b=”rameshwari”; we need not to worry about length of string being assigned.


To input string using scanf we need not to allocate memory for array ‘a’ declared as char a[20] but care must be taken no. of characters given for  input must not exceed 19.
To input string using scanf we need to allocate memory for pointer to character b declared as char *b.

Let us see an example.
#include<stdio.h>
#include<conio.h>
void main()
{
 char a[20]=”raman”; /* a is pointer constant or constant pointer */
 char *b=”raman”;
 printf(“\n printing string character by character by incrementing pointer to character”);
 for(i=0;*b!=’\0’;b++)
        printf(“%c”,*b);

/*
(i) following is invalid
 printf(“\n printing string character by character by incrementing character array”);
 for(;*a!=’\0’;a++)
        printf(“%c”,*a);
 this is invalid because ‘a’ is pointer constant or constant pointer.
(ii)following is valid
 printf(“\n printing string character by character by incrementing i”);
 for(i=0;*(a+i)!=’\0’;i++)
        printf(“%c”,*(a+i));
 because ‘a’ is not being modified in this case.
(iii)following is valid
 q=a; where q has been declared char *q; 
 then
 for(;*q!=’\0’;q++)
        printf(“%c”,*q);
because a is not being modified in this case.

(iv)following is valid
 printf(“\n printing string character by character by incrementing i”);
 for(i=0;*(b+i)!=’\0’;i++)
        printf(“%c”,*(b+i));

*/
getch();
}

Can we store a string in a pointer to character(pointer and string)?
A pointer to character can store a string constant.
#include<stdio.h>
#include<conio.h>
void main()
{
 char *s=”raman”;
/*  or  char *s={‘r’,’a’,’m’,’n’,’\0’};   */
 int i;
 printf(“\n the string is as follows\n”);
 for (i=0;*s!=’\0’;s++)
         printf(“%c”,*s);
/* we can also use printf(“%s”,s);  */
getch();
}

Write a program in c using pointer and function to receive a string and a character as argument and return the no. of occurrences of this character in the string.
#include<stdio.h>
#include<conio.h>
void main()
{
 int count(char *,char);
char a[80],t;
int n;
printf(“\n enter string “);
gets(a);
printf(“\n enter character to search”);
scanf(“%c”,&t);
n=count(a,t);
printf(“\n no. of occurrences=%d”,n);
getch();
}
int count(char *a,char t)
{
 int m,s=0;
for(m=0;a[m]!=’\0’;m++)
   if(t==a[m])
     s++;
return s;
}
  
What is the difference between array of pointer to character and double dimension character array?
Array of pointer
Double dimension character array

if we declare array of pointers to character as follows:
char *a[3]={“ram”,”shyam”,”ajay”};
it consume memory 21 bytes (4 bytes for string ram+ 6 bytes for string shyam+ 5 bytes for string ajay+ 6 bytes for pointer to characters a[0],a[1],a[2]).
Thus it is memory saving if used initialization.
If we declare as below then it will take more computer memory.
char a[3][20]={“ram”,”shyam”,”ajay”};
it will consume memory 60 bytes.
Thus it is more memory consuming if used initialization.

if we declare array of pointers and want to read string during run time of program, we must allocate memory before reading input.
We don’t need allocation of memory before reading strings in double dimensional character array.
         

Differentiate between pointer to constant and constant pointer(pointer constant)?
pointer to constant
constant pointer or pointer constant

If we declare pointer
const int *a;  or int const  *a; then a is pointer to constant.
Suppose:
int p=20;
a=&p;
then we can not  use statement *a=50; to alter value of p.
but we can use statement  a++, a=a+2 etc.

(i)When we declare an array as
int a [5]={1,2,3,4,5};
then ‘a’ denotes base address which is address of first element of array. Base address of array is constant pointer(pointer constant) because we can not write any statement like a++ , a-- , a=a+2 etc. to modify ‘a’.
(ii) when we declare a pointer as
int p=20;
int * const a=&p;  now a is pointer constant or constant pointer, since const appears before ‘a’.
if we write statement
*a=50; will change value of p to 50.
Again we can not write any statement like a++ , a-- , a=a+2 etc. to modify ‘a’.


const is used before or after data type.
const is used between * and variable name

Pointer to constant is useful when actual parameter must not be modified by called function when passing by address.


What does int const *const p=&i ; means?
It means that pointer to constant and constant pointer. This declaration neither allows p++ nor allows *p=20;
Explain the following notations/ differentiate int *m[10] and int (*m)[10].
(i)int (*p)[10];
p is pointer to an array having 10 elements.
(ii)int *p[10];
p is an array of pointers having 10 elements
(iii)int **p;
p is pointer to pointer
(iv) float * p();
p is a function returning pointer to float
(v) float * (*p)();
p is a pointer to function which returns pointer to float
(vi) int (*p)(int,int);
p is a pointer to function which returns integer and takes to integer arguments.
(vii) int (*p[3])(int,int);
p is a an array of pointer to function having 3 elements which returns integer and takes to integer arguments.


Structure and Union:

What is structure?./ write notes on tag and template.
Structure is a user defined data type, similar to record in a database management system. Defining of structure works as template (prototype, model or rubber stamp) from which we can create structure variable. It groups variables into a single entity.
e.g.
struct emp
{
 char name[20];
 int age;
};
this is known as structure declaration. After structure declaration we can create a structure variable as follows:
struct emp e;
now e will be composed of name and age. Name and age are known as data members of structure.
In above example emp is known as structure tag. Structure tag is useful to identify one structure declaration from other when program consists of many structure declaration.

How to declare structure and structure variable/ How can we input/output a structure variable?
#include <stdio.h>
#include <conio.h>
void main()
{
 struct emp
 {
   char name[20];
   int age;
   float salary;
 };
 struct emp e;
 printf(“\n enter name, age salary”);
 scanf(“%s %d %f”,e.name,&e.age,&e.salary);
 printf(“\n name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
 getch();
}
explanation: struct emp e is known as structure variable declaration. Structure variable e is composed of name, age and salary. While using scanf we did not used & in front of e.name because name is character array.

How to declare structure and initialize structure variable?
#include <stdio.h>
#include <conio.h>
void main()
{
 struct emp
 {
   char name[20];
   int age;
   float salary;
 };
 struct emp e={“ramesh”,22,5500};
 printf(“\n name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
 getch();
}
explanation: struct emp e is known as structure variable declaration. Structure variable e is composed of name, age and salary.

What are the local and global structure declaration?
When we write structure declaration inside any function it is known as local structure declaration in this case only the function where structure is declared, we can declare structure variable. When we write structure declaration not inside curly brace it is known as global structure declaration in this case we can declare structure variable inside any function.

What are different forms/variation in structure variable declaration?
They are as follows:
(a)struct emp
     {
       char name[20];
       int age;
     };
     struct emp e;
(b) struct emp
     {
       char name[20];
       int age;
     }e;
    
(c)struct
{
       char name[20];
       int age;
     }e;
     this form of structure declaration did not used structure tag therefore we can not declare any structure       variable from this point onward.

What care we need to take when initializing structure variable?
The values we give for structure variable initialization inside curly brace must match with the order in which data members appears inside structure declaration.
e.g.
 struct emp
{
       char name[20];
       int age;
       float salary;
     };
    struct emp e={“rama”,22}; /* from missing data member if numeric, will be zero , for missing data member
if character array it will be “”  */
if structure declaration is as follows :
struct emp
{
       int age;
       float salary;
       char name[20];
     };
 then initialization will be
 struct emp e={22,4200,”rama”};

What do you mean by structure within structure(nested structure)?
When a structure variable is used as data member in another structure declaration it is known as structure within structure or nested structure.
Let us see one example.
#include<stdio.h>
#include<conio.h>
struct date
{
 int mm,dd,yy;
};
struct emp
{
 char name[20];
 struct date dob;
 int age;
};
void main()
{
  struct emp e;
  printf(“\n enter name ,date of birth (mm dd yy) and age”);
  scanf(“%s %d %d %d %d”,e.name,&e.dob.mm,&e.dob.dd,&e.dob.yy,&e.age);
  printf(“\n name=%s,date of birth (mm dd yy)=%d %d %d,age=%d” ,e.name, e.dob.mm, e.dob.dd, e.dob.yy, e.age);
getch();
}
explanation: e is composed of name, dob and age, and dob is itself composed of mm, dd, yy. When inputting(reading/scanning) we have to use e.name, &e.dob.mm and so on.
Initialization of nested struct will be
struct emp e={“rama”,5,7,1980,23};

What are the different forms of declaration of nested structure?
Forms are:
(a)struct emp
     {
        char name[20];
        struct date
          {
            int mm,dd,yy;
          }dob;
        int age;
      };

(a) struct date
          {
            int mm,dd,yy;
          };
    struct emp
     {
        char name[20];
        struct date dob;
        int age;
      };



What are the different operation which can be performed on structure variable or what are the operations can be performed on union?
On Structure/Union  variable we can perform following operation:these concept of operations are useful while learning c++ in next sem/year therefore should be learn carefully.
1.     we can assign one structure/union variable to other structure/union variable when both belong to same structure/union.
2.     we can initialize the structure/union variable.
3.     we can access value of data member of structure/union using . (dot ) known as member access operator.
4.     we can assign value to data member of structure/union.
5.     we can declare array of structure/union
6.     we can pass structure/union variable to function by value.
7.     we can pass array of structure/union to function(passed as reference).
8.     we can pass a structure/union variable to function by reference.
9.     function can return structure/union variable and can take structure as argument.
We can not use existing operator +,-,*,/ on two structure/union variable.
e.g. c3=c1+c2; are invalid.

How can we assign a structure variable to another structure variable belonging to same structure declaration?
Let us see with one example.
#include <stdio.h>
#include <conio.h>
void main()
{
 struct emp
 {
   char name[20];
   int age;
   float salary;
 };
 struct emp e={“ramesh”,22,5500},f;
 f=e;
 printf(“\n name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);

 printf(“\n name=%s,age=%d,salary=%f”,f.name,f.age,f.salary);
 getch();
}
output will be name=ramesh,age=22,salary=5500.000000
output will be name=ramesh,age=22,salary=5500.000000

How can we assign values to data members of structure variable?
Let us see one example
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
 struct emp
 {
   char name[20];
   int age;
   float salary;
 };
 struct emp e;
 strcpy(e.name,”ramesh”);
 e.age=22;
 e.salary=5500;
 printf(“\n name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);

getch();
}
output will be name=ramesh,age=22,salary=5500.000000

No comments:

Post a Comment