All articles
c

A program to explain WHILE

Share this article

Share on LinkedIn Share on X (formerly Twitter)

C Programming Language 026

The following code shows how to write a program to explain WHILE. Find the sum of odd numbers below 'n'.

Program

#include <stdio.h>
 
void main()
{
    int i = 1, n, sum = 0;
 
    printf("Enter the value of n: ");
    scanf("%d", &n);
 
    while (i <= n)
    {
        if (i % 2 == 1)
        {
            sum = sum + i;
        }
 
        i++;
    };
 
    printf("%d", sum);
 
    printf("\n");
}

Result

Enter the value of n: 4
4

Comments