In todays tutorial we shall be learning how to find and display odd numbers using while loop in C-Programming language. Before you can successfully write this code you need to understand 3 different concept:
- Variable declaration
- Format specifier
- While loop and finally
- If statement.
What is a variable
A variable is a container that is used to either store an integer value, char value etc. The syntax to declare a variable is Data type variable_name= value. To store an integer value to variable name number we write: int number = 10; and to store a character value we write char grade='A';.
What is format specify
In C-programming Language a format specifier is used to tell the compiler about the type of data that must be given or input and the type of data that must be printed on the screen. Format specifiers are used to take inputs and print the output of a data type.
% symbol is used along side a letter as format specifier. Example %d for integer, %f for float, c% for character.
% symbol is used along side a letter as format specifier. Example %d for integer, %f for float, c% for character.
What is a while loop
While loop is a control structure that is used to iterate over a block of code over until the specified condition becomes false. syntax of a while loop.
int iterator=1;
while (condition){
//block of code
iterator++;
}
What is an if statement
An if statement is a programming conditional statement that execute it block of code if the condition stated for it evaluate to true. The syntax for if statement is:
if(condition){
//block of code to be executed
}
Solution
#include <stdio.h>
int main() {
// Write C code here
printf("List of odd numbers from 1-50:\n");
int iterator=1;
while(iterator <=50){
if(iterator%2==1){
printf(" %d ", iterator);
}
iterator++;
}
return 0;
}
the % used within the if statement is called a modulus operator.
Tags:
C