Numeric Array and Functions
Question:1
C Program to take input for “n” elements using an array. Pass the entire array to a function and display all the array elements.
Sol:
#include<stdio.h> void show(int a[],int n) { int i; for(i=0;i<n;i++) { printf("%d\n",a[i]); } } int main() { int a[50],i,n; printf("Enter total elements "); scanf("%d",&n); /* input */ for(i=0;i<n;i++) { printf("Enter element "); scanf("%d",&a[i]); } /* to display elements */ show(a,n); return(0); }
/* Output */ Enter total elements 5 Enter element 10 Enter element 20 Enter element 30 Enter element 40 Enter element 50 10 20 30 40 50
Question:2
C Program to take input for “n” elements using an array. Pass the entire array to a function, Further calculate and print their sum of all the elements.
Sol:
#include<stdio.h> void show(int a[],int n) { int i,s=0; for(i=0;i<n;i++) { printf("%d\n",a[i]); s=s+a[i]; } printf("Sum = %d\n",s); } int main() { int a[50],i,n; printf("Enter total elements "); scanf("%d",&n); /* input */ for(i=0;i<n;i++) { printf("Enter element "); scanf("%d",&a[i]); } /* to display elements */ show(a,n); return(0); }
/* Output */ Enter total elements 5 Enter element 10 Enter element 2 Enter element 6 Enter element 32 Enter element 14 10 2 6 32 14 Sum = 64
Question:3
C Program to take input for “n” elements using an array. Pass the entire array to a function, Further print total number of +ve elements in the array.
Sol:
#include<stdio.h> void show(int a[],int n) { int i,p=0; for(i=0;i<n;i++) { printf("%d\n",a[i]); if(a[i]>0) p++; } printf("Total +ve elements = %d\n",p); } int main() { int a[50],i,n; printf("Enter total elements "); scanf("%d",&n); /* input */ for(i=0;i<n;i++) { printf("Enter element "); scanf("%d",&a[i]); } /* to display elements */ show(a,n); return(0); }
/* Output */ Enter total elements 5 Enter element 10 Enter element -96 Enter element -3 Enter element 5 Enter element 97 10 -96 -3 5 97 Total +ve elements = 3