x[i] = i( i=0, 99 ) please help

Hello there,

Because my lab instructor is so annoying and he absolutely explains nothing.. Can I get help with this:

Question 1: One-dimensional Array

Write a program lab6.cpp. Below is a skeleton for lab6.cpp. There are two for loops: the first one is to set up the values for each array element by using the formula x[i]=i (i=0,99), and the second loop is to compute the sum of all array elements.




#include <iostream>
using namespace std;

int main()
{

int x[100], sum=0;



//the first for loop to set up each array element by using the above formula

/* TO BE FILLED IN */



//the second for loop to compute the sum of all array elements and store it in sum

/* TO BE FILLED IN */


cout << “Sum of all array elements is ” << sum << endl ;

system( “pause”);
return 0;
}

can anyone explain this to me please?


Regards,
Said
Looks like you just need a breakdown of for loops.

Check the section on for loops on this page:

http://cplusplus.com/doc/tutorial/control/
What is a breakddown of for loops?
Read the section of the tutorial Disch posted, about for loops.

Your problem involves for loops as well as an array. I would read the section on arrays as well, if you aren't already familiar with them: http://cplusplus.com/doc/tutorial/arrays/

The loop structure is like this:
1
2
for (initialization; condition; increase) 
{ ... statements to happen if condition is true .... }


Initialization is where you define and set a value for your increment variable. (i.e... int i = 0; )

Condition is where you set a conditional statement that, if determined to be true, will allow everything inside the body of the for loop to repeat until that conditional is false.

Increase is where you can increment or decrement your increment variable by one, for every iteration of the loop. (i.e... i++, ++i, i--, or --i) This will allow your for loop to be eventually false, avoiding an infinite loop in your program.

So you would want to have something like this for your for loop:
1
2
3
4
5
//the first for loop to set up each array element by using the above formula
for (int i=0; i<100;i++){
	x[i] = i;
	sum += x[i];
}


Really I don't see the point in creating a second, additional for loop. The one can handle both of your problems.

But for your sake, since some teachers want to see you practicing new concepts, you could use the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int main()
{
int x[100];
int sum = 0;

//the first for loop to set up each array element by using the above formula
for (int i=0; i<100;i++){
	x[i] = i;
}

//the second for loop to compute the sum of all array elements and store it in sum
for (int i=0; i<100; i++)
	sum += x[i];

cout << "Sum of all array elements is: " << sum << endl ;

system( "PAUSE");
return 0;
}
Last edited on
Thank you so much for explaining.
Topic archived. No new replies allowed.