Print and Separate the Positive and Negative Numbers Using For Loop in C


This program is written in the C programming language and is used to print the positive and negative numbers between a given range of values and count the total number of positive and negative numbers. The program starts by including the standard input/output library (stdio.h) and then defines a main function. Within the main function, the program declares four variables: "i", "n", "pos", "neg" and "s". The variable "i" is used to store the starting value entered by the user, "n" is used to store the ending value entered by the user, "pos" and "neg" are used to count the total number of positive and negative numbers respectively and "s" is used to store the initial value of "i" so that it can be reused later in the program.

The program then prompts the user to enter the starting and ending values using the "printf" function and stores the values in the variables "i" and "n" using the "scanf" function. Next, the program uses a "for" loop with the counter variable "i" to iterate from the starting value to the ending value. Within this loop, it uses an if statement to check if the current value of "i" is less than 0 or not. If the current value of "i" is less than 0, it means that the number is negative. If the number is negative, the program uses the "printf" function to print the number and increments the value of the "neg" variable by 1. This loop will print all the negative numbers between the given range.

Source Code

#include<stdio.h>
int main()
{
  int i,n,pos,neg,s;
  printf("\nEnter the starting value:");
  scanf("%d",&i);
  s=i;
  printf("\nEnter the ending value:");
  scanf("%d",&n);
  printf("\nNegative numbers:");
  for(i;i<=n;i++)
  {
  if(i<0)
  {
    printf("\n%d",i);
    neg++;
  }
  }
  i=s;
  printf("\nPositive numbers:");
  for(i;i<=n;i++)
  {
    if(i>0)
    {
      printf("\n%d",i);
      pos++;
    }
  }
  printf("\nTotal number of positive:%d",pos);
  printf("\nTotal number of negative:%d",neg);
  return 0;
}
         
To download raw file Click Here

Output

Enter the starting value: -5
Enter the ending value: 5
Negative numbers:
-5
-4
-3
-2
-1

Positive numbers:
1
2
3
4
5

Total number of positive:5
Total number of negative:5


List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C