Simple If If ..Else Nested If ..Else Else .If
Simple If If ..Else Nested If ..Else Else .If
Unit –II
Control Structure
Decision Making And Branching Looping:
In c the following are the control or decision making statements:
If statement
Switch statement
Goto statement
If statement
Simple if
if …..else
Nested if……..else
else…….if
Simple if:
Syntax: if(condition)
{
statement _block;
}
statement_x;
If the condition is true, the statement block will be executed. Otherwise, statement_block will be skipped
and the execution will jump to statement_x.
When the condition is true both statement block and statement x will be executed in sequence.
Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
1
a=30;
b=20;
if(a>b)
{
a=a+b;
}
printf(“%d”,a);
getch();
}
The output is: 50.
In this program, value of a is 30 and value of b is 20. Check the condition (a>b) if it’s true the
control execute the statement a=a+b and print the value of a. Otherwise the control execute only one statement
that statement is print the value of a.
if….else:
Syntax:
if(condition)
{
true _block statement;
}
else
{
false _block statement;
}
statement_x;
if condition is true, true _block statements will be executed. Otherwise, false _block statements will be executed.
Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
a=30, b=20;
if(a>b)
{
printf(“a is greatest”);
}
2
else
{
printf(“b is greatest”);
}
printf(“\n
Welcome”); getch();
}
The output is: a is greatest
Welcome
If condition is true, print the statements “a is greatest” and “Welcome”. Otherwise print the statements “b
is greatest” and “Welcome”.
Nested – if statements
Here more than one if….else statements are nested.
Syntax:
if( condition1)
{
if(condition2)
{
statement_1;
}
else
{
statement_2;
}
}
else
{
statement_3;
}
statement_x;
When both the conditions 1 and 2 are true, it executes the statement_1 and statement_x.
If condition1 is false, it execute the statement_3 and statement x.
If condition2 is false, it execute the statement_2 and statement x
else if ladder
Syntax :
if(condition1)
statement1; else
if(condition2)
statement2; else
if(condition3)
3
statement3;
else
default_statement;
statement_x;
The conditions are evaluated from the top. If a true condition is found, the statement associated will be executed and
the control is transferred to statement_x. if all the conditions are false, default_statement will be executed.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int avg;
printf(“Enter the average:”);
scanf(“%d”,&avg);
if(avg>79)
printf(“Grade=Honours”);
else if(avg>59)
printf(“Grade=First Class”);
else if(avg>49)
printf(“Grade=Second
Class”); else if(avg>39)
printf(“Grade=”Third Class”);
else
printf(“Grade=Fail”);
getch();
}
Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int x;
printf(“Enter the x value:”);
scanf(“%d”,&x);
switch(x)
{
case 1: printf(“one”);
break;
case 2: printf(“two”);
break;
case 3: printf(“three”);
break;
default: printf(“invalid”);
break;
}
}
Output: Enter the x value: 1
one.
Enter the x value: 4
invalid
In this program, the value of x is 1. The value of x is compared against, 1, 2, 3, a match is found; the
block of statements of case 1 will be executed. Second time it getting another one value, that value is 4. There is
no_match default_block will be executed. It print the statement is invalid.
5
LOOPING:
looping statements execute the body of the loop repeatedly until some conditions are
satisfied. There are 2 types of loops.
Entry controlled loop
Exit controlled loop
In entry controlled loop the conditions are tested first if the conditions are not satisfied the body of
the loop will not be executed.
In exit controlled loop the conditions are tested at the end of body of body of loop, so the body of loop
is executed for the first time.
C language has 3 looping statements. They
are, While statement
Do statement
For statement
While statement:
Syntax :
while(condition)
{
body of the loop
}
while is an entry controlled loop. Condition is evaluated first. If it is true loop is executed. This process is
repeated until the test condition becomes false. The body of loop may have one or more statements. Braces
are needed only if the body has more than 1 statement.
Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
while(i<=5)
{
printf(“Welcome”);
i++;
}
getch();
}
Output: Welcome
Welcome
6
Welcome
Welcome
Welcome
Do statement
Syntax:
do
{
body of the loop;
}whil(condition);
This is an exit controlled loop. The body of the loop is executed first. Then the condition is evaluated. If it is
true then the body of loop is executed again. This process continues until the test condition becomes false. So
the body of loop is executed at least once.
Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int
i=10; do
{
printf(“Welcome”);
i++;
} while (i<=5);
getch();
}
Output: Welcome
For statement
Syntax:
for(initialization part; condition part;increment/decrement part)
{
body of the loop;
}
7
This is an entry controlled loop. Initialization of variables is done first using assignment
statements. Condition is evaluated next. If it is true body of the loop is executed. Then the increment part is
evaluated condition is evaluated and the process repeats until the test condition becomes false.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
printf(“Welcome”);
}
getch();
}
Output: Welcome
Welcome
Welcome
Welcome
Welcome
Unconditional Statement
The goto statement:
C uses goto statement to branch from one point to another point unconditionally. Goto statement
requires a label to identify the place label is any valid variable name.
Syntax : goto labelname;
labelname is referred to identify the location. goto statement used to transfer control to another
location in a program.
Break statement
If you want to jump out of the loop during the execution of loop we can use break statement.
Syntax: break;
Continue statement
Transfer the control to the next iteration of the nearest enclosing do, for or while statement.
Syntax: continue;
These 3 types are unconditional statements.
ASSIGNMENT QUESTIONS
10. Which of the following comment about for loop are correct?
[A] Using break is equivalent to using a goto that jumps to the statement immediately following the loop
[B] Continue is used to by pass the remainder of the current pass of the loop
[C ] if comma operator is used,then the value returned is the value of the right operand
[D] All of above
11. In a for loop, if the condition is missing, then infinite looping can not be avoided by
a [A] Continue statement
[B] goto statement
[C] return statement
[D] break statement
EXAMPLE PROGRAM
1. for(i = 2; i <= 6; i = i + 2)
printf("%d\t", i + 1);
2. for(i = 2; i != 11; i = i + 3)
printf("%d\t", i + 1);
3. for(i = 2; i == 2; i = i + 1)
printf("%d\t", i + 1);
3. for(i = 2; i == 2; i = i + 1)
printf("%d\t", i + 1);
4. for(i = 2; i <= 6; i = i + 2)
printf("%d\t", i + 1);
26. Print out $$$$$$ on seven consecutive lines.
REFERENCE LINKS
http://www.cquestions.com/2012/02/c-questions-and-answers.html
http://edugrip.blogspot.in/2012/09/c-language-multiple-choice-questions.html
Functions
A function is a block of code that has a name and it has a property that it is reusable i.e. it can be
executed from as many different points in a C Program as required.The name of the function is unique in a C
Program and is Global. It means that a function can be accessed from any location with in a C Program. We pass
information to the function called arguments specified when the function is called. And the function either returns
some value to the point it was called from or returns nothing.
We can divide a long C program into small blocks which can perform a certain task. A function is a
self contained block of statements that perform a coherent task of same kind.
11
2. User_define functions.
This function should be written by the
user. Eg: add(), f1(), f4(), etc…
Advantages: Length of source program can be reduced.
Function
definition Syntax:
Datatype Functionname(argument list)
{
Local variable
declaration; Executable
stmt1; Executable stmt2;
------------
----------
return(expression);
}
Return values:
A function may or may not send back values to the calling function. The value is returned thru
return statement. The function can return only one value per call.
Syntax : return; (or) return(expression)
Eg1 return(x*y);
Eg2 if(x<=0)
return(0);
else
return(1);
We can specify the return type of a function in the function
header. Eg double product(x,y)
It means that the return type is double.
Function declaration:
Syntax: Datatype Functionname(number of parameters)
12
Eg: int add(int,int)
Calling a function:
A function can be called by using the function name in a stmt.
Syntax: Functionname(number of
parameters); Or
variable = Functionname(number of parameters);
Eg add(10,2);
Or
x=add(10,5);
When the compiler finds a function call control is transferred to that function.
Eg program:
#include<stdio.h>
#include<conio.h>
void main()
{
int add(int,int); Function declaration
printf(“Functions”);
x=add(“%d”,x); Function call
printf(“value of x is: %d”,x);
}
int add(int x,int y) Function header
{
int z;
z=x+y; Function defination return(z);
In the program, x takes the value 10, y takes value 2.add these two values and stored in variable is z
and returned to add() which is then returned to x and print the value of x.
Category of function:
Functions , depending on the arguments , and return values , are classified as
1. Functions with no argument and no return value.
2. Functions with argument and no return value.
3. Functions with no argument and one return value.
4. Functions with argument and one return value.
5. Functions with argument and multiple return values.
13
1. Functions with no argument and no return value
Here there is no data transfer between the calling function & the called function. A function does not
receive any data and it does not return any value.
--------------- ---------------
Function2(); no output
} }
Eg
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
sample();
getch();
}
sample()
{
printf(“welcome“);
return;
}
The output is: welcome
Main()
{ actual arguments
----
Fun1(a1,a2……am)
}
Fun1(f1,f2…….fn)
Formal arguments
{
--------------
---------
--------------
}
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter the values for a&b ”);
scanf(“%d%d”,&a,&b);
15
mul(a,b); a & b are actual arguments
getch();
}
void mul(int p,int q) p & q are Formal arguments
{
int m;
m=p*q;
printf(“The value of m is%d”,m);
}
The output is: Enter the values for a&b 10 20
The value of m is 200
Function1() Function2(f)
{ {
--------------- ---------------
--------------- ---------------
Function2(a); result Return(e);
} }
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int c;
clrscr();
c=add();
printf(“The value of c
is%d”,c); getch();
}
int add()
{
16
int x,y,z;
printf(“Enter the values for x &
y”); scanf(“%d%d”,&x,&y);
z=x+y;
return(z);
}
The output is: Enter the values for x & y 10 20
The value of c is 30
--------------- ---------------
Function2(a); result Return(e);
} }
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
clrscr();
x=int div(10,2);
printf(“The value of x
is%d”,x); getch();
}
int div(int a, int b)
{
int c;
c=a/b;
17
return(c);
}
The output is: The value of x is 5.
--------------- ---------------
--------------- ---------------
Function2(a); result Return(e);
} }
Eg:
#include<stdio.h>
#include<conio.h>
void maths(int x,int y,int *s,int
*d); void main()
{
int x=20,y=10,s,d;
clrscr();
maths(x,y,&s,&d);
printf(“The value of s is%d”,s);
printf(“\n The value of d
is%d”,d); getch();
}
void maths(int a,int b,int *sum,int *diff)
{
*sum=a+b;
*diff=a-b;
}
The output is: The value of s is 30.
The value of d is 10
18
In the program, *s denotes address of s and &s denotes value of s. value of a+b is stored in address of
s. value of a-b is stored in address of d and finally printed.
Recursion:
A function calling itself is called recursion.
Eg:
main()
{
printf(“example”);
main();
}
File Management In C
File is a technique to store the information in the Secondary Storage Device (SSD). Informations
are permanent.
The informations available in the program are stored in the memory without using a file..
Place on the disk where a group of related data is stored and data can be read whenever necessary
File operations
Naming, opening, reading from, writing to, closing
Note:
w – a file with specified name is created if the file contents deleted, if the file
exists. r – if exists file is opened with the current content safe otherwise error.
a – file opened with the current contents safe. a file created if not exists .
. Step 3: Input and output operation
After the file is open, we can perform the input & output operation.
Input / Output Operations for file
Character Function: Used to read & write character
functions. getc() & putc()
getc() – Read the single character from the text file and assigned to c.
c= getc(fp)
putc() - Handles one char at a time. Writes a char to the file opened with write mode
putc(c,fp)
fp - filepointer
The getc will return an end of file markers EOF when end of file has been reached. So
reading should be terminated when EOF is encountered
Integer Function: Used to read & write integer
functions. getw() & putw()
getw() – Read the integer value from the file and assigned to
n. n= getw(fp)
putw() - Writes a integer to the file opened with write mode
putw(n,fp)
Mixed Data File Input and Output: Used to read and write more than one different data at time.
Like character , float and integer.
fprintf and fscanf
Can handle a group of mixed data.
Similar to printf & scanf.
Syntax :
fscanf(fp,”format specification”,&variable);
fprintf(fp,”format specification”,variable);
Eg:
fprintf(f1,”%s%d%f”,name, age,7.5);
fscanf(f2,”%s%d”,item,&quantity);
There is no & symbol for string variable.
Step 4: Close a file
20
After the operation is performed on a file ,the file must be cosed.
Syntax : fclose(file-pointer);
file must be closed as soon as all operations are over.
All outstanding information flushed out from buffers, links are broken.
Prevents any accidental misuse.
Close the file when we want to reopen the same file in different mode.
File input/output function in c library
Eg:
if(feof(fp)) printf(“end
of data”);
ferror()
Report the states of file.
Returns nonzero if an error occurs up to that pt. zero otherwise.
Eg:
if(ferror(fp)!=0)
printf(“error”);
NULL pointer:
While using fopen, if the file cannot be opened then it returns a null pointed.
Used to test whether the file has been opened or not.
Eg
if(fp==NULL)
Printf(“File cannot be opened”);
Eg:2
If((fp2 =fopen(filename,”r”))==NULL)
Printf(“cannot open”);
Eg program:
// Creating a text file
22
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp=fopen(“sample.txt”,”w”);
while((c=getc(fp))!=”EOF”)
putc(c,fp);
fclose(fp);
}
ASSIGNMENT QUESTIONS
1. What is C function?
2. Uses of C functions
3. C function declaration, function call and definition with example program
4. How to call C functions in a program?
1. Call by value
2. Call by reference
5. C function arguments and return values
1. C function with arguments and with return value
2. C function with arguments and without return value
3. C function without arguments and without return value ===
4. C function without arguments and with return value
6. Types of C functions
1. Library functions in C
2. User defined functions in C
7. What is file pointer in C?
8. What is the purpose of type FILE?
9. What is the purpose of function fopen() and fclose()?
10. Describe the syntax of function fopen()?
11. What is the purpose of functions fread() and fwrite()?
12. What file modes can be used by the function fopen()?
13. What are functions fprintf() and fscanf()?
14. What are getc() and putc() functions?
15. What does SEEK_SET, SEEK_CUR and SEEK_END mean in the declaration of fseek().
16. C Program to read name and marks of students and store it in file.
17. C Program to read name and marks of students and store it in file. If file already exists, add information to
it.
18. C Program to write members of arrays to a file using fwrite().
19. Explain the steps to write a file program.
23
20. Write the syntax for fseek().
24