|
-
April 27th, 2006, 10:50 PM
#1
Need help with arrays
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];
}
}
-
April 28th, 2006, 12:24 AM
#2
Re: Need help with arrays
How about this
Code:
#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];
}
}
Appreciate others by rating good posts
"Only buy something that you'd be perfectly happy to hold if the market shut down for 10 years." - Warren Buffett
-
April 28th, 2006, 12:38 AM
#3
Re: Need help with arrays
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.
-
April 28th, 2006, 12:42 AM
#4
Re: Need help with arrays
more compact version, behnood, to show u where u can save code lines
Code:
#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]);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|