Saturday, July 2, 2016

C Program to print series 1, 2, 3, 4, 5.....N for the given value of N.

C Program to print series 1, 2, 3, 4, 5.....N for the given value of N.
For example, if N=5, output should be
1, 2, 3, 4, 5


#include<stdio.h>
int main()
{
 int i, N;
 printf("Enter N:");
 scanf("%d", &N);

 for(i=1; i<=N; i++)
 {
  printf("%d",i);
 
  //Logic avoid last , 
  if(i!=N)
   printf(", ");
 }
 return 0; }

Output of program
Enter N:5
1, 2, 3, 4, 5


6 comments:

  1. If i want print negative integer numbers than what condition apply.
    Tell me sir

    ReplyDelete
    Replies
    1. You can change your for loop as under to print negative integers:

      for(i=0; i>=-5; i--)
      {
      printf("%d ", i);
      }

      Read full C program to print negative series here.

      Delete
  2. How to print sum=1+1/2+1/3+1/4+....n in c language

    ReplyDelete
    Replies
    1. Dear friend, your requested program is posted on the blog at following link: Sum of series 1 + 1/2 + 1/3 + 1/4 + ....N

      Delete
  3. How to solve it when no value of N is given?

    ReplyDelete
    Replies
    1. Dear MJ,
      Thank you for referring this blog.
      When no value of N is taken from user, in that case program becomes static. For example, to print 1 2 3 4 5 one can write a for loop as shown below:
      for(i=1; i<=5; i++)
      { printf("%d ", i); }

      Delete