Menu
×
Tutorials Ms Word Tutorial Ms Excel Tutorial Ms PowerPoint Tutorial C Language Tutorial C++ Tutorial C Sharp Tutorial Visual Basic Tutorial HTML Tutorial CSS Tutorial JavaScript Tutorial WordPress Tutorial
     ❯   

ADVERTISEMENT

Print Odd Numbers Till ‘N’

This C program takes an integer ‘n’ as input from the user and then prints all odd numbers from 1 to ‘n’.

#include<stdio.h>
main()
{
  int i,n;
  printf("Enter a Number\n");
  scanf("%d",&n);
  for(i=0;i<=n;i++)
  {
    if(i%2==1)
      printf("%d\n",i);
    else
      continue;
   }
   printf("\n");
}
C Programming Examples
OUTPUT
Enter a Number
20
1
3
5
7
9
11
13
15
17
19
C Programming Examples

Explanation:

Here’s a step-by-step explanation of the code:

Header File:

  • The program includes the standard C library header <stdio.h>. This header is required for input and output operations.

Main Function:

  • The main function is the entry point of the program, where the execution starts.

Variable Declaration:

  • The program declares two integer variables: ‘i’ and ‘n’.
  • ‘i’ is used as a loop counter to iterate through numbers, and ‘n’ is used to store the user’s input.

User Input:

  • The program prompts the user to enter a number with the printf function and reads the input using scanf. The entered value is stored in the variable ‘n’.

For Loop:

  • The program uses a for loop to iterate through numbers from 0 to ‘n’.
  • Initialization: i = 0 – The loop counter ‘i’ is initialized to 0 when the loop begins.
  • Condition: i <= n – The loop continues as long as ‘i’ is less than or equal to ‘n’.

Conditional Check:

  • Within the loop, there’s an if statement to check whether ‘i’ is an odd number:
  • if (i % 2 == 1) – The modulo operator (%) is used to check if ‘i’ divided by 2 has a remainder of 1, which indicates an odd number.
  • If ‘i’ is an odd number, the program proceeds to the next step. If ‘i’ is even, it encounters the else statement and uses continue to skip the remaining code in the loop for this iteration.

Printing Odd Numbers:

  • If ‘i’ is an odd number (i.e., the condition is met), the program uses printf to print ‘i’ followed by a newline character (\n). This displays the current odd number on the screen.

Loop Iteration:

  • The loop continues to execute, incrementing ‘i’ in each iteration. It checks each number from 0 to ‘n’, and when it encounters an odd number, it is printed.

End of Program:

  • Once ‘i’ exceeds ‘n’, the loop terminates, and the program reaches the end of the main function, concluding the program’s execution.

This code takes a user-entered integer ‘n’, and then, using a for loop, it iterates through numbers from 0 to ‘n’. It checks each number and prints the odd ones, one per line, using the printf statement.

Spread the love
Scroll to Top
Scroll to Top