C Exercises

Jul 3, 2020

C Program to Print all Negative Elements in Array

Ex: Write a C program to print all negative elements in array. How to write a C program which print all negative elements in array. C program to print all negative elements in array.


Input from user:

Enter the limit: 5

Enter the numbers:
10
-3
12
-9
-2

Expected output:

Negative elements are:
-3
-9
-2




  Step by step logic of the given program:


1. Accept input (limit) from user declare variable say no.

2. Declare array of size 100 using a[100].

3. Declare variable i  for a loop.

4. Use one for loop to accept elements one by one and store it in variable a[i](it store elements position wise):
for(i=0;i<no;i++)
{
scanf("%d",&a[i]);
  }


5. Use one more for loop to print negative elements using if statement.

6. Inside the for loop give condition using if-statement-if(a[i]<0). It means if array of i position number is less than zero then we will print this (negative) number:
for(i=0;i<no;i++)
{
if(a[i]<0)
printf("\n %d",a[i]);
}





  C Program to Print all Negative Elements in Array:


#include<stdio.h>
void main()
{
int a[100],i,no;

printf("Enter how many elements you are going to enter: ");
scanf("%d",&no);

printf("Enter the elements:\n");
for(i=0;i<no;i++)
{
scanf("%d",&a[i]);

}

printf("All negative elements in array are:");
for(i=0;i<no;i++)
{
if(a[i]<0)

printf("\n %d",a[i]);
}

}


Above program shows the following output:

C Program to Print all Negative Elements in Array



No comments:

Post a Comment

If you have any doubts, please discuss here...