Sie sind auf Seite 1von 52

Control structures in C - Program

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.

There are 3 types of Control Structures in C-Language


1. Sequence Control Statements.
2. Decision Control Statement (or) Condition Control Statements (or) Selection
3. Iterative Control Statement (or) Looping Control Statements (or) Repetition.

1. Sequence: Statements are executed in a specified order. No statement is skipped and


no statement is executed more than once.

Flowchart :

For Example
#include<stdio.h>
void main()
{
int a=5;
printf(Value of a = %d,a);
}

2. Decision Control Statement (or) Condition Control Statements (or) Selection

Decision making is an important part of programming. Every programming language supports


decision making statements allowing programmers to branch according to the condition. In C
programming language, if statement is used to check condition and make decision. The
decisions or statements are enclosed inside curly braces, however if only a single statement has
to be executed, curly braces are not mandatory. Depending upon the number of conditions to be
checked, we have following types of if statement:
1. if statement
2. if ... else statement
3. if ... else if ... else statement
4. Nested if
a) if statement
if statement is used for branching when a single condition is to be checked.
The condition enclosed in if statement decides the sequence of execution of instruction. If the
condition is true, the statements inside if statement are executed, otherwise they are skipped. In C
programming language, any non zero value is considered as true and zero or null is considered
false.
Syntax of if statement
if (condition)
{
statements;
... ... ...
}

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("%d is less than 10\n",n);

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

b) if ... else statement

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.

Syntax of if...else statement


if (condition)
{
statements;
... ... ...
}
else
{
statements;
... ... ...
}
Flowchart of if ... else statement

Example of if ... else statement


Example 2: C program to find if a number is odd or even.
#include<stdio.h>
void main()
{
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n%2 == 0)
printf("%d is even",n);
else
printf("%d is odd",n);
return 0;
}

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

c) if ... else if ... else statement

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

Example of if ... else if ... else statement

Example 3: C program to find if a number is negative, positive or zero.

#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

printf("Number is equal to zero");


return 0;

In this program, a number is entered by user stored in variable n. The if ... else if ... else
statement tests two conditions:

n<0: If it is true, "Number is negative" is printed on the screen.

n>0: If it is true, "Number is positive" is printed on the screen.

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

Number is equal to zero

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.

Syntax of nested if statement

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;

Flowchart of nested if statement


Example of Nested if statement

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)

printf("%d is less than 100\n",n);

if(n%2 == 0)

printf("%d is even",n);
else

printf("%d is odd",n);

else

printf("%d is equal to or greater than 100",n);

return 0;

This program tests two conditions:

If the number is less than 100 or not.

If the number is less than 100 then is it odd or even.

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 less than 100

46 is even

Enter a number:67

67 is less than 100

67 is odd

Enter a number:316

316 is equal to or greater than 100

3. Iterative Control Statement (or) Looping Control Statements (or) Repetition.


Looping is a process of repeating a certain group of statements until a specified condition is
satisfied. There are three types of loop in C. They are:

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.

Syntax of while loop

while (condition)

{ statement(s);

... ... ... }

Flowchart of while loop

Example of while loop


Example: C program to print the multiplication table of 2 from 1 to 10.
#include<stdio.h>
int main()
{
int i=1;
while(i<=10)
{
printf("2 * %d = %d\n",i,2*i);
i++;
}
return 0;
}
This program prints a multiplication table of 2 from 1 to 10. We have used while loop to achieve
our result. Initially i is assigned to 1. The condition to be tested is i<=10. After executing the
loop each time, the value of i is increased by 1. When the value of i becomes 11, the condition
becomes false and the loop is terminated.
Output
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

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

Example of do-while loop


Example: C program to print the table of 5 from 1 to 10.
#include<stdio.h>
int main()
{
int i=1;
do
{
printf("5 * %d = %d\n",i,5*i);
i++;
}while(i<=10);
return 0;
}
This program prints a multiplication table of 5 from 1 to 10. Do-while loop is used in this
program. Initially, the value of i is 1. On each iteration, the value of i is increased by 1 and
condition is tested. When the value of i becomes 11,the condition becomes false and loop is
terminated.
Output
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

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.

Syntax of for loop

for (initialization; condition; increment/decrement)

statement(s);

... ... ...

Components of for loop

For loop consists of three components


1. Initialization

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:

for(i=0; condition; increment/decrement)

for( ; condition; increment/decrement) // initialization is absent

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:

for(i=0; i<=10; increment/decrement)

for(i=0 ; i<strlen(name); increment/decrement)

In these examples, i<=10 and i <strlen(name) are conditions.

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:

for(i=0; i<=10; i++) // increment


for(i=10 ; i>0; i--) // decrement

In these examples, i++ and i-- are increment, and decrement components respectively.

Flowchart of for loop

Example of for loop

Program1: C program to find the sum of first n natural numbers.

#include<stdio.h>

int main()

int i,n,s=0;

printf("Enter value of n:");

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

Enter value of n:15

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.

Types of nested loops

Nested while loop


Nested do-while loop
Nested for loop
Note: There can be mixed type of nested loop i.e. a for loop inside a while loop, or a while loop
inside a do-while loop. Nested while loop

A while loop inside another while loop is called nested while loop.

Syntax of Nested while loop

while (condition1)

statement(s);

while (condition2)

statement(s);

... ... ...

... ... ...

Flowchart of Nested
while loop
Example of Nested while loop

Example 1: C program to print the number pattern.

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.

Nested do-while loop

A do-while loop inside another do-while loop is called nested do-while loop.

Syntax of Nested do-while loop

do

statement(s);

do

statement(s);

... ... ...

}while (condition2);

... ... ...

}while (condition1);

Flowchart of Nested do-while loop


Example of Nested do-while loop

Example 2: C program to print the given star pattern.

**

***

****

*****

#include <stdio.h>

int main()

int i=1,j;
do

j=1;

do

printf("*");

j++;

}while(j <= i);

i++;

printf("\n");

}while(i <= 5);

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.

Nested for loop

A for loop inside another for loop is called nested for loop.

Syntax of Nested for loop

for (initialization; condition; increment/decrement)

{
statement(s);

for (initialization; condition; increment/decrement)

statement(s);

... ... ...

... ... ...

Flowchart of Nested for loop


Example of Nested for loop

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.

Syntax of switch...case statement

switch (variable or expression)

case value1:

statement(s);

break;

case value2:

statement(s);

break;

... ... ...

... ... ...

case valueN:

statement(s);

break;

default:

statement(s);

break;

Flowchart of switch case statement


Example of switch case statement

Example 1: Check if entered alphabet is vowel or a consonant. (Incorrect output)

#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:

printf("You entered a consonant.\n");

return 0;

Output

Enter an alphabet:i

Alphabet i is a vowel.

Alphabet o is a vowel.

Alphabet u is a vowel.

You entered a consonant.

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.

Syntax of break Statement

break;

Example of switch case statement using break statement


Example 2: Check if entered alphabet is vowel or a consonant. (Correct output)

#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:

printf("You entered a consonant.\n");

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.

Nested switch case

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

switch (variable or expression)

case value1:

statement(s);

switch (variable or expression)

[body of nested switch]

break;
... ... ...

... ... ...

case valueN:

statement(s);

switch (variable or expression)

[body of nested switch]

break;

default:

statement(s);

switch (variable or expression)

[body of nested switch]

break;

Example of nested switch case statement

Example 3: C program to check for head/tail using nested switch case statement

#include<stdio.h>

int main()

int ch1,ch2;

printf("H/h for head, T/t for tail\n");

printf("Enter first choice-");

scanf("%c",&ch1);

fflush(stdin);

printf("Enter second choice-");


scanf("%c",&ch2);

switch(ch1)

case 'h':

case 'H':

switch(ch2)

case 'h':

case 'H':

printf("2 Heads");

break;

default:

printf("Head and Tail");

break;

default:

switch(ch2)

case 'h':

case 'H':

printf("Tail and Head");

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

H/h for head, T/t for tail

Enter first choice-h

Enter second choice-t

Head and Tail

H/h for head, T/t for tail

Enter first choice-t

Enter second choice-t

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 () {

/* local variable definition */


int a = 10;

/* do loop execution */
do {

if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}

printf("value of a: %d\n", a);


a++;

} 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;
}

printf("value of a: %d\n", a);


a++;
}while( a < 20 ); }
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

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.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Syntax: return_type function_name( parameter list )


{
body of the function
}
Return Type A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.

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;

if (num1 > num2)


result = num1;
else
result = num2;

return result; }

Types of functions in C programming


Depending on whether a function is defined by the user or already included in C compilers, there
are two types of functions in C programming

There are two types of functions in C programming:

Standard library functions


User defined functions

Standard library functions


The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling etc.

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.

Advantages of user-defined function


1. The program will be easier to understand, maintain and debug.
2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can be divided
among many programmers.

In C Programming, As per our requirement, We can define the User defined functions in multiple
ways (or) Types of functions in C

1. Function with no argument and no Return value


2. Function with no argument and with Return value
3. Function with argument and No Return value
4. Function with argument and Return value

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.

Types of Functions in C Programming


The Following examples will explain you the available function types in C programming.

1. Function with No argument and No Return value

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.

Function with No argument and No Return value Example

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 with No argument and No Return value Example */


#include<stdio.h>

// Function Declaration
void Addition();

void main()
{
printf("\n ............. \n");

Addition();
}

void Addition()
{
int Sum, a = 10, b = 20;
Sum = a + b;

printf("\n Sum of a = %d and b = %d is = %d", a, b, Sum);


}

2. Function with no argument and with Return value

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;
}

3. Function with argument and No Return value

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.

Function with argument and No Return value Example

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>

void Addition(int, int);


void main()
{
int a, b;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


Addition(a, b);
}

void Addition(int a, int b)


{
int Sum;

Sum = a + b;

printf("\n Additiontion of %d and %d is = %d \n", a, b, Sum);


}

4. Function with argument and Return value

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.

Function with arguments and Return value Example

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 Multiplication(int, int);

int main()
{
int a, b, Multi;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


Multi = Multiplication(a, b);
printf("\n Multiplication of %d and %d is = %d \n", a, b, Multi);
return 0;
}

int Multiplication(int a, int b)


{
int Multi;

Multi = a * b;

return Multi;
}

Call by value and call by reference in C


There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by reference.

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();

printf("Before function call x=%d \n", x);


change(x);//passing value in function
printf("After function call x=%d \n", x);

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();

printf("Before function call x=%d \n", x);


change(&x);//passing reference in function
printf("After function call x=%d \n", x);

getch();
return 0;
}

Output:

Before function call x=100


Before adding value inside function num=100
After adding value inside function num=200

No. Call by value Call by reference

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

Difference between call by value and call by reference in c

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 () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

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

Storage Storage Place Default Value Scope Life-time


Classes

auto RAM Garbage Local Within function


Value

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

register Register Garbage Local Within function


Value

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.

register int counter=0;

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.

extern int counter=0;

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.

Syntax:- data_type array_name[n];


where, n is the number of data items (or) index(or) dimension.
0 to (n-1) is the range of array.
Ex: int a[5];

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.

1. Ex:- int a[5]={10,15,1,3,20};

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.

Fig: Initialization of int Arrays


2. Ex:- int a[3]={9,2,4,5,6}; //error: no. of initial vales are more than the size of array.

3. Ex:- int a[5]={10,15};


Eventhough compiler allocates 5 memory locations, using this declaration statement; the
compiler initializes first two locations with 10 and 15, the next set of memory locations are
automatically initialized to 0's by compiler as shown in figure.
Initialization without size:- Consider the declaration along with the initialization.

Ex:- char b[]={'C','O','M','P','U','T','E','R'};


In this declaration, eventhough we have not specified exact number of elements to be used in
array b, the array size will be set of the total number of initial values specified. So, the array size
will be set to 8 automatically. The array b is initialized as shown in figure.

Fig: Initialization without size


Ex:- int ch[ ]={1,0,3,5} // array size is 4

Array initialization with a string: -Consider the declaration with string initialization.

Ex:- char b[ ]="COMPUTER";


The array b is initialized as shown in figure.

Array Initialized with a String


Eventhough the string "COMPUTER" contains 8 characters, because it is a string, it always ends
with null character. So, the array size is 9 bytes (i.e., string length 1 byte for null character).

Ex:- char b[9]="COMPUTER"; // correct


char [8]="COMPUTER "; //wrong
52

Das könnte Ihnen auch gefallen