C program to print numbers using for loop

C program to print numbers using for loop: we will print numbers using for loop. We want no comma at last so we will use an if-else statement or conditional operator to do this. 

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 conditional operator to print comma. if "i" equal to the last number then it will not print comma otherwise it will print comma.
Query: we have to print numbers in the following method 
1,2,3,4,5,6,7,8,9,10
No comma at last

C program to print numbers using for loop

Print Numbers in C using for loop and if-else

 #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(); 
 }

Approach:

  1. Initialize an int variable for loop 
  2. Using for loop we will print natural numbers.
  3. If "i" equal to 10 then it will not print a comma 
  4. If the value of i is other than 10 then it will print comma.
You can also input how many numbers the user wants to print for that you have to initialize another int variable called num.
int num;
you can do using the following statements
scanf(“%d”,&num);
you should edit for loop statement according to this variable
for(i=1;i<=num;i++)

You can also, edit if-else statement in the following way

 if(i==num)
printf("");elseprintf(",");

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 you can comment below. 

This is a very easy program but you can face a bit difficult to not print comma at last.

 You can also subscribe to our newsletter so that you will receive notifications when I upload any program so what are you waiting for. if you like this post share this post with your friends 

Siddharth Jha
• Software Developer • Website Developer • Masters in SEO • Social Media Manager

Related Posts

Post a Comment

Follow by Email