Back to Study material
PPS

UNIT - 3Loops & Functions Q1) What are Loops and explain types of loops?A1) A Loop executes the sequence of statements many times until the stated condition becomes false. A loop consists of two parts, a body of a loop and a control statement. The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false. The purpose of the loop is to repeat the same code a number of times. Types of LoopsDepending upon the position of a control statement in a program, a loop is classified into two types:1. Entry controlled loop 2. Exit controlled loop In an entry controlled loop, a condition is checked before executing the body of a loop. It is also called as a pre-checking loop. In an exit controlled loop, a condition is checked after executing the body of a loop. It is also called as a post-checking loop.

 

 The control conditions must be well defined and specified otherwise the loop will execute an infinite number of times. The loop that does not stop executing and processes the statements number of times is called as an infinite loop. An infinite loop is also called as an "Endless loop." Following are some characteristics of an infinite loop: 1. No termination condition is specified. 2. The specified conditions never meet. The specified condition determines whether to execute the loop body or not. 'C' programming language provides us with three types of loop constructs: 1. The while loop 2. The do-while loop 3. The for loop  Q2) Explain While Loop with examplesA2)

A while loop is the most straightforward looping structure. The basic format of while loop is as follows:

while (condition) {

             statements;

}

It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false. Once the condition becomes false, the control goes out of the loop.

After exiting the loop, the control goes to the statements which are immediately after the loop. The body of a loop can contain more than one statement. If it contains only one statement, then the curly braces are not compulsory. It is a good practice though to use the curly braces even we have a single statement in the body.

In while loop, if the condition is not true, then the body of a loop will not be executed, not even once. It is different in do while loop which we will see shortly.

Following program illustrates a while loop:

#include<stdio.h>

#include<conio.h>

int main()

{

 int num=1; //initializing the variable

 while(num<=10) //while loop with condition

 {

  printf("%d\n",num);

  num++;  //incrementing operation

 }

 return 0;

}

Output:

1

2

3

4

5

6

7

8

9

10

The above program illustrates the use of while loop. In the above program, we have printed series of numbers from 1 to 10 using a while loop.

  1. We have initialized a variable called num with value 1. We are going to print from 1 to 10 hence the variable is initialized with value 1. If you want to print from 0, then assign the value 0 during initialization.
  2. In a while loop, we have provided a condition (num<=10), which means the loop will execute the body until the value of num becomes 10. After that, the loop will be terminated, and control will fall outside the loop.
  3. In the body of a loop, we have a print function to print our number and an increment operation to increment the value per execution of a loop. An initial value of num is 1, after the execution, it will become 2, and during the next execution, it will become 3. This process will continue until the value becomes 10 and then it will print the series on console and terminate the loop.

\n is used for formatting purposes which means the value will be printed on a new line.

 Q3) Explain Do-While loop in detail with examplesA3)

A do-while loop is similar to the while loop except that the condition is always executed after the body of a loop. It is also called an exit-controlled loop.

The basic format of while loop is as follows:

 do {

  statements

} while (expression);

As we saw in a while loop, the body is executed if and only if the condition is true. In some cases, we have to execute a body of the loop at least once even if the condition is false. This type of operation can be achieved by using a do-while loop.

In the do-while loop, the body of a loop is always executed at least once. After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop.

Similar to the while loop, once the control goes out of the loop the statements which are immediately after the loop is executed.

The critical difference between the while and do-while loop is that in while loop the while is written at the beginning. In do-while loop, the while condition is written at the end and terminates with a semi-colon (;)

The following program illustrates the working of a do-while loop:

We are going to print a table of number 2 using do while loop.

#include<stdio.h>

#include<conio.h>

int main()

{

 int num=1; //initializing the variable

 do //do-while loop

 {

  printf("%d\n",2*num);

  num++;  //incrementing operation

 }while(num<=10);

 return 0;

}

Output:

2

4

6

8

10

12

14

16

18

20

In the above example, we have printed multiplication table of 2 using a do-while loop. Let's see how the program was able to print the series.

  1. First, we have initialized a variable 'num' with value 1. Then we have written a do-while loop.
  2. In a loop, we have a print function that will print the series by multiplying the value of num with 2.
  3. After each increment, the value of num will increase by 1, and it will be printed on the screen.
  4. Initially, the value of num is 1. In a body of a loop, the print function will be executed in this way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on until the value of num becomes 10. After that loop will be terminated and a statement which is immediately after the loop will be executed. In this case return 0.
 Q4) Explain For loop with examplesA4)

A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop is as follows:

for (initial value; condition; incrementation or decrementation )

{

  statements;

}

  • The initial value of the for loop is performed only once.
  • The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.
  • The incrementation/decrementation increases (or decreases) the counter by a set value.

Following program illustrates the use of a simple for loop:

#include<stdio.h>

int main()

{

 int number;

 for(number=1;number<=10;number++) //for loop to print 1-10 numbers

 {

  printf("%d\n",number);  //to print the number

 }

 return 0;

}

Output:

1

2

3

4

5

6

7

8

9

10

The above program prints the number series from 1-10 using for loop.

  1. We have declared a variable of an int data type to store values.
  2. In for loop, in the initialization part, we have assigned value 1 to the variable number. In the condition part, we have specified our condition and then the increment part.
  3. In the body of a loop, we have a print function to print the numbers on a new line in the console. We have the value one stored in number, after the first iteration the value will be incremented, and it will become 2. Now the variable number has the value 2. The condition will be rechecked and since the condition is true loop will be executed, and it will print two on the screen. This loop will keep on executing until the value of the variable becomes 10. After that, the loop will be terminated, and a series of 1-10 will be printed on the screen
 Q5) Explain Break statement in detail with examplesA5)

The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following two scenarios:

  1. With switch case
  2. With loop

Syntax:

  1. //loop or switch case   
  2. break;  

Flowchart of break in c

Example

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. void main ()  
  4. {  
  5.     int i;  
  6.     for(i = 0; i<10; i++)  
  7.     {  
  8.         printf("%d ",i);  
  9.         if(i == 5)  
  10.         break;  
  11.     }  
  12.     printf("came outside of loop i = %d",i);  
  13.       
  14. }  

Output

0 1 2 3 4 5 came outside of loop i = 5

Example of C break statement with switch case

C break statement with the nested loop

In such case, it breaks only the inner loop, but not outer loop.

  1. #include<stdio.h>  
  2. int main(){  
  3. int i=1,j=1;//initializing a local variable    
  4. for(i=1;i<=3;i++){      
  5. for(j=1;j<=3;j++){    
  6. printf("%d &d\n",i,j);    
  7. if(i==2 && j==2){    
  8. break;//will break loop of j only    
  9. }    
  10. }//end of for loop    
  11. return 0;  
  12. }    

Output

1 1

1 2

1 3

2 1

2 2

3 1

3 2

3 3

As you can see the output on the console, 2 3 is not printed because there is a break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break statement is used to break the inner loop only.

break statement with while loop

Consider the following example to use break statement inside while loop.

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int i = 0;  
  5.     while(1)  
  6.     {  
  7.         printf("%d  ",i);  
  8.         i++;  
  9.         if(i == 10)  
  10.         break;   
  11.     }  
  12.     printf("came out of while loop");  
  13. }  

Output

0  1  2  3  4  5  6  7  8  9  came out of while loop 

break statement with do-while loop

Consider the following example to use the break statement with a do-while loop.

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.    int n=2,i,choice;  
  5.    do  
  6.    {  
  7.        i=1;  
  8.        while(i<=10)  
  9.        {  
  10.            printf("%d X %d = %d\n",n,i,n*i);  
  11.            i++;  
  12.        }  
  13.        printf("do you want to continue with the table of %d , enter any non-zero value to continue.",n+1);  
  14.        scanf("%d",&choice);  
  15.     if(choice == 0)  
  16.        {  
  17.            break;  
  18.        }  
  19.        n++;  
  20.    }while(1);  
  21. }  

Output

2 X 1 = 2

2 X 2 = 4

2 X 3 = 6

2 X 4 = 8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

do you want to continue with the table of 3 , enter any non-zero value to continue.1

3 X 1 = 3

3 X 2 = 6

3 X 3 = 9

3 X 4 = 12

3 X 5 = 15

3 X 6 = 18

3 X 7 = 21

3 X 8 = 24

3 X 9 = 27

3 X 10 = 30

do you want to continue with the table of 4 , enter any non-zero value to continue.0

Q6) Explain Continue statement in detail with examplesA6)

The continue statement in C language is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a condition so that we can skip some code for a particular condition.

Syntax:

  1. //loop statements  
  2. continue;  
  3. //some lines of the code which is to be skipped  

Continue statement example 1

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int i = 0;   
  5.     while(i!=10)  
  6.     {  
  7.         printf("%d", i);   
  8.         continue;   
  9.         i++;  
  10.     }  
  11. }  

Output

infinite loop

Continue statement example 2

  1. #include<stdio.h>  
  2. int main(){  
  3. int i=1;//initializing a local variable       
  4. //starting a loop from 1 to 10    
  5. for(i=1;i<=10;i++){      
  6. if(i==5){//if value of i is equal to 5, it will continue the loop    
  7. continue;    
  8. }    
  9. printf("%d \n",i);    
  10. }//end of for loop    
  11. return 0;  
  12. }    

Output

1

2

3

4

6

7

8

9

10

As you can see, 5 is not printed on the console because loop is continued at i==5.

C continue statement with inner loop

In such case, C continue statement continues only inner loop, but not outer loop.

  1. #include<stdio.h>  
  2. int main(){  
  3. int i=1,j=1;//initializing a local variable    
  4. for(i=1;i<=3;i++){      
  5. for(j=1;j<=3;j++){    
  6. if(i==2 && j==2){    
  7. continue;//will continue loop of j only    
  8. }    
  9. printf("%d %d\n",i,j);    
  10. }    
  11. }//end of for loop    
  12. return 0;  
  13. }    

Output

1 1

1 2

1 3

2 1

2 3

3 1

3 2

3 3

As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and j==2.

 Q7) What is Functions explain in detail?A7)

In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program. The function is also known as procedureor subroutinein other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

  • By using functions, we can avoid rewriting same logic/code again and again in a program.
  • We can call C functions any number of times in a program and from any place in a program.
  • We can track a large C program easily when it is divided into multiple functions.
  • Reusability is the main achievement of C functions.
  • However, Function calling is always a overhead in a C program.

Function Aspects

There are three aspects of a C function.

  • Function declaration A function must be declared globally in a c program to tell the compiler about the function name, function parameters, and return type.
  • Function call Function can be called from anywhere in the program. The parameter list must not differ in function calling and function declaration. We must pass the same number of functions as it is declared in the function declaration.
  • Function definition It contains the actual statements which are to be executed. It is the most important aspect to which the control comes when the function is called. Here, we must notice that only one value can be returned from the function.

 

SN

C function aspects

Syntax

1

Function declaration

return_type function_name (argument list);

2

Function call

function_name (argument_list)

3

Function definition

return_type function_name (argument list) {function body;}

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Types of Functions

There are two types of functions in C programming:

  1. Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
  2. User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code.

C Function

 Q8) Program to check whether a number is even or oddA8)

 

#include<stdio.h>  

int even_odd(int);  

void main()  

{  

 int n,flag=0;  

 printf("\nGoing to check whether a number is even or odd");  

 printf("\nEnter the number: ");  

 scanf("%d",&n);  

 flag = even_odd(n);  

 if(flag == 0)  

 {  

    printf("\nThe number is odd");  

 }  

 else   

 {  

    printf("\nThe number is even");  

 }  

}  

int even_odd(int n)  

{  

   if(n%2 == 0)  

    {  

        return 1;  

    }  

    else   

   {  

       return 0;  

    }  

}  

Output

Going to check whether a number is even or odd

Enter the number: 100

The number is even

Q9) Program to calculate the average of five numbers.A9)

 

#include<stdio.h>  

void average(int, int, int, int, int);  

void main()  

{  

    int a,b,c,d,e;   

   printf("\nGoing to calculate the average of five numbers:");  

    printf("\nEnter five numbers:");  

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

    average(a,b,c,d,e);  

}  

void average(int a, int b, int c, int d, int e)  

{  

    float avg;   

    avg = (a+b+c+d+e)/5;   

    printf("The average of given five numbers : %f",avg);  

}  

Output

Going to calculate the average of five numbers:

Enter five numbers:10

The average of given five numbers : 30.000000

 Q10) Explain call by value and call by reference A10)

Call by value in C

  • In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method.
  • In call by value method, we cannot modify the value of the actual parameter by the formal parameter.
  • In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.
  • The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include<stdio.h>  
  2. void change(int num) {    
  3.     printf("Before adding value inside function num=%d \n",num);    
  4.     num=num+100;    
  5.     printf("After adding value inside function num=%d \n", num);    
  6. }    
  7. int main() {    
  8.     int x=100;    
  9.     printf("Before function call x=%d \n", x);    
  10.     change(x);//passing value in function    
  11.     printf("After function call x=%d \n", x);    
  12. return 0;  
  13. }    

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 Value Example: Swapping the values of the two variables

  1. #include <stdio.h>  
  2. void swap(int , int); //prototype of the function   
  3. int main()  
  4. {  
  5.     int a = 10;  
  6.     int b = 20;   
  7.     printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main  
  8.     swap(a,b);  
  9.     printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20  
  10. }  
  11. void swap (int a, int b)  
  12. {  
  13.     int temp;   
  14.     temp = a;  
  15.     a=b;  
  16.     b=temp;  
  17.     printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10   
  18. }  

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 10, b = 20 

Call by reference in C

  • In call by reference, the address of the variable is passed into the function call as the actual parameter.
  • The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.
  • In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.

Consider the following example for the call by reference.

  1. #include<stdio.h>  
  2. void change(int *num) {    
  3.     printf("Before adding value inside function num=%d \n",*num);    
  4.     (*num) += 100;    
  5.     printf("After adding value inside function num=%d \n", *num);    
  6. }      
  7. int main() {    
  8.     int x=100;    
  9.     printf("Before function call x=%d \n", x);    
  10.     change(&x);//passing reference in function    
  11.     printf("After function call x=%d \n", x);    
  12. return 0;  
  13. }    

Output

Before function call x=100

Before adding value inside function num=100

After adding value inside function num=200

After function call x=200

Call by reference Example: Swapping the values of the two variables

  1. #include <stdio.h>  
  2. void swap(int *, int *); //prototype of the function   
  3. int main()  
  4. {  
  5.     int a = 10;  
  6.     int b = 20;   
  7.     printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main  
  8.     swap(&a,&b);  
  9.     printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20  
  10. }  
  11. void swap (int *a, int *b)  
  12. {  
  13.     int temp;   
  14.     temp = *a;  
  15.     *a=*b;  
  16.     *b=temp;  
  17.     printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10   
  18. }  

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 20, b = 10