MTC-101 Lab Assignment 5 Solution
Please use the concept of Arrays, functions and loops to work out the
following C++ programs.
1. Write a C++ program using an array to calculate the value of the sum of
100 natural numbers in the series: 1+2+3+....+100.
Solution:
#include <iostream>
using namespace std;
int main()
{
int num[100];
int sum = 0;
for(int i = 0; i<100; i++)
{
// the series start from 1, but loop starts from 0 as the first array index is zero
num[i] = i+1;
sum += num[i];
}
cout << sum << endl;
return 0;
}
2. Write a C++ program using a function to calculate the average of the
sum of 100 natural numbers in the series: 1+2+3+....+100. (Hint: Passing
Arrays to Functions)
Solution:
#include <iostream>
using namespace std;
int average(int num[], int size);
// Passing Arrays to Functions
int average(int num[], int size)
{
int sum = 0;
double average;
for(int i = 0; i<100; i++)
{
sum += num[i];
}
average = sum/size;
return average;
}
int main()
{
int num[100];
for(int i = 0; i<100; i++)
{
num[i] = i+1;
}
cout << average(num, 100) << endl;
return 0;
}
3. Write a C++ program to define a 2-dimensional array with 10 rows and
10 columns where the value of each element is given by the product of
the indices.
Solution:
#include <iostream>
using namespace std;
#define num_row 10
#define num_column 10
int main()
{
int num[num_row][num_column];
for(int i=0;i<num_row;i++)
{
for(int j=0;j<num_column;j++)
{
num[i][j] = i*j;
cout << i << " * " << j << " = " << num[i][j] << endl;
}
}
return 0;
}
4. Write a C++ program that will read the strings “Merry Christmas.” and
“Happy New Year 2023.” from the user prompt and Concatenate them
using <cstring> class.
Solution:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[100];
char str2[100];
cout << "enter string 1:" << endl;
// It can read spaces in your input string.
cin.getline(str1, sizeof(str1));
cout << "enter string 2:" << endl;
cin.getline(str2, sizeof(str2));
cout << strcat(str1,str2) << endl;
return 0;
}