C program to print numbers using for loop

In this program we will print numbers using for loop. We want no comma at last so we will use if else statement or conditional operator to do this.
We will print natural numbers from 1 to 10 using for loop. We do not want to print comma at last so we have to use an if-else statement or conditional operator to do so.

C program to print numbers using for loop and conditional operator

 #include<stdio.h> 
 #include<conio.h> 
 void main() 
 { 
 int i; 
 clrscr(); 
 for(i=1;i<11;i++) 
 { 
 printf("%d",i); 
 printf((i==10)?"":","); 
 } 
 getch(); 
 }
Approach:
  • Initialize an int variable.
  • Using for loop we will print natural numbers.
  • We will use a conditional operator to print comma. If "i" is equal to the last number then it will not print a comma otherwise it will print a comma.

Print Numbers in C using if-else

Write a program to print numbers using for loop.
1,2,3,4,5,6,7,8,9,10
    #include<stdio.h> 
 #include<conio.h> 
 void main() 
 {int i;clrscr(); 
 for(i=1;i<11;i++) 
 { 
 printf("%d",i); 
 if(i==10) 
 printf(""); 
 else 
 printf(","); 
 } 
 getch(); 
 }
About this post:
This post is written by Coding Wallah. This query is brought to you by Shivam Gupta. Thank you so much for reading this post. If you have any queries related to this post,please let me know in the comment section. 

Post a Comment

Please do not enter any spam link in the comment box.