Function, Arrays, And Pointer in C++
Example:1
Take input for “n” element using an array, pass the entire array to a function and display the elements?
Sol:
#include<iostream> #include<conio.h> using namespace std; void show(int *p,int n) { int i; for(i=0;i<n;i++) { cout<<*p<<endl; p++; } } int main() { int a[20],n,i; cout<<"Enter total elements "; cin>>n; //input for(i=0;i<n;i++) { cout<<"Enter any element "; cin>>a[i]; } //display show(a,n); //show(&a[0],n); return(0); }
Output:
Enter total elements 5
Enter any element 10
Enter any element 20
Enter any element 30
Enter any element 40
Enter any element 50
10
20
30
40
50
Example:2
Take input for “n” element using an array, pass the entire array to a function and display the elements. Also, calculate and print sum of all the elements.
Sol:
#include<iostream> #include<conio.h> using namespace std; void show(int *p,int n) { int i,s=0; for(i=0;i<n;i++) { cout<<*p<<endl; s=s+*p; p++; } cout<<"Sum = "<<s<<endl; } int main() { int a[20],n,i; cout<<"Enter total elements "; cin>>n; //input for(i=0;i<n;i++) { cout<<"Enter any element "; cin>>a[i]; } //display show(a,n); //show(&a[0],n); return(0); }
Output:
Enter total elements 5
Enter any element 10
Enter any element 20
Enter any element 30
Enter any element 40
Enter any element 50
10
20
30
40
50
Sum = 150
Example:3
Take input for “n” element using an array, pass the entire array to a function and display the elements. Also, check and print total +ve and -ve elements present in the array.
Sol:
#include<iostream> #include<conio.h> using namespace std; void show(int *p,int n) { int i,po=0,ne=0; for(i=0;i<n;i++) { cout<<*p<<endl; if(*p>0) po++; if(*p<0) ne++; p++; } cout<<"Total +ve elements = "<<po<<endl; cout<<"Total -ve elements = "<<ne<<endl; } int main() { int a[20],n,i; cout<<"Enter total elements "; cin>>n; //input for(i=0;i<n;i++) { cout<<"Enter any element "; cin>>a[i]; } //display show(a,n); //show(&a[0],n); return(0); }
Output:
Enter total elements 5
Enter any element 21
Enter any element -36
Enter any element 45
Enter any element -98
Enter any element 24
21
-36
45
-98
24
Total +ve elements = 3
Total -ve elements = 2