Beruflich Dokumente
Kultur Dokumente
A control structure is a block of programming that analyzes variables and chooses a direction in
which to go based on given parameters. The term flow controldetails the direction the program
takes (which way program control "flows"). Hence it is the basic decision-making process in
computing; flow control determines how a computer will respond when given certain conditions
and parameters.
(or)
A statement that is used to control the flow of execution in a program is called control structure.
It combines instruction into logical unit. Logical unit has one entry point and one exit point.
Flowchart :
For Example
#include<stdio.h>
void main()
{
int a=5;
printf(Value of a = %d,a);
}
Flowchart of if statement
Example of if statement
Example 1: C program to print the square
of a number if it is less than 10.
#include<stdio.h>
void main()
{ int n;
printf("Enter a number:");
scanf("%d",&n);
if(n<10)
printf("Square = %d\n",n*n);
} }
This program is an example of using if statement. A number is asked from user and stored in
variable n. If the value of n is less than 10, then its square is printed on the screen. If the
condition is false the program, execution is terminated.
Output
Enter a number:6
6 is less than 10
Square = 36
if ... else statement is a two way branching statement. It consists of two blocks of statements each
enclosed inside if block and else block respectively. If the condition inside if statement is true,
statements inside if block are executed, otherwise statements inside else block are executed. Else
block is optional and it may be absent in a program.
Here, a number is entered by user which is stored in n. The if statement checks if the remainder
of that number when divided by 2 is zero or not. If the remainder is zero, the number is even
which is printed on the screen. If the remainder is 1, the number is odd.
Note: If there is only one statement inside if block, we don't need to enclose it with curly
brackets { }.
Output
Enter a number:18
18 is even
Enter a number:33
33 is odd
It is used when more than one condition is to be checked. A block of statement is enclosed inside
if, else if and else part. Conditions are checked in each if and else if part. If the condition is true,
the statements inside that block are executed. If none of the conditions are true, the statements
inside else block are executed. A if ... else if ... else statement must have only one if block but
can have as many else if block as required. Else part is optional and may be present or absent.
Syntax of if...else if...else statement
if (condition 1)
{ statements;
... ... ... }
else if (condition 2)
{ statements;
... ... ...
}... ... ...
... ... ...
else if (condition n)
{ statements;
... ... ... }
else
{
statements;
... ... ... }
Flowchart of if ... else if ... else statement
#include<stdio.h>
int main()
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n<0)
printf("Number is negative");
else if(n>0)
printf("Number is positive");
else
In this program, a number is entered by user stored in variable n. The if ... else if ... else
statement tests two conditions:
If both of these conditions are false then the number is zero. So the program will print "Number
is zero".
Output
Enter a number:109
Number is positive
Enter a number:-56
Number is negative
Enter a number:0
d) Nested if statements
When a if statement is kept inside another if statement, it is called nested if statement. Nested if
statements are used if there is a sub condition to be tested. The depth of nested if statements
depends upon the number of conditions to be checked.
if (condition 1)
statements;
if (sub condition 1)
statements;
statements;
else if (condition 2)
{
statements;
if (sub condition 2)
statements;
statements;
else
statements;
if (sub condition n)
statements;
statements;
Example 4: C program to check if a number is less than 100 or not. If it is less than 100
then check if it is odd or even.
#include<stdio.h>
int main()
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n<100)
if(n%2 == 0)
printf("%d is even",n);
else
printf("%d is odd",n);
else
return 0;
It consists of a nested if statement. The outer if statement checks whether the number is less than
100 or not. If the number is less than hundred, another condition i.e. if the number is even or odd
is checked and respective message is displayed.
Output
Enter a number:46
46 is even
Enter a number:67
67 is odd
Enter a number:316
while loop
for loop
do-while loop
a) While loop is an entry controlled loop i.e. the condition is checked before entering into the
loop. So if the condition is false for the first time, the statements inside while loop may not be
executed at all. The condition to be checked can be changed inside loop by changing values of
variables. When the condition becomes false, the program control exits the loop. We can also exit
a loop by using break statement like in switch case.
while (condition)
{ statement(s);
b) Do-while loop is an exit controlled loop i.e. the condition is checked at the end of loop. It
means the statements inside do-while loop are executed at least once even if the condition is
false. Do-while loop is an variant of while loop. In order to exit a do-while loop either the
condition must be false or we should use break statement.
Syntax of do-while loop
do
{
statement(s);
... ... ...
}while (condition);
Flowchart of do-while loop
c) For loop is an entry controlled loop i.e. the condition is checked before entering into the
loop. So if the condition is false for the first time, the statements inside while loop may not be
executed at all. In order to exit from a for loop, either the condition should be false or a break
statement should be encountered. For loop is suitable to use when we have to run a loop for a
fixed number of times.
statement(s);
In this part, the variable required for the loop is initialized. It is executed only once at the first
iteration. This part is optional and may be absent.
For example:
Here, in the first example, i = 0 is the initialization variable while in the second example, no
initialization is done.
2. Condition
Here, condition for executing the loop is checked. The condition is checked after the execution of
increment/decrement statement. If the condition is true then loop is executed, otherwise it is
terminated. If this part is left blank, it is considered true in C causing the loop to run infinite
times.
For example:
3. Increment/Decrement
This part increments or decrements the value of a variable that is being checked. This part is
executed at the end of each iteration before executing the conditional part. It is also optional part
of for loop.
For example:
In these examples, i++ and i-- are increment, and decrement components respectively.
#include<stdio.h>
int main()
int i,n,s=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
s=s+i;
printf("Sum = %d",s);
return 0;
This program prints the sum of first n natural numbers. A number is asked from user and stored
in variable n. For loop is used to add numbers from 1 to n and store the sum in s. Variable i is
used for looping and it is incremented on each iteration. The condition is checked and until i is
less than or equal to n, the loop runs. Finally the value of sum is printed after terminating the
loop.
Output
Sum = 120
Nested loop in C
A loop inside another loop is called a nested loop. The depth of nested loop depends on the
complexity of a problem. We can have any number of nested loops as required. Consider a nested
loop where the outer loop runs n times and consists of another loop inside it. The inner loop
runs m times. Then, the total number of times the inner loop runs during the program execution is
n*m.
A while loop inside another while loop is called nested while loop.
while (condition1)
statement(s);
while (condition2)
statement(s);
Flowchart of Nested
while loop
Example of Nested while loop
12
123
1234
12345
#include <stdio.h>
int main()
int i=1,j;
while (i <= 5)
j=1;
while (j <= i )
printf("%d ",j);
j++;
printf("\n");
i++;
}
return 0;
In this program, nested while loop is used to print the pattern. The outermost loop runs 5 times
and for every loop, the innermost loop runs i times which is 1 at first, meaning only "1" is
printed, then on the next loop it's 2 numbers printing "1 2" and so on till 5 iterations of the loop
executes, printing "1 2 3 4 5". This way, the given number pattern is printed.
A do-while loop inside another do-while loop is called nested do-while loop.
do
statement(s);
do
statement(s);
}while (condition2);
}while (condition1);
**
***
****
*****
#include <stdio.h>
int main()
int i=1,j;
do
j=1;
do
printf("*");
j++;
i++;
printf("\n");
return 0;
In this program, nested do-while loop is used to print the star pattern. The outermost loop runs 5
times and for every loop, the innermost loop runs i times which is 1 at first, meaning only one
"*" is printed, then on the next loop it's 2 printing two stars and so on till 5 iterations of the loop
executes, printing five stars. This way, the given star pattern is printed.
A for loop inside another for loop is called nested for loop.
{
statement(s);
statement(s);
Example 3: C program to print all the composite numbers from 2 to a certain number entered by
user.
#include<stdio.h>
#include<math.h>
int main()
int i,j,n;
printf("Enter a number:");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
for(j=2;j<=(int)pow(i,0.5);j++)
if(i%j==0)
printf("%d is composite\n",i);
break;
return 0;
Output
Enter a number:15
4 is composite
6 is composite
8 is composite
9 is composite
10 is composite
12 is composite
14 is composite
15 is composite
A number is said to be composite if it has at least one factor other than 1 and itself. This program
prints all the composite numbers starting from 2 to a certain number n, entered by user. We need
to use a nested loop to solve this problem. The outer for loop runs from 2 to n and the inner loop
is used to determine whether a number is composite or not. We need to check for that factor
starting from 2 to integer part of square root of that number.
Consider 15, its square root is nearly 3.873. Here, the integer part is 3. Now, if there is a factor of
15 from 2 to 3 then it is composite. Here, 3 is a factor of 15. Hence, 15 is a composite number.
switch case statement in C programming
switch case is a multiple branching statement which compares the value of expression or
variable inside switch() with various cases provided with the statement and executes a block
when a match is found. If no cases inside the switch is matched, the statements
inside default block is executed. However, default is optional and may not be present. It is
similar to else part of if statement.
switch case can be considered as simplified version of if statement. When there are large number
of conditions to be tested, it is difficult to use if statement as the number of repeated if statements
may cause confusion and makes the program unreadable. So, switch case is preferred in such
cases to simplify programmers job and increases code readability.
case value1:
statement(s);
break;
case value2:
statement(s);
break;
case valueN:
statement(s);
break;
default:
statement(s);
break;
#include <stdio.h>
int main()
char alphabet;
printf("Enter an alphabet:");
scanf("%c",&alphabet);
switch(alphabet)
case 'a':
printf("Alphabet a is a vowel.\n");
case 'e':
printf("Alphabet e is a vowel.\n");
case 'i':
printf("Alphabet i is a vowel.\n");
case 'o':
printf("Alphabet o is a vowel.\n");
case 'u':
printf("Alphabet u is a vowel.\n");
default:
return 0;
Output
Enter an alphabet:i
Alphabet i is a vowel.
Alphabet o is a vowel.
Alphabet u is a vowel.
In this program, an alphabet is stored in a variable alphabet. Using a switch case statement, we
check for all the cases a, e, i, o, u and statement inside the case is executed. But when users
enters alphabet i, the program prints all statements following the matching case, i.e. case i. This
is because, switch case, by design, executes all statements after the match is found until the end
of the block. To get around this, we need to break its execution. This is done
using break statement.
break Statement
The break statement is used to break out of a loop or a switch case. It is very important to use
break statement inside switch case, where when a matching case is found, all the cases below it
are executed by default. So, break statement is used after each case in order to break out of
switch..case after a case has been matched.
break;
#include <stdio.h>
int main()
char alphabet;
printf("Enter an alphabet:");
scanf("%c",&alphabet);
switch(alphabet)
case 'a':
printf("Alphabet a is a vowel.\n");
break;
case 'e':
printf("Alphabet e is a vowel.\n");
break;
case 'i':
printf("Alphabet i is a vowel.\n");
break;
case 'o':
printf("Alphabet o is a vowel.\n");
break;
case 'u':
printf("Alphabet u is a vowel.\n");
break;
default:
break;
return 0; }
Output
Enter an alphabet:i
Alphabet i is a vowel.
Above examples illustrates the use of of break statement. In each program, user enters a number
which is then compared with various cases inside switch statement. In the first example, break
statement is not used so if a matching case is found, all the statements below it are executed.
However in the second example, break is used so only the statements inside the matching case is
executed.
Like nested if, we can use nested switch case in C programming. A switch case statement
enclosed inside another switch case statement is called nested switch case.
Syntax of nested switch case
case value1:
statement(s);
break;
... ... ...
case valueN:
statement(s);
break;
default:
statement(s);
break;
Example 3: C program to check for head/tail using nested switch case statement
#include<stdio.h>
int main()
int ch1,ch2;
scanf("%c",&ch1);
fflush(stdin);
switch(ch1)
case 'h':
case 'H':
switch(ch2)
case 'h':
case 'H':
printf("2 Heads");
break;
default:
break;
default:
switch(ch2)
case 'h':
case 'H':
break;
default:
printf("2 Tails");
return 0;
}
This program is an example of nested switch case. Here, a switch case is inserted inside another
switch case. User needs to enter two characters, H/h for head and T/t for tail. Both switch case
(outer and inner) tests whether the input entered by user is Head or Tail. According to the
combination of inputs entered by user, the output is displayed.
Output
2 Tails
Note: Nested switch aren't popularly used by programmers. In practice, generally nested if
statements are preferred instead of nested switch case.
continue statement in C
The continue statement in C programming works somewhat like the breakstatement. Instead of
forcing termination, it forces the next iteration of the loop to take place, skipping any code in
between.
For the for loop, continue statement causes the conditional test and increment portions of the
loop to execute. For the while and do...whileloops, continue statement causes the program
control to pass to the conditional tests.
Syntax
The syntax for a continue statement in C is as follows
continue;
Flow Diagram
Example
#include <stdio.h>
int main () {
/* do loop execution */
do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto statement
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement in the same function.
NOTE Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program, making the program hard to understand
and hard to modify. Any program that uses a goto can be rewritten to avoid them.
Syntax
The syntax for a goto statement in C is as follows
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program
above or below to goto statement.
Flow Diagram
Example
#include <stdio.h>
Void main ( )
{ int a = 10;
do {
if( a == 15) {
a = a + 1;
goto LOOP;
}
C - Functions
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
Function Name This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
Function Body The function body contains a collection of statements that define what the function
does.
Example
Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
return result; }
These functions are defined in the header file. When you include the header file, these functions
are available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display output on
the screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions are
available for use.
User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created by the
user are called user-defined functions.
Depending upon the complexity and requirement of the program, you can create as many user-
defined functions as you want.
How user-defined function works?
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
The execution of a C program begins from the main() function.
When the compiler encounters functionName(); inside the main function, control of the program
jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside
the function definition are executed.
Remember, function name is an identifier and should be unique.
In C Programming, As per our requirement, We can define the User defined functions in multiple
ways (or) Types of functions in C
NOTE:
From the above, 1 and 3 types does not return any value when the function is called so,
We use void return type while defining the function.
When we call the function 2 and 4 types will return some value so, We have to use the
appropriate data type (int, float, double etc) as return type while defining the function. We
use return keyword inside the function to return some value when the function is called
from the main() function or any sub functions.
In this method, We wont pass any arguments to the function while defining, declaring or calling
the function. This type of functions will not return any value when we call the function from
main() or any sub function. When we are not expecting any return value but, we need some
statements to be printed as output then, this type of functions are very useful.
In this program, We are going to calculate the Sum of 2 integer values and print the output from
the user defined function itself.
// Function Declaration
void Addition();
void main()
{
printf("\n ............. \n");
Addition();
}
void Addition()
{
int Sum, a = 10, b = 20;
Sum = a + b;
In this method, We wont pass any arguments to the function while defining, declaring or calling
the function. This type of functions will return some value when we call the function from main()
or any sub function. Data Type of the return value will depend upon the return type of function
declaration. For instance, if the return type is int then return value will be int.
Function with No arguments and with Return value Example
In this program, We are going to calculate the multiplication of 2 integer values using the user
defined function without arguments and return keyword.
#include<stdio.h>
int Multiplication();
int main()
{
int Multi;
Multi = Multiplication();
printf("\n Multiplication of a and b is = %d \n", Multi );
return 0;
}
int Multiplication()
{
int Multi, a = 20, b = 40;
Multi = a * b;
return Multi;
}
If you observe the above 2 methods, No matter how many times you executive, it will give the
same output. We dont have any control over the values of the variables a and b because they are
fixed values. In real time, we mostly deal with dynamic data means we have to allow the user to
enter his own values rather than fixed ones.
This method allows us to pass the arguments to the function while calling the function. But, This
type of functions will not return any value when we call the function from main () or any sub
function.
If we want to allow our user to pass his own data to the function arguments but we are not
expecting any return value then, this type of functions are very useful.
This program allows the user to enter 2 integer values and then, We are going to pass those
values to the user defined function to calculate the sum.
#include<stdio.h>
Sum = a + b;
This method allows us to pass the arguments to the function while calling the function. This type
of functions will return some value when we call the function from main () or any sub function.
Data Type of the return value will depend upon the return type of function declaration. For
instance, if the return type is int then return value will be int.
This type of user defined functions are called as fully dynamic function means, it provide
maximum control to the end user.
This program allows the user to enter 2 integer values and then, We are going to pass those
values to the user defined function to multiply those values and return the value using return
keyword.
#include<stdio.h>
int main()
{
int a, b, Multi;
Multi = a * b;
return Multi;
}
Call by value in C
In call by value, original value is not modified.
In call by value, value being passed to the function is locally stored by the function parameter in
stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().
Example:
#include <stdio.h>
#include <conio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
clrscr();
getch();
return 0;
}
Output:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by reference in C
In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments shares the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.
Example:
#include <stdio.h>
#include <conio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
clrscr();
getch();
return 0;
}
Output:
1 A copy of value is passed to the function An address of value is passed to the function
2 Changes made inside the function is not reflected Changes made inside the function is reflected
on other functions outside the function also
3 Actual and formal arguments will be created in Actual and formal arguments will be created in
different memory location same memory location
After function call x=200
Recursion in C
When function is called within the same function, it is known as recursion in C. The
function which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is know as tail
recursion.
Syntax:
recursionfunction(){
recursionfunction();//calling self function
}
Example:
#include<stdio.h>
#include<conio.h>
int factorial (int n)
{
if ( n < 0)
return -1; /*Wrong value*/
if (n == 0)
return 1; /*Terminating condition*/
return (n * factorial (n -1));
}
void main(){
int fact=0;
clrscr();
fact=factorial(5);
printf("\n factorial of 5 is %d",fact);
getch();
}
Output: factorial of 5 is 120
Calling a Function:
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters along with the function
name, and if the function returns a value, then you can store the returned value. For example
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
return result;
}
Storage Classes in C
Storage classes are used to define scope and life time of a variable. There are four storage
classes in C programming.
o auto
o extern
o static
o register
extern RAM Zero Global Till the end of main program, May be
declared anywhere in the program
static RAM Zero Local Till the end of main program, Retains
value between multiple functions call
1) auto
The auto keyword is applied to all local variables automatically. It is the default storage
class that is why it is known as automatic variable.
#include <stdio.h>
void main(){
int a=10;
auto int b=10;//same like above
printf("%d %d",a,b);
}
Output:
10 10
2) register
The register variable allocates memory in register than RAM. Its size is same of register
size. It has a faster access than other variables.
It is recommended to use register variable only for quick access such as in counter.
3) static
The static variable is initialized only once and exists till the end of the program. It retains
its value between multiple functions call.
The static variable has the default value 0 which is provided by compiler.
#include <stdio.h>
void func() {
static int i=0;//static variable
int j=0;//local variable
i++;
j++;
printf("i= %d and j= %d\n", i, j);
}
void main() {
func();
func();
func();
}
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
4) extern
The extern variable is visible to all the programs. It is used if two or more files are sharing
same variable or function.
Array
An array is a data structure that contains a group of elements. Typically these elements
are all of the same data type, such as an integer or string.
An array is a collection of data items, all of the same type, accessed using a common
name.
C Array is a collection of variables belongings to the same data type. You can store
group of data of same data type in an array.
1. What is an array? How to declare and initialize arrays? Explain with examples
Ans: Array:-
An array is defined as an ordered set of similar data items. All the data items of an array are
stored in consecutive memory locations in RAM. The elements of an array are of same data
type and each item can be accessed using the same name.
Declaration of an array:- We know that all the variables are declared before they are used
in the program. Similarly, an array must be declared before it is used. During declaration, the
size of the array has to be specified. The size used during declaration of the array informs the
compiler to allocate and reserve the specified memory locations.
float x[10];
Initialization of Arrays:-
Arrays can be initialized at the time of declaration when their initial values are known in
advance. Array elements can be initialized with data items of type int, char etc.
During compilation, 5 contiguous memory locations are reserved by the compiler for the variable
a and all these locations are initialized as shown in figure.
Array initialization with a string: -Consider the declaration with string initialization.