In: Computer Science
Can someone please walk through this program for me and explain out the outputs are generated.
#include <iostream>
#include <iomanip>
using namespace std;
const int size = 5;
int fun(int arz[size], int jump)
{
int i, j = 0;
for(i = 0; i < size; i += jump)
j += arz[i];
return j;
}
main()
{
int arx[size] = {1, 2, 4, 8, 16};
int ary[size] = {10, 20, 40, 80, 160};
cout << fun(arx, 1) << endl;
cout << fun(ary, 2) << endl;
cout << fun(arx, 3) << endl;
cout << fun(ary, 4) << endl;
cout << fun(arx, 5) << endl;
cout << fun(ary, 6) << endl;
} // main
//header files
#include <iostream>
#include <iomanip>
using namespace std;
//constant size having value 5
const int size = 5;
//function fun accepting array and an integer as an argument
int fun(int arz[size], int jump)
{
//set i, j to 0
int i, j = 0;
//loop in which i go from 0 to size-1 incrementing by jump
for(i = 0; i < size; i += jump)
j += arz[i];//add arr[i] to j and store back in j
//return j
return j;
}
//main function
main()
{
//array arx and ary both having 5 elements in it
int arx[size] = {1, 2, 4, 8, 16};
int ary[size] = {10, 20, 40, 80, 160};
//calling fun by passing arx and 1
cout << fun(arx, 1) << endl;
//calling fun by passing ary and 2
cout << fun(ary, 2) << endl;
//calling fun by passing arx and 3
cout << fun(arx, 3) << endl;
//calling fun by passing ary and 4
cout << fun(ary, 4) << endl;
//calling fun by passing arx and 5
cout << fun(arx, 5) << endl;
//calling fun by passing ary and 6
cout << fun(ary, 6) << endl;
} // main