Click to See Complete Forum and Search --> : Need help with arrays


Behnood
April 27th, 2006, 10:50 PM
I'm trying to write this program which doesn't yield the output desired.

Here's the prompt:
Write a C++ program that declares an array alpha of 50 components of the type double. Initialize the array so that the first 25 components are equal to the square of the index variable and the last 25 components are equal to three times the index variable. Then just output the array.

Here's what I have:

#include <iostream>
using namespace std;

int main(){
double alpha[50];
int counter;
int square;
int times3;
for(counter = 0; counter <= 24; counter++)
{
square = counter * counter;
square = alpha[counter];

}

for(counter = 25; counter <= 49 && counter > 24; counter++)
{
times3 = counter * 3;
times3 = alpha[counter];
}

for(counter = 0; counter <= 49; counter++)
{
cout << " ";
cout << alpha[counter];
}
}

sunnypalsingh
April 28th, 2006, 12:24 AM
How about this

#include <iostream>
using namespace std;

int main(){
double alpha[50];
int counter;
for(counter = 0; counter <= 24; counter++)
{
alpha[counter]=counter*counter;
}

for(counter = 25; counter <= 49; counter++)
{
alpha[counter]=3*counter;
}

for(counter = 0; counter <= 49; counter++)
{
cout << " ";
cout << alpha[counter];
}
}

Behnood
April 28th, 2006, 12:38 AM
Thanks! Now I see where my problem was. It was a mistake I should have learned not to make by now.

The statement

square = alpha[counter]

makes no sense. You must have alpha[counter] before the assignment statement because it's evaluated from right to left and you want square's value to be copied into the array alpha.

The same is true for several other statements in my code.

thre3dee
April 28th, 2006, 12:42 AM
more compact version, behnood, to show u where u can save code lines
#include <iostream>
using namespace std;

int main () {
double alpha[50];

// i^2
for (int i = 0; i < 25; ++i) // note the < 25 this is the same as <= 24 but the more common way
alpha[i] = i * i;

// 3*i
for (int i = 25; i < 50; ++i)
alpha[i] = i * 3;

// print
for (int i = 0; i < 50; ++i)
printf ("%d\n", alpha[i]);
}