2.1 Assume that s and n have been declared as integers. Explain in words what the purpose of the following segment of code is: (2)
int s = 0;
int n = 0; while (n <= 5)
{
s = s + n;
n++;
}
2.2 Explain the purpose of the following segment of code: (2)
int numbers[ ] = {11, 0, 15, 0, 16, 23};
int c = 0;
for (int i = 0; i <= 5; i++)
if (numbers[i] != 0)
c += 1;
#include<iostream>
using namespace std;
int main()
{
//a)
int s = 0;
int n = 0;
//Purpose of this code is increasing incrementing
//After every iteration s increases by 1..2..3..4..5
while (n <= 5)
{
s = s + n;
n++;
cout << "n= "<< n<< " s= " << s<< endl;
}
//b)
int numbers[] = { 11, 0, 15, 0, 16, 23 };
int c = 0;
//Purpose of this code is count of nonzero elements in an array
for (int i = 0; i <= 5; i++)
if (numbers[i] != 0)
c += 1;
cout << "The number of nonzero c = "<<c;
}
Comments
Leave a comment