I am trying to write a program that declares an array (alpha) of 50 components of type double. The first 25 components should be equal to the square of the index variable and the last 25 components should be equal to three times the index variable. 10 elements should be printed per line. Did I do this correctly?
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
int main()
{
double alpha[50];
int i;
for (i = 0; i < 25; i++)
{
alpha[i] = i^2; //sets first 25 components of array equal to the square of the index
}
for (i = 0; i > 24; i++)
{
alpha[i] = i*3; //sets last 25 components of array equal to three times the index
}
for (i = 0; i < 50; i++) //for every array component under 50,
{
cout << alpha[i] << alpha[i] << alpha[i] << alpha[i] << alpha[i] << alpha[i] << alpha[i] << alpha[i] << alpha[i] << alpha[i] << endl; //outputs 10 elements per line
}
system("pause"); //keeps program open
}
2nd loop: Not good. You're setting 25-49, however you are not setting the right value. For loops do not have to start at 0. You should start at 25 & use < 50 as your end value. Also, you will never enter the body of the loop because i = 0 is not >= 25.
3rd loop: This is quite a mess. You're going to be printing all 50 elements 50 times. If you really want the loop, you need to change the body. If you don't want the loop, the body is perfect. For the third loop, try printing element i each time. Then, check if i is the tenth element, outputting endl if it is.
Line 16: The '^' operator is for XOR, not exponentiation.
Line 19: This loop will exit immediately because the i >= 25 test fails right away.
In the second loop, use the loop counter as the index. You don't need that 'x' variable. You don't have to start 'for' loops with the loop counter as zero. There's nothing wrong with doing this:
1 2 3 4 5 6 7 8 9
for (int i = 0; i < 25; i++)
{
alpha[i] = i * i; //index squared
}
for (int i = 25; i < 50; i++)
{
alpha[i] = i * 3; //index times 3
}
Oops did not look to carefully lol had some mistakes anyways
The for statement is as follows
start;end;increment
Again in your last loop you are still outputting all values 50 times
for (i = 0; i < 50; i++)
do what is between { } 50 times, the key here is to combine the alpha variable with the loop variable.
Now if you really want to impress your teacher you could approach this using only one loop and check if the loop counter is greater than 24 and perform another action then print this all
using 1 for statement.
Understanding of coding foundations is mandatory in debugging most simple issues like these,