Saturday 2 September 2017

EASY NOTES ON C LANGUAGE PART 2







NOTES FOR C LANGUAGE PART 2


 






Write short notes on switch statement/ what will happen if break is absent in switch statement?
The control statement which allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default. Since these three keywords go together to make up the control statement. They most often appear as follows:
switch(integer or character expression)
{
case constant1:
do this;
and this;
case costant2:
do this;
and this;
}
the integer expression following the keyword switch is any ‘c’ expression that will generate an integer value. It could be an integer constant like 1,2,3 or an expression that evaluates to an integer or any character constant .
The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the others. The “do this and this” lines mentioned above are replaced in actual practice with valid ‘c’ statements.
What happens when we run a program containing a switch? First, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statement. When a match is found, then program executes the statements following that case, and all subsequent case and default statements as well. If no match is found with any of the case statement, only the statements following the default are executed. A few examples will show how this control works.
Understanding what happens when break is absent in switch?
#include <stdio.h>
#include<conio.h>
void main()
{
int i =2;
switch(i)
{
case 1:
printf(“\n I am in case 1”);
case  2:
printf(“\n I am in case 2”):
case 3:
printf(“\n I am in case 3”);
default:
printf(“\n I am in default”);
}
getch();
}
out put:
I am in case 2
I am in case 3
I am in default

#include <stdio.h>
#include<conio.h>
void main()
{
int i =2;
switch(i)
{
case 1:
printf(“\n I am in case 1”);
break;
case  2:
printf(“\n I am in case 2”):
break;
case 3:
printf(“\n I am in case 3”);
break;
default:
printf(“\n I am in default”);
}
getch();
}
out put:
I am in case 2
If you want that only case 2 should be executed, it is up to you to get out of the control structure then and thereby using a break statement.

Consider following example:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf(“\n enter a alphabet a,b or c”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘a’:
case ‘A’:
printf(“\n a for apple”);
break;
case ‘b’:
case ‘B’:
printf(“\n b for ball”);
break;
case ‘c’:
case ‘C’:
printf(“\n c as cat”);
break;
default:
printf(“\n wish you knew what are a,b and c”);
}
getch();
}
Here, we are making use of the fact that once a case is satisfied the control simply falls through the case till it doesn’t meets a break statement. That is why if an alphabet a is enter the case ‘a’ is satisfied and since there are no statements to be executed in this case the control automatically reaches the next case i.e. case ‘A’ and executes all the statements in this case and comes out of the control structure due to break statement.

State the difference between switch and if
switch
1.All programs made using switch can be solved using if
2. ‘switch’ can not have case like case i<=20
3. ‘switch’ leads to more structured programming and level of indentation is manageable even if we have nested switch.
if-else
All programs made by ‘if’ are not possible to solve by ‘switch’.
‘if’ can have condition like i<=20 && i>=10.
 
‘if’ leads to less structured programming and level of indentation is difficult to manage if using nested ‘ifs’.

How can we get input and output of string/ what is the difference between gets and scanf for character array?
We can get input and output of string in following ways

#include<stdio.h>
#include<conio.h>
 
void main()
{
char a[40];
printf(“\n enter a string”);
scanf(“%s”,a);
printf(“\n string is %s”,a);
getch();
}

#include<stdio.h>
#include<conio.h>
 
void main()
{
char a[40];
printf(“\n enter a string”);
gets(a);
printf(“\n string is %s”,a);
getch();
}

#include<stdio.h>
#include<conio.h>
 
void main()
{
char a[40];
printf(“\n enter a string”);
gets(a);
puts(“string is “);
puts(a);
getch();
}
 


difference between gets and scanf: gets’ can read  multiple words but scanf can not read multiple words. e.g. input “surendra verma” for program in first column then output will be “surendra” only the reason behind this is scanf(“%s”,a) stops scanning when it meets space.
input “surendra verma” for program in second column then output will be “surendra verma”

Third column explain uses of  ‘puts’ library function ,puts library function accepts string or character array and prints it in new line.

What do you mean by general Input/Output?
General input output means how we can read values for variable or how we can display value of constants and variables in desired format.
Consider following examples of general output facilities offered by printf.
printf with formatting(output formatting):-
#include<stdio.h>
#include<conio.h>
void main()
{
float f_var=10.12576893;
int wid_prec;
/* output 1: Ordinary output.*/
printf(“Output 1:%f\n”,f_var);
/*output 2: Output in a field of width 20 (direct specification)*/
printf(“Output 2: %20f\n”,f_var);
/*output 3: same as above, but left justified.*/
printf(“Output 3: %-20f\n”,f_var);
/*explicit sign display*/
printf(“Output 4: %+f\n”,f_var);
/*Output 5: Indirect width specification (Compare Output 2)*/
printf(“\n enter width”);
scanf(“%d”,&wid_prec);
printf(“Output 5: %*f\n”,wid_prec,f_var);
/* output 6 precision specification 5 digits with rounding */
printf(“Output 6: %.5f\n”,f_var);
/* output 7 precision specification 5 digits indirect with rounding */
printf(“\n enter precision”);
scanf(“%d”,&wid_prec);
printf(“Output 7: %20.*f\n”,wid_prec,f_var);
/*output *: a combination of field width of 20,left justify,explicit sign, precision of 5 */
printf(“Output 8: %+20.5f\n”,f_var);
getch();
}
scanf width specifier and input formatting :-
#include<stdio.h>
#include<conio.h>
void main()
{
char string1[40],string2[40];
printf(“enter two strings”);
scanf(“%4s %5s”,string1,string2);
printf(“\n the two input strings are %s %s”,string1,string2);
getch();
}
for input of two string “morning” and “comes” output will be “morn” and “ing”.

What are the different types of characters which can appear in format string?
Different types of characters are:
White space characters (tab, space , new-line), ordinary characters and format specifier.

What do you mean by search sets?
When reading values for  variables we want to separate the values being input by some separator characters; those separator characters constructs search set. Search set are set of characters enclosed in square brackets []. These search sets are parts of some format specifier. for example , the format specifier %[/-].
This tells ‘scanf’ to match any sequence of characters consisting of / and -.  All these characters are assigned to the corresponding argument. This argument must be the  name of character array. Let us see how search sets are used.
#include<stdio.h>
#include<conio.h>
void main()
{
int date,month,year;
char sep[2];
printf(“\n enter the date:”);
scanf(“%d%[/-]%d%[/-]%d”,&date,sep,&month,sep,&year);
printf(“\n date =%d,month=%d,year=%d”,date,month,year);
getch();
}
If input was 31-13/1999
The output will be
date=12 month=12 year=1999

Explain assignment suppression character./what is the purpose of assignment suppression character?
Till now we were having one argument for every format specifier in the format string. Sometimes this is unnecessary, as shown in above example. Using an assignment suppression character tells the ‘scanf’ that input field should only be scanned and not assigned to any argument(variable).
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int date,month,year;
printf(“input the date:”);
scanf(“%d*[/-]%d*[/-]%d”,&date,&month,&year);
printf(“\n date =%d,month=%d,year=%d”,date,month,year);
getch();
}
if input was 31-13/1999
the output will be
date=12 month=12 year=1999
we can note there are 5 format specifiers but only 3 argument(variables).
The corresponds are shown as
Format specifier
Argument

%d
&date

%*[/-]
(no argument)

%d
&month

%*[/-]
No argument

%d
&year

What is use of sizeof Operator?
‘sizeof’  operator allows to find out memory taken in no. of bytes by a variable or data type as illustrated.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
float b;
printf(“\n no. of bytes taken by an integer=%d”,sizeof(a));
printf(“\n no. of bytes taken by an integer=%d”,sizeof(int));
printf(“\n no. of bytes taken by an integer=%d”,sizeof(float));
getch();
}
in this example output would be 2 2 and 4 because int takes 2 bytes and float takes 4 bytes.

What is use of const keyword (qualifier)?
const keyword is useful to declare a constant with a given symbolic name whose value can not change during program run time.
#include<stdio.h>
#include<conio.h>
const float pi=3.1415;
void main()
{
float area,r;
printf(“\n enter radius of circle”);
scanf(“%f”,&r);
area=pi*r*r;
printf(“\n area=%f”,area);
getch();
}

What is output of following statement-viva?
int i=0;
printf(“\n %d %d”,i,i++);
output will be: 1  0

What is return value of scanf?
Answer
(a)1 for successful scanf,
(b)0 for unsuccessful scanf  or encountering end of file
(c)Nothing if program indicates abnormal termination.

What is output of following statement?
char name[]=” ”;
scanf(“%c”,name);
printf(“%s”,name);
output will be : any character equivalent of address of array due to %c
and space due to %s.

What do you mean by nested loop?
nested loop is a special case in which one loop contains other loop inside its loop body. for each value of outer loop counter , inner loop counter changes frequently.
e.g. program to print reverse pyramid
#include<stdio.h>
#include<conio.h>
void main()
{
int m,n;
for(m=5;m>=1;m--)
{
for(n=1;n<=5-m;n++)
printf(“ “);
for(n=1;n<=2*m-1;n++)
printf(“*”);
printf(“\n”);
}
getch();
}

Write program to evaluate 1/!1+2/!2+3/!3+…
#include<stdio.h>
#include<conio.h>
void main()
{
float term,m,s=0;
int n;
printf(“\n how many terms to evaluate”);
scanf(“%d”,&n);
term=1;
for(m=1;m<=n;m++)
{
printf(“\t %f”,term);
s=s+term;
term=term/m;
}
printf(“\n sum=%f”,s);
getch();
}



Define Array.
Array or Subscripted variables:
Array is collection of variables having common name and common data type. Individual variable in collection is identified by index or subscript. Elements of array occupy contiguous memory location.

How can we declare a single dimension Array?
Declaration (single dimension numeric array):
int a[5];
‘a’ is name of array and ‘a’ denotes address of first element of array known as base address and ‘a’ is constant.
it means there are 5 variables viz. a[0],a[1],a[2],a[3],a[4] index or subscript will change from 0 to 4. All variables will be integers.
float b[10];
It means there are 10 variables viz. a[0],a[1],a[2],a[3]….a[9] index or subscript will change from 0 to 9. All variables will be floats.

How we can initalise an array?
Initialization of single dimension array (numeric):
int  a[5]={2,1,3,4,6};
which means a[0]=2,a[1]=1,a[2]=3,a[3]=4,a[4]=6;
int  a[]={2,1,3,4,6};
which means a[0]=2,a[1]=1,a[2]=3,a[3]=4,a[4]=6; and size of array will be 5. index will range from 0 to 4.
int  a[5]={2,1,3};
which means a[0]=2,a[1]=1,a[2]=3,a[3]=0,a[4]=0; and size of array will be 5. index will range from 0 to 4.
memory scheme of array of integers having  5 elements
A[0]
A[1]
A[2]
A[3]
A[4]

100
102
104
106
108
memory scheme of array of floats having  5 elements

A[0]
A[1]
A[2]
A[3]
A[4]

100
104
108
112
116

following is not correct:
int  a[3]={2,1,3,4};
This will result in compile time error.

What special keyword is used in initialization of character arrays in c?
ans: static

What are the three different ways to assign values to string variables?
ans :
char a[]=”ramesh”;
char a[]={‘r’,’a’,’m,’e’,’s’,’h’,’\0’};
strcpy(a,”ramesh”);

What is a null statement?
null statement is a statement terminated by ; without any statement.

What are the usages/Applications of Array?
Application of arrays:
* It is useful to solve simultaneous equation.
* It is useful to solve problems of data structure like searching, sorting, linked list, graph etc.
* Its is useful to solve such problems requiring variable of same data type in contiguous memory location.

If an array is declared as int a[5] can we access element a[5]?
No. if an array is declared as int a[5] then index will range from 0 to 4, element with index does not exist.
Don’t access array element which doesn’t exist.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
a[6]=11;
printf(“\n value of element with index 6 =%d”,a[6]);
getch();
}
Above program will not  generate any compile error but it may result the error ‘program has performed an illegal operation’ if window 9x session is active.

What does ‘a’ means if an array is declared as int a[5]?
Name of address denotes address of first element of address known as base address of array. Base address of an array is a constant-pointer or pointer-constant.
#include<stdio.h>
#include<conio.h>
void main()
{ int a[5];
printf(“\n base address of  array =%u”,a);
getch();
}

Write program to input an array of integers having 5 elements and find its sum.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,sum=0;
printf(“\n enter 5 values for array a:”);
for (i=0;i<5;i++)        /* input routine for array elements */
scanf(“%d”,&a[i]);
for(i=0;i<5;i++)       /* sum the values of array elements */
sum=sum+a[i];
printf(“sum=%s”,sum);
getch();
}


What is string ? How character array can be declared and initialized?
Collection of characters having last character null character (‘\0’) is known as string. a single character variable can store a single character enclosed in single quote. Sometimes it is required to store name, address and other alphanumeric or special characters; in that case pointer to character or character array is the only solution.
Declaration:
char a[40];
a is a character array having no. of elements 40 and index varying from 0 to 39. we can store maximum 39 character leaving one space for null character.
Initialization:
char a[40]=”ramesh” ;
or
char a[40]={‘r’,’a’,’m’,’e’,’s’,’h’,’\0’};
or
char a[]=”ramesh”;  /* in this case array size will be 7(including hidden null character) and index will range from index 0 to 6 */

program to initialize, input and print the strings.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[]=”ramesh”;  /* initialization of character array */
char b[40];
printf(“\n enter a string:”);
scanf(“%s”,a); /* do not use &a */
printf(“\n first string is %s,second string is %s”,a,b);
getch();
}

Write program to find rotation of given string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[20];
int i,n,j;
int len;
printf("\n enter a string");
scanf("%s",a);
len=strlen(a);
clrscr();

for(n=1;n<=len;n++)
{
printf("\n");
for(j=0;j<len;j++)
printf("%c",a[(j+n)%len]);

}
getch();
}

Write program to find whether a word/number is palindrome or not?
#include<stdio.h>
#include<conio.h>
void main()
{
char a[40];
char t;
int m,n;
printf(“\n enter word/number to check palindrome”);
scanf(“%s”,a);
/* count no. of characters */
for(m=0;a[m]!=’\0’;m++);
/* position m to last physical character */
m=m-1;
/* compare first and first from last side character and so on */
for(n=0;n<=m;m--,n++)
{
if(a[n]!=a[m])
break;
}
if (n<=m)
printf(“\n not palindrome”);
else
printf(“\n palindrome”);
getch();
}

Write program to find greatest no. in a list of values.
#include<stdio.h>
#include<conio.h>
void main()
{
float a[5];
int i,p;
float max;
printf(“\n enter five values”);
for(i=0;i<5;i++)
scanf(“%f”,&a[i]);
max=a[0];
p=i;
for(i=1;i<5;i++)
if (max<a[i])
{
max=a[i];
p=i;
}
printf(“\n largest value=%f at index=%d”,max,p);
getch();
}

Write program to arrange the alphabets of an entered string in alphabetical order.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[80],t;
int n,m,len;
printf(“\n enter a string”);
gets(a);
/* count no. of characters in string */
for(len=0;a[i]!=’\0’;len++);

/* use bubble sort */
for(m=0;m<len-1;m++)
for(n=0;n<len-1-m;n++)
{
if(a[n]>a[n+1])
{
t=a[n];
a[n]=a[n+1];
a[n+1]=t;
}
}
printf(“\n sorted string is %s”,a);
getch();
}

Write a program to copy one string to other string without using library function?
#include<stdio.h>
#include<conio.h>
void main()
{
char a[40];
int
printf(“\n enter the string”);
gets(a);

#include<stdio.h>
#include<conio.h>
void main()
{
char a[20],b[20];
int j;
printf(“\n enter first string”);
gets(a);
for(j=0;a[j]!=’\0’;j++)
b[j]=a[j];
b[j]=’\0’;
printf(“\n string copied to b as %s”,b);
getch();
}
What is Multi Dimension Arrays? What are their usages?
Array declared with more than one dimension is know as multi-dimension array.
Often multi dimension array is needed to store data for table and matrices. Multi -dimension array has more than one subscript. Two dimension array contains two subscript, three dimension array has three subscript and so on.

Understanding declaration, initialization
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2]; /* declaration of  2d array having total no. of elements 3*2=6 */
int b[3][3]={2,1,3,2,4,5,6,7,8};
int i,j;
printf(“\n enter 6 values for array a”); /* input routine for array of 3x2 */
for(i=0;i<3;i++)
for (j=0;j<2;j++)
scanf(“%d”,&a[i][j]);

/* print contains of array a then array b*/
printf(“\n contents of array a:”);     /* output routine for array 3x2 */
for(i=0;i<3;i++)
{
for (j=0;j<2;j++)
printf(“\t%d”,&a[i][j]);
printf(“\n”);
}

printf(“\n contents of array b:”);

for(i=0;i<3;i++)
{
for (j=0;j<3;j++)
printf(“\t%d”,b[i][j]);
printf(“\n”);
}
getch();
}

Understanding initialization of array b


Column index  0
Column index 1
Column index 2

Row index 0
2
1
3

Row index 1
2
4
5

Row index 2
6
7
8






Write program to add, multiply two matrix of 3x3
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3];
int m,n,p;
printf(“\n enter 9 values for matrix a\n”);
for(m=0;m<3;m++)
for(n=0;n<3;n++)
scanf(“%d”,&a[m][n]);

printf(“\n enter 9 values for matrix b\n”);
for(m=0;m<3;m++)
for(n=0;n<3;n++)
scanf(“%d”,&b[m][n]);

printf(“\n result of matrix addition\n”);
for(m=0;m<3;m++)
{
for(n=0;n<3;n++)
{
c[m][n]=a[m][n]+b[m][n];
printf(“\t %d”,c[m][n]);
}
printf(“\n”);
}

printf(“\n result of matrix multiplication\n”);
for(m=0;m<3;m++)
{
for(p=0;p<3;p++)
{
c[m][p]=0;
for(n=0;n<3;n++)
{
c[m][p]=c[m][p]+a[m][n]*b[n][p];
}
printf(“\t %d”,c[m][p]);
}
printf(“\n”);
}
getch();
}

Write program to transpose matrix of 4x4 order
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4][4],c[4][4];
int m,n;
printf(“\n enter 16 values for matrix a”);
for(m=0;m<4;m++)
for(n=0;n<4;n++)
scanf(“%d”,&a[m][n]);

for(m=0;m<4;m++)
for(n=0;n<4;n++)
c[n][m]=a[m][n];

printf(“\n result of matrix transpose”);
for(n=0;n<4;n++)
{
for(m=0;n<4;m++)
{
printf(“\t %d”,c[n][m]);
}
printf(“\n”);
}
getch();
}

Write program to sum diagonal elements of square matrix of 3x3 order
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3];
int m,n;
int fd=0,bd=0;
printf(“\n enter 9 values for matrix a”);
for(m=0;m<3;m++)
for(n=0;n<3;n++)
scanf(“%d”,&a[m][n]);

for(m=0;m<3;m++)
{
fd=fd+a[m][m];
bd=bd+a[m][2-m];
}
printf(“\n sum of forward diagonal=%d,backward diagonal=%d”,fd,bd);
getch();
}

Write program to make diagonal elements of square matrix of 3x3 order to zero
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3];
int m,n;
printf(“\n enter 9 values for matrix a”);
for(m=0;m<3;m++)
for(n=0;n<3;n++)
scanf(“%d”,&a[m][n]);

for(m=0;m<3;m++)
{
a[m][m]=0;
a[m][2-m]=0;
}
printf(“\n result of making diagonal elements zero”);
for(n=0;n<3;n++)
{
for(m=0;n<3;m++)
{
printf(“\t %d”,a[n][m]);
}
printf(“\n”);
}
getch();
}

Write program to sum row elements and column element of matrix of order 3x3
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3];
int m,n;
int rs=0,cs=0;
printf(“\n enter 9 values for matrix a”);
for(m=0;m<3;m++)
for(n=0;n<3;n++)
scanf(“%d”,&a[m][n]);


for(m=0;m<3;m++)
{
cs=0;
for(n=0;n<3;n++)
cs=cs+ a[m][n];
printf(“\n column sum=%d”,cs);
}
for(m=0;m<3;m++)
{
rs=0;
for(n=0;n<3;n++)
rs=rs+ a[n][m]; /* index interchanged */
printf(“\n row sum=%d”,rs);
}
getch();
}

How can we declare and initialize?
An array of strings is collection of strings which can be stored by double dimension array of characters.
Declaration of array of strings or double dimension character array:
char a[5][20];
it means that a is capable of holding 5 strings each having 19 characters maximum, leaving one space for null character.
Intialization of array of strings
char a[5][20]={“ram”,”shyam”,”ajay”,”vijay”,”murli”};
internal storage of character constant would be as follows:
Row/index
0
1
2
3
4
5
….
19

0
‘r’
‘a’
‘m’
‘\0’






1
‘s’
‘h’
‘y’
‘a’
‘m’
‘\0’




2
‘a’
‘j’
‘a’
‘y’
‘\0’





3
‘v’
‘i’
‘j’
‘a’
‘y’
‘\0’




4
‘m’
‘u’
‘r’
‘a’
‘l’
‘i’
‘\0’



Program on array of string input and printing the array of strings.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[5][20];
int i;
printf(“\n enter 5 strings”);
for (i=0;i<5;i++)
scanf(“%s”,a[i]); /* input routine for array of strings */
printf(“\n the strings are \n”);
for(i=0;i<5;i++)
printf(“\n %s”,a[i]);
getch();
}

Write program to demonstrate use of string library functions supported by string.h/ write any 5 string handling library function?
/* note header files can be included in any order */
#include<string.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char a[20],b[20];
int i;
/* demo of string copy function ‘strcpy’ used to copy one string to other follows now.
strcpy(destination-single dimension-character-array, source-single dimension character array or string).
*/
printf(“\n enter a string :”);
scanf(“%s”,a);
/* now copy contents of character array a to b */
strcpy(b,a);  /* destination is given first */
printf(“\n copied string into b is %s”,a);

/* demo of string concatenation (string addition ) begins now */
/*  strcat(character array to add in, string or character array need to add )*/
printf(“\n enter first string “);
scanf(“%s”,a);
printf(“\n enter second string”);
scanf(“%s”,b);
/* note: when contents of character array (string) ‘b’ is added to ‘a’; capacity of array ‘a’ must be such that it is able to accommodate both contents of array ‘a’ and ‘b’ */
strcat(a,b);
printf(“\n new contents of array is %s”,a);


/* demo of  string comparisons begins now
two string can not be compared using >,<,>=,<= but we have to use strcmp for comparison. When comparing two strings if first string comes first in alphabetical order then it will be smaller than second string which comes later in alphabetical order. Never think no. of characters decides which string is smaller and which string is greater.
strcmp returns value >0 if string1 comes later when compared to string2 in alphabetical order
strcmp returns value =0 if string1 and string2 are exactly equal.
strcmp returns value<0 if string1 comes before when compared to string2 in alphabetical order
for case insensitive comparison of strings use strcmpi in place of strcmp syntax is similar. E.g. if  string “ram” is contained in character array ‘a’ and “Ram” is contained in character array ‘b’ strcmp will give return value >0 because letter ‘r’ has greater ascii value when compared to letter ‘R’ but strcmp will give return value 0  */
printf(“\n enter first string “);
scanf(“%s”,a);
printf(“\n enter second string to compare”);
scanf(“%s”,b);
i=strcmp(a,b);
if (i<0)
printf(“\n first string is smaller”);
elseif (i>0)
printf(“\n first string is greater”);
else
printf(“\n both the strings are equal”);


/* strlen function gives no. of characters inside a character array or string
syntax is
int_variable=strlen(character array or string constant) */
i=strlen(“ramesh”); /* or use i=strlen(a); to know no. of characters entered into character array ‘a’ */
printf(“\n no. of characters in string =%d”,i);

/* strreverse reverses contents of a character array and returns pointer to reversed string
syntax is
strrev(character array or string);
or
char *p;
p=strrev(character array or string) */
printf(“\n enter a string to reverse”);
scanf(“%s”,a);
strrev(a);
printf(“\n reverse string is %s”,a);

/* strlwr converts an string or contents of character array to small letters
strupr converts an string or contents of character array to capital letter */
printf(“\n enter a string to convert to uppercase “);
scanf(“%s”,a);
strupr(a);
printf(“\n string in upper case is %s”,a);
strlwr(a);
printf(“\n string in lowe case is %s”,a);
getch();
}

What is function?
a number of statements grouped into a single logical unit is referred to as a function which is made to complete a specific task. A program can be made of many functions but ‘main’ is the function whose statements are executed first.
Types of functions:
User defined function: these are those functions which are made by programmer for his programming convenience.
Library function: these are those functions which are readymade and are provided by compiler, uses of which are possible by including corresponding header files. Source code of library function is not available to programmer but its object codes are available in precompiled form.

List out header files in ‘c’/write notes on library functions. Why they are needed?
list of header files
we need to include header file in our program to utilize library function, macro definition and structure declaration contained in header file.
though there are many header files in c. some of the quite commonly used header file are discussed here.
#include <stdio.h>
supports printf, scanf, getchar etc.
#include <math.h>
supports some math related function.
A=sqrt(25);  now A will have 5
A=pow(3,2); now A will have 9
A=abs(-5); now A will have 5
#include<conio.h>
clrscr();  this statement will clear screen
c=getch(); this will assign a character to variable c
#include<ctype.h>
c=toupper(‘a’);  now c will have uppercase letter ‘C’
c=tolower(‘A’); now c will have lowercase letter ‘a’
#include<time.h>
time.h includes clock, ctime, stime, asctime, difftime, time  and many more time related library functions.
#include<dos.h>
supports exit etc.
#include<stdlib.h>
supports malloc,calloc,free,realloc functions to dynamically allocate memory
#include<string.h>
support library function strlen,strcpy,strupr etc. for string related operation.


Explain ‘main’ function.
‘main’ is a function which is called by operating system when a program is run. ‘main’ is the foremost function which gets executed even if program is made up of several functions.
Execution of other function: other function executes when the ‘main’ function calls it directly or indirectly ( ‘main’ function calls a function and in turn the called function calls another function and so on). Each program must contain a function ‘main’ otherwise  program will not compile.
e.g.
#include<stdio.h>
void main()
{
printf(“ welcome to c programming”);
}
This program contains a preprocessor #include directive, a function heading void main()  where void indicates function does not return a value, a function body inside curly braces, a printf statement to print message ‘welcome to c programming’.

What are the usages/applications of functions?
Usages are as follows:
1.           Function avoids code repetition:- once a function has been made we can call the function to complete the task when and where necessary.
2.           Function used carefully makes the process of error removing easier called debugging.
3.           Once function is tested and satisfies the one’s needs, one can convert it in to library, and can distribute it others for use.
4.           Function allows breaking bigger task into smaller manageable subtasks which is soul of modular programming.
5.           Recursive function (function calling itself at least once) solves some typical programming tasks easily and with few lines of coding which otherwise would have taken several lines of code.

What is the format of function?
format of function is as follows:
<return data type> function-name (datatype var1,datatype var2…)
{
statement1.
statement2.
<return value/variable>
}

Define various key concepts/components applicable to function.
Let us explore the various key concepts associated with function using a simple example:
Program to add two numbers(function using more than one parameter/argument)/
Function returning value and function taking argument.
1.           #include<stdio.h>
2.           #include<conio.h>
3.           void main()
4.           {
5.           int a,b,c;
6.           int add(int,int);
7.           printf(“\n enter two values:”);
8.           scanf(“%d %d”,&a,&b);
9.           c=add(a,b);
10.       printf(“\n addition=%d”,c);
11.       getch();
12.       }
13.       int add(int x, int y)
14.       {
15.       int z;
16.       z=x+y;
17.       return z;
18.       }
(a) function declaration or prototype(line no 6):
function prototype or function declaration is as follows
int add(int ,int);
int add(int x,int y);
int add(int,int y);
int add(int x,int);
all these are applicable.
It means that name of variables or optional and if we like we can leave these.
int indicates data type of the value that the user define function will return.
If we use function declaration as :
int add(int x,int y);
It does not mean that we can use variable x and y inside main function without declaring these variables.
Similarly if we use function declaration as :
int add (int a,int b);
It does not mean that we can use variable a and b inside main function without declaring these variables.
If we use function declaration as :
int add(int x,int y);
then x and y are know as dummy/formal   parameter/argument.
Following declaration or prototyping is not allowed
int add(int x,y); this will generate error.
(b) function call(line no. 9):
Function call statement is as follows:
c=add(a,b);
following are incorrect way of calling function:
c=add(int a,b);
c=add(int a,int b);
c=add(int ,int b);
etc.
it means that while calling function never prefix data type just give name of variable or give constant or combination of constant or variable or any mathematical expression
e.g.
c=add(3,a);
c=add(a,b);
c=add(4*5+3,b);
etc.
name of variable or constant or expression given here is know as actual parameter/argument.
The function call statement causes control to be transferred to user defined function and value of variable b is copied to variable z and value of variable a is copied to x ( right to left). Function stores addition of variable x and y to z and value of z in turn is assigned to variable c in main function. Now statement followed by function call inside main starts execution.
(c) Function header line or function declarator (line no. 13):
It could be written as follows:
int add(int x,int y)  /* y will receive value of main’s b and x will receive value of main’s a */
int add(int a,int b)  /* b will receive value of main’s b and a will receive value of main’s a */
int add(int x,int b)  /* b will receive value of main’s b and x will receive value of main’s a */
etc.
but  followings are incorrect:
int add (int x,y)  /* correct way is  int add(int x,int y) */
int add(int,int)   /* variable names are not optional here */
int add(int x,int y);  /*  don’t use semicolon here */
if we find in some books
int add(a,b)
int a,b;
{
----
----
}
we must change this to:
int add(int a,int b)
{
--
--
}
(c) Function body(line no. 14 to 18)
Function body is made up of  line no. 14 to 18. function body is surrounded by brace.
Function body contents the statements which are necessary to perform the task for which function is made. Function body and function header line makes function definition.
(d) Function return value(line no. 17):
This statement is useful to send value calculated by called function to calling function.
Calling function can send value of variables or constant using actual argument when function is called. Called function can send either one value(if function has return type) or zero value(if function has no return type) using return statement to calling function.
Calling function is the function which calls another function in our example it is main.  Called function is the function which is called by calling function.
Following points are note worthy:
(i)We can not use variables declared in called function inside calling function without declaring them in called function.
(ii) We can not use variable declared in called function in calling function without declaring them in calling function.
(iii) If function header line contents :
int add(int x,int y) then don’t declare int x,y inside function body of called function otherwise it will generate error. Don’t assign new value to variable x and y otherwise you will loose values passed by actual arguments during function call.
(iv) Assigning new value to variables x and y will not change value of variable a and b in our example(call by value).
(v) Omission of function prototype or declaration: if function definition occurs before call of function it is possible to remove function declaration or function prototype.
Function prototype can be global. If function declaration is global any function can call the user defined function.
to do so –
Put function declaration outside curly brace of any function’s body.
Function prototype can be local. If function declaration appears inside function body of any function, function prototype becomes local in such case only the function whose function body contents the function declaration can call the user defined function.

What is function parameter/differentiate actual and formal parameter?
Function parameters are means of communication between the calling and the called function. They can be classified into formal parameters and actual parameters. The formal parameters are the parameter given int the function declaration and function definition. The actual parameters or actual arguments, are specified in the function call statement.
While using parameters followings points are important:
1.           the number of arguments in the function call and function declarator and function declaration must match.
2.           the data type of each of the arguments in the function call should be the same as corresponding parameter in the function header-line (function-declarator) and  function declaration.

What is function definition?
Function definition contents function declarator( or function header line) and function body. Function body includes all those statements which will complete the task  for which function is made.

What is function declaration?
Function declaration specifies return data type of function, name of function and data type of arguments, if any. Function declaration is necessary if function is called first and defined later.  Number of arguments/parameters and corresponding data type must match when calling function and when writing function declarator.
Function declaration can be dropped if definition of function appears before function call. Function declaration can be global or local. If function declaration appears inside curly brace of any function body it is known as local function declaration in such case the function whose function body contains function declaration can call the user defined function. If function declaration does not fall inside curly brace every function can call the user defined function and function declaration is known as global function declaration.

What is return statement?
Return statement is means of communication between called function and calling function as the return statement meets control is transferred to calling function.
(a)return statement can be used to pass a single value to calling function if function returns a value.
return statement will take form:
return variable;  (or return constant;)
(b)return statement can be used to return the control to the calling function prematurely .
(c)if function does not return any value then return statement will take form
return ;
(d) a function body can use return statement more than one times.

What do you mean by parameter/argument passing technique? Or what do you mean by call by value or call by reference or differentiate call by value and call by reference. or Explain passing value between function.
‘C’ provides two mechanisms to ass arguments to a function
(i)pass arguments by value, and
(ii)pass arguments by address or pointer or reference.
Ordinary variable ( not array) is always passed by value which states that value of actual argument can not be altered by called function.
Array is always passed by reference therefore any changes made to value of elements of an array inside called function will change value of actual parameter.
If it is required to change value of actual argument which is ordinary variable(not array) we need to pass its address or pointer which is know as call by reference.
Consider a example of swapping two numbers:
(i) call by value
#include<stdio.h>
#include<conio.h>
void main()
{
int a=3,b=4;
void swap(int,int);  /* function declaration */
printf(“\n before call of function swap value of a and b inside main %d %d”,a,b,);
swap(a,b);
printf(“\n after call of function swap value of a and b inside main %d %d”,a,b,);
getch();
}
void swap(int a,int b)
{
int t;
printf(“\n before swapping  value of a and b inside called function %d %d”,a,b,);

t=a;
a=b;
b=t;
printf(“\n after swapping inside called function value of a and b %d %d”,a,b,);
}
program will give output:
before call of function swap value of a and b inside main 3 4
before swapping  value of a and b inside called function 3 4
after swapping inside called function value of a and b 4 3
after call of function swap value of a and b inside main 3 4
clearly value of actual argument did not change to 4 3.
(ii) call by reference or address or pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int a=3,b=4;
void swap(int*,int*);  /* function declaration */
printf(“\n before call of function swap value of a and b inside main %d %d”,a,b,);
printf(“\n before call of function swap address of a and b inside main %u %u”,&a,&b,);

swap(&a,&b);
printf(“\n after call of function swap value of a and b inside main %d %d”,a,b,);
printf(“\n after call of function swap address of a and b inside main %u %u”,&a,&b,);

getch();
}
void swap(int *a,int *b)
{
int t;
printf(“\n before swapping  value of a and b inside called function %d %d”,*a,*b,);

t=*a;
*a=*b;
*b=t;
printf(“\n after swapping inside called function value of a and b %d %d”,*a,*b,);
}
program will give output:
before call of function swap value of a and b inside main 3 4
before call of function swap address of a and b inside main 3210 3212

before swapping  value of a and b inside called function 3 4
after swapping inside called function value of a and b 4 3

after call of function swap value of a and b inside main 4 3
after call of function swap address of a and b inside main 3210 3212);
clearly value of actual argument changed to 4 3.



No comments:

Post a Comment