C Language Tutorials by Ghulam Murtaza Dahar - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Output

Enter a number

3

Enter a number

-2

Enter a number

0

sum=1

In this C program, user is asked a number and it is added with sum. Then, only the test condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to 0, the body of do...while loop is again executed until num equals to zero.

C Programming break and continue Statement

There are two statement built in C, break; and continue; to interrupt the normal flow of control of a program. Loops performs a set of operation repeately until certain condition becomes false but, it is sometimes desirable to skip some statements inside loop and terminate the loop immediately without checking the test expression. In such cases, break and continue statements are used.

break Statement

In C programming, break is used in terminating the loop immediately after it is encountered. The break statement is used with conditional if statement.

Syntax of break statement

break;

The break statement can be used in terminating all three loops for, while and do...while loops.

index-30_1.jpg

index-30_2.jpg

The figure below explains the working of break statement in all three type of loops.

Example of break statement

Write a C program to find average of maximum of n positive numbers entered by user. But, if the input is negative,

display the average(excluding the average of negative input) and end the program.

/* C program to demonstrate the working of break statement by terminating a loop, if user

inputs negative number*/

# include <stdio.h>

int main(){

float num,average,sum;

int i,n;

printf("Maximum no. of inputs\n");

scanf("%d",&n);

for(i=1;i<=n;++i){

printf("Enter n%d: ",i);

scanf("%f",&num);

if(num<0.0)

break; //for loop breaks if num<0.0

sum=sum+num;

}

average=sum/(i-1);

printf("Average=%.2f",average);

return 0;

}