looping statements in C ( while, do while , for)

Loops in C

Loops are used in programming to repeat a specific block of statements until some end condition is met.


Types of Loops in C

Depending on the position of the control statement in a program, looping in C is classified into two types:

  1. Entry controlled loop

  2. Exit controlled loop


1. Entry Controlled Loop (Pre-checking Loop)

  • In an entry controlled loop, the condition is checked before executing the loop body.

  • If the condition is false, the loop body may not execute at all.

  • Also called a pre-checking loop.


2. Exit Controlled Loop (Post-checking Loop)

  • In an exit controlled loop, the condition is checked after executing the loop body.

  • The loop body executes at least once.

  • Also called a post-checking loop.


Important Note

  • Control conditions must be well defined and specified, otherwise the loop may execute infinitely.

  • A loop that never stops and executes statements repeatedly is called an:

    • Infinite loop

    • Also known as an Endless loop


Looping Statements in C

There are three looping statements in C programming:

  • while loop(Entry controlled)

  • do...while loop(Exit controlled)

  • for loop(Entry controlled)

 

while Loop in C

The while loop is an entry-controlled looping statement.


Syntax

while (testExpression) { // codes }

Explanation

  • The testExpression checks whether the condition is true or false before each iteration.

  • The while loop first evaluates the test expression.

  • If the test expression is true (nonzero), the statements inside the loop body are executed.

  • After execution, the test expression is evaluated again.

  • This process continues until the test expression becomes false.

  • When the test expression is false, the while loop terminates.



 
// Program to find factorial of a number 
// For a positive integer n, factorial = 1*2*3...n
#include <stdio.h>
int main()
{
int number;
long long factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial= 1;
//loop terminates when number is less than or equal to 0
while(number > 0)
{
factorial*= number;
--number;
}
printf("Factorial=%lld", factorial);
return 0;
}
 

do...while Loop in C

The do...while loop is similar to the while loop with one important difference:

  • The body of the do...while loop executes once before checking the test expression.

  • Hence, the do...while loop always runs at least once.

  • It is an exit-controlled loop.


Syntax

do { // codes } while (testExpression);

Explanation

  • The code block (loop body) inside the braces is executed first.

  • Then, the test expression is evaluated.

  • If the test expression is true (nonzero), the loop body executes again.

  • This process continues until the test expression becomes false (0).

  • When the test expression is false, the do...while loop terminates.



 

// Program to add numbers until user enters zero
#include <stdio.h>
int main()
{
double number, sum = 0;
//loop body is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf",&number);
sum+= number;
}
while(number!= 0.0);
printf("Sum= %.2lf",sum);
return 0;
}

whiledo-while
Condition is checked first then statement(s) is executed.Statement(s) is executed atleast once, thereafter condition is checked.
It might occur statement(s) is executed zero times, If condition is false.At least once the statement(s) is executed.
No semicolon at the end of while.
while(condition)
Semicolon at the end of while.
while(condition);
If there is a single statement, brackets are not required.Brackets are always required.
Variable in condition is initialized before the execution of loop.variable may be initialized before or within the loop.
while loop is entry controlled loop.do-while loop is exit controlled loop.
while(condition)
{ statement(s); }
do { statement(s); }
while(condition);

 

for Loop in C

The for loop is an entry-controlled looping statement.


Syntax

for (initializationStatement; testExpression; updateStatement) { // statements }

Explanation

  • The initialization statement is executed only once at the beginning of the loop.

  • Then, the test expression is evaluated:

    • If the test expression is false (0), the for loop terminates.

    • If the test expression is true (nonzero), the statements inside the loop body execute.

  • After executing the loop body, the update statement runs.

  • This process repeats until the test expression becomes false.


Note

The for loop is commonly used when the number of iterations is known in advance.




Example: for loop

// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d",&num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum+= count;
}
printf("Sum= %d", sum);
return 0;
}


Summary:


Which Loop to Select?

Selecting the right loop can be challenging. To choose an appropriate loop, follow these steps:

  1. Analyze the problem and determine whether it requires a pre-test loop or a post-test loop.

  2. If a pre-test is required, use a while loop or a for loop.

  3. If a post-test is required, use a do-while loop.


Summary

  • Looping is one of the key concepts in any programming language.

  • A block of loop control statements in C executes repeatedly until the condition becomes false.

  • Loops are of two types:

    • Entry-controlled loops

    • Exit-controlled loops

  • C programming provides:

    1. while loop

    2. do-while loop

    3. for loop

  • for and while loops are entry-controlled loops.

  • do-while is an exit-controlled loop.

Sample programs ( all university questions)

Print factors of a number
#include <stdio.h>
main()
{
int n,i;
printf("Enter the number...\n");
scanf("%d",&n);
printf("Factors of the number\n");
for(i=1;i<=n;i++)
if(n%i==0)
printf("%d\n",i);
}
Note: an efficient way is to go up to n/2

Check whether the given number is prime or not

#include <stdio.h>
#include <math.h>
main()
{  
  int n,flag=1,i;
  printf("enter a number n >1 for primality test\n");
  scanf("%d",&n);
   for(i=2;i<=sqrt(n);i++)
     if(n%i==0)
      { flag=0;break;}
  if(flag==1)
     printf("%d is prime \n",n);
  else
     printf("%d is not prime \n",n);
}

Print Fibonacci Series up to 100

#include <stdio.h>
main() {
int a=0,b=1,c=1;
  while(c<100)

 {
    printf("%d, ", c);
    c = a+b;
    a= b;
     b=c;
    }

printf("\n");
}

Program to reverse a number
#include <stdio.h>
main()

 {
int n, rev = 0, digit;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
digit= n % 10;
rev = rev * 10 + digit;
n /= 10;
}
printf("Reversed number = %d\n", rev);
}

printing the sin series x^1/1!-x^3/3!+x^5/5!.......x^20/20!

#include <stdio.h>
main()
{  
  int i,sign=1;

  for(i=1;i<=20;i+=2)
   {
     printf("x^%d/%d!",i,i);
     sign=-sign;
     if(sign==-1)
        printf("-");
     else
        printf("+");
    }

Check for perfect number ( Eg: 6,28,496 etc..)
#include <stdio.h>
#include <string.h>
int main()
{
int n,i,s=0;
printf("Enter the number\n");
scanf("%d",&n);
for(i=1;i<=n/2;i++)
{
if(n%i==0)
s=s+i;
}
if(s==n)
printf("%d is a perfect number \n",n);
else
printf("%d is a not a perfect number \n",n);
}
Write a C program to find the sum of first and last digit of a number.

 #include <stdio.h>
main()

 {
int n, fdig,ldig;
printf("Enter an integer: ");
scanf("%d", &n);
ldig=n%10;
while (n != 0) {
    fdig=n%10;
n /= 10;
}
printf("Sum of first and last digit = %d\n", fdig+ldig);
}

Write C program to convert the given decimal number into binary number.( university question)

#include <stdio.h>
main()
{
int i,n,bit,bin=0,place=1;
printf("Enter the number:");
scanf("%d",&n);
while(n!=0)
{
bit=n%2;
bin=bin+bit*place;
n=n/2;
place=place*10;
}
printf("Binary=%d\n",bin);
}

Write a C function to evaluate the series 1 + x + x^2 + ....... + x^n , given x and n.(university question)
#include <stdio.h>

int main() {
    int x, n;
    long long term = 1;
    long long sum = 1;

    printf("Enter the value of x: ");
    scanf("%d", &x);

    printf("Enter the value of n: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        term = term * x;
        sum = sum + term;
    }

    printf("The sum of the series is: %lld\n", sum);

    return 0;
}
Enter the value of x: 2
Enter the value of n: 4
The sum of the series is: 31

Write a C program to print sum of n natural numbers. also count the number of odd numbers in it.( University Question)
#include <stdio.h>

int main() {
    int n, sum = 0, oddCount = 0;

    // Input from the user
    printf("Enter a positive integer n: ");
    scanf("%d", &n);

    // Validate input
    if (n <= 0) {
        printf("Please enter a positive integer greater than 0.\n");
        return 1;
    }

    // Loop to calculate sum and count odd numbers
    for (int i = 1; i <= n; i++) {
        sum += i;

        if (i % 2 != 0) {
            oddCount++;
        }
    }

    // Output results
    printf("Sum of first %d natural numbers = %d\n", n, sum);
    printf("Number of odd numbers = %d\n", oddCount);

    return 0;
}
Output
Enter a positive integer n: 10
Sum of first 10 natural numbers = 55
Number of odd numbers = 5

Write a C program to check whether a given number is a perfect number.(university question)
Hint: A perfect number is a positive integer that is equal to the sum of its
proper divisors (excluding itself). Example: The divisors of 6 (excluding 6)
are 1, 2, and 3. Since 1 + 2 + 3 = 6, the number 6 is a perfect number.

#include <stdio.h>

int main() {
    int num, i, sum = 0;

    printf("Enter a positive number: ");
    scanf("%d", &num);

    /* Check for valid input */
    if (num <= 0) {
        printf("Please enter a positive integer.\n");
        return 1;
    }

    /* Find sum of proper divisors */
    for (i = 1; i <= num / 2; i++) {
        if (num % i == 0) {
            sum += i;
        }
    }

    /* Check if perfect number */
    if (sum == num) {
        printf("%d is a PERFECT number.\n", num);
    } else {
        printf("%d is NOT a perfect number.\n", num);
    }

    return 0;
}

Programs to try using Loops
1)Print the even numbers between 0 and 50 (use while)
2)Print the odd numbers between 0 and 50 in the reverse order ( use while)
3)Print the series 5,10,15,….,100 (using for loop)
4)Generate the series 1, 2, 4 ,7, 11 ,16....n ( use while...read n)
5)Generate the Fibonacci series 0 1 1 2 3 5 8…..n ( use do while..read n)
6)Find the factorial of a number ( use for statement do not use built in factorial() function)
7)Print the powers of a number upto 10th power. ( Eg: if n=2 then the program should print 2^0, 2^1, 2^2,2^3,…..,2^10 use for loop)
8)Print the multiplication table of a given number. ( use while)
9)Print the numbers from 1 to 10 and their natural logarithms as a table ( use for)
10)Find the sum of the digits of a number.( use while-university question)
11)Check whether the given 3 digit number is an Armstrong number. (use do while Eg:153,370,371,407) ( uq)
12)Find the factors of a number ( use for)
13)Check whether the given number is prime or not ( use for)
14) Find the GCD or HCF of two numbers ( use Euclid algorithm and while loop)
15) Reverse a number (use while)
16)Find the numbers between 10 and 1000 that are divisible by 13 but not divisible by 3
( use for)
17)Find the sum of series 1-x^2/2+x^4/4-x^6/6........x^n/n ( use while)
18)Check whether the given number is a Krishnamurti number( Krishnamurti Number: It is a number which is equal to the sum of the factorials of all its digits.
For example : 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145)
19)Read N numbers and find the biggest and smallest. ( university question)
20)Read N numbers and find the sum of all odd and even numbers separately.(university question)
21)Count the number of digits in a number.(university question)
22)Write a C program to input a list of n numbers. Calculate and display the sum of cubes of each value in the list.(university question)
23)Write a C program to count the number of zeros and negative terms in a given set of n numbers.
24)Write a C program to input a list of n numbers. calculate and display the average of numbers. Also display the cube of each value in the list.( university question)
25)read mark of n students and print the average mark.Also print the number of students who scored more than 80% mark (mark out of 50)
26)Find the sum s=1+2/3!+3/5!+4/7!... n
27)Write a C program to evaluate the series x-x^3/3!+x^5/5!-x^7/7!....n(uq)
28)Write a program to check whether a number is perfect or not.(sum of factors excluding the number equal to the number :eg 6=1+2+3)( uq)
29)Print the pattern 101010....using for loop(uq) 
30) Print the binary equivalent of a number( eg 12: 1100) ( university question)
31.Write an algorithm to check whether largest of 3 natural numbers is prime or not.(uq)
32.Write a C program to find the sum of first and last digit of a number.( uq)
33.Calculate the sum of the first n odd integers (i.e., 1 + 3 + 5 + - - - + 2n - 1). Test the program by calculating the sum of the first 100 odd integers (note that the last integer will be 199).

 

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays