Here are C++ programs to increment all array elements by n and print the resultant array. In first program to increment all array elements by n we have used for-loop, and in second program we have used operator overloading.
C++ programs to increment all array elements by n and print the resultant array
#include<iostream>
using namespace std;
int main()
{
int a[20],num,n;
cout<<"How many elements to be stored (max 20) : ";
cin>>num;
cout<<"Enter elements of array : ";
for(int i=0;i<num;i++)
cin>>a[i];
cout<<"Enter value of n : ";
cin>>n;
cout<<"After incrementing all element in array by "<<n<<" : ";
for(int i=0;i<num;i++)
{
a[i]=a[i]+n;
cout<<a[i]<<" ";
}
return 0;
}
using namespace std;
int main()
{
int a[20],num,n;
cout<<"How many elements to be stored (max 20) : ";
cin>>num;
cout<<"Enter elements of array : ";
for(int i=0;i<num;i++)
cin>>a[i];
cout<<"Enter value of n : ";
cin>>n;
cout<<"After incrementing all element in array by "<<n<<" : ";
for(int i=0;i<num;i++)
{
a[i]=a[i]+n;
cout<<a[i]<<" ";
}
return 0;
}
C++ programs to increment all array elements by n using operator overloading
#include<iostream>
using namespace std;
int num;
struct add
{
int ar[20];
};
add operator+(add &a1,int n)
{
add a2;
for(int i=0;i<num;i++)
a2.ar[i]=a1.ar[i]+n;
return a2;
}
int main()
{
add a1,a2;
int n;
cout<<"How many elements to be stored (max 20) : ";
cin>>num;
cout<<"Enter elements of array : ";
for(int i=0;i<num;i++)
cin>>a1.ar[i];
cout<<"Enter value of n : ";
cin>>n;
a2=a1+n;
cout<<"After incrementing all element in array by "<<n<<" : ";
for(int i=0;i<num;i++)
cout<<a2.ar[i]<<" ";
return 0;
}
using namespace std;
int num;
struct add
{
int ar[20];
};
add operator+(add &a1,int n)
{
add a2;
for(int i=0;i<num;i++)
a2.ar[i]=a1.ar[i]+n;
return a2;
}
int main()
{
add a1,a2;
int n;
cout<<"How many elements to be stored (max 20) : ";
cin>>num;
cout<<"Enter elements of array : ";
for(int i=0;i<num;i++)
cin>>a1.ar[i];
cout<<"Enter value of n : ";
cin>>n;
a2=a1+n;
cout<<"After incrementing all element in array by "<<n<<" : ";
for(int i=0;i<num;i++)
cout<<a2.ar[i]<<" ";
return 0;
}
thanks so much.
ReplyDelete