sum of an array

Mar 26, 2010 at 3:15am
I have made this small program to help me add numbers and find the sum, it runs but no output.what could be the problem?
// Program that uses a switch statement

# include<iostream>
using namespace std;
//const int values = 30;
int main ()
{
int sum, i ;
int num[5];

cout << "Please enter 5 numbers to get the sum \n";
cin >> num[0] >>num[1] >>num[2] >> num[3] >>num[4];

sum = num[0] + num[i];

while (i<5)
{
cout << "The sum is:" << sum << endl ;
if (sum < num[i]) sum = num[i];
i++;
}
system ("pause");
return 0;
}
Mar 26, 2010 at 3:25am
i is uninitialized (and just so happens to have a value that is not less than 5, so
the while loop never runs.

But your logic is way messed up...
Mar 26, 2010 at 3:33am
/* your logic is really messed up man..u need to know how to operate an array in looping..some more..why u need to use switch for sum??is not u should only sum in some condition?

# include<iostream>
using namespace std;
//const int values = 30;

int main ()
{
int sum=0;
int num[5];

cout << "Please enter 5 numbers to get the sum \n";

for (int i=0; i<5; i++)
{
cin >> num[i];
}

int j=0;
while (j<5)
{
sum += num[j];
j++;
}

cout << "Sum : " << sum;
system ("pause");
return 0;
}
Mar 26, 2010 at 3:57am
closed account (1yR4jE8b)
@EAStudent
Please don't ever use system() ever again, and don't ever tell anyone to use it. System is EVIL. If your IDE is too dumb to keep the command line window before you can see the output, you should probably use cin.get() instead of calling the system function.

and why are you using a while loop? You're just basically immitating a for loop anway

1
2
3
4
for(int j = 0; j < 5; ++j)
{
     sum += num[j];
} 
Mar 26, 2010 at 5:33am
This code looks perfect, but still no output!

# include<iostream>
using namespace std;
//const int values = 30;

int main ()
{
int sum=0;
int num[5];

cout << "Please enter 5 numbers to get the sum \n";

for (int i=0; i<5; i++)
{
cin >> num[i];
}

int j=0;
while (j<5)
{
sum += num[j];
j++;
}

cout << "Sum : " << sum;
system ("pause");
return 0;
}
Mar 26, 2010 at 8:19am
may be because of your console not pause..
try this code..it would stop your program until u input anything

# include<iostream>
using namespace std;
//const int values = 30;

int main ()
{
int sum=0;
int num[5];

cout << "Please enter 5 numbers to get the sum \n";

for (int i=0; i<5; i++)
{
cin >> num[i];
}

int j=0;
while (j<5)
{
sum += num[j];
j++;
}

cout << "Sum : " << sum;
cin >> sum;
return sum;
}
Mar 26, 2010 at 8:22am
@darkestfright

sorry mr darkesfright..
i just use its existing code only..
i'm not write my own..
just want to show to him.
how to do wat ever his trying to do..

thanks you bro..:)
Topic archived. No new replies allowed.