Example:16
Write a C program to take input for 5 nos , check and print total even elements entered by the user.
Sol:
#include <stdio.h> int main() { int i=1,n,p=0; while(i<=5) { printf("Enter any no "); scanf("%d",&n); if(n%2==0) p++; i=i+1; } printf("Total even elements = %d\n",p); return 0; }
Output:
Enter any no 2
Enter any no 5
Enter any no 6
Enter any no 3
Enter any no 8
Total even elements = 3
Example:17
Write a C program to take input for 5 nos , check and print total odd elements entered by the user.
Sol:
#include <stdio.h> int main() { int i=1,n,p=0; while(i<=5) { printf("Enter any no "); scanf("%d",&n); if(n%2==1) //or if(i%2!=0) p++; i=i+1; } printf("Total odd elements = %d\n",p); return 0; }
Output:
Enter any no 3
Enter any no 6
Enter any no 2
Enter any no 5
Enter any no 7
Total odd elements = 3
Example:18
Write a C program to take input for 5 nos , check and print the following :
a. total +ve elements
b. sum of all +ve elements.
c. Average of all +ve elements
Sol:
#include <stdio.h> int main() { int i=1,n,p=0,s=0; float av; while(i<=5) { printf("Enter any no "); scanf("%d",&n); if(n>0) { p++; s=s+n; } i=i+1; } av=(float)s/p; printf("Total +ve elements = %d\n",p); printf("Sum of all +ve elements = %d\n",s); printf("Average of all +ve elements = %f\n",av); return 0; }
Output:
Enter any no 2
Enter any no 3
Enter any no 6
Enter any no -7
Enter any no -8
Total +ve elements = 3
Sum of all +ve elements = 11
Average of all +ve elements = 3.666667
Example:19
Write a C program to take input for 5 nos , check and print the following :
a. total -ve elements
b. sum of all -ve elements.
c. Average of all -ve elements
Sol:
#include <stdio.h> int main() { int i=1,n,p=0,s=0; float av; while(i<=5) { printf("Enter any no "); scanf("%d",&n); if(n<0) { p++; s=s+n; } i=i+1; } av=(float)s/p; printf("Total -ve elements = %d\n",p); printf("Sum of all -ve elements = %d\n",s); printf("Average of all -ve elements = %f\n",av); return 0; }
Output:
Enter any no 6
Enter any no -7
Enter any no 2
Enter any no -8
Enter any no 9
Total -ve elements = 2
Sum of all -ve elements = -15
Average of all -ve elements = -7.500000
Example:20
Write a C program to take input for 5 nos , check and print the following :
a. total even elements
b. sum of all even elements.
c. Average of all even elements
Sol:
#include <stdio.h> int main() { int i=1,n,p=0,s=0; float av; while(i<=5) { printf("Enter any no "); scanf("%d",&n); if(n%2==0) { p++; s=s+n; } i=i+1; } av=(float)s/p; printf("Total even elements = %d\n",p); printf("Sum of all even elements = %d\n",s); printf("Average of all even elements = %f\n",av); return 0; }
Output:
Enter any no 6
Enter any no 3
Enter any no 2
Enter any no 4
Enter any no 5
Total even elements = 3
Sum of all even elements = 12
Average of all even elements = 4.000000