trouble with for loop printing data(arrays)

hey

im making a program that has two arrays. This program takes input from user and puts into the arrays using for statements. After all numbers entered its suppose to add them together and print that using another for statement... the program compiles but has runtime/semantic errors.

ps: using g++ compiler from terminal and also using terminal editor utility
here is the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int a[5];
int b[5];

int main()
{
int q = 4;
int bb=4;
int i;
for ( i = 0; i <=q; i++) 
{
for(int d = 0; d<=bb; d++)
{ 
cout << "enter a number:";
cin >> b[d];
cout << "enter a number:";
cin >> a[i];
}
}

for (int c=0; c<=q; i++)
{
for (int o=0; c<=bb; o++)
{
cout << a[c] + b[o] << endl;
}
}
return 0;
}

your problem statement is ambiguous, however it is still clear there are code bugs.

To paraphrase your code:


for every integer I in [ 0..4 ], do the following:
for every integer D in [ 0..4 ], do the following:
read a number into b[ D ]
read a number into a[ I ]


How many times do you read into a[ I ]?

Then look at your loops on 23-29, as it does a similar thing.
You're using nested for loops for both input and output.

By nesting them, they will scan for input and then output 25 times. Perhaps you have wanted to use a 2D array instead of 2 separate arrays?

Can you define your problem more clearly? What do you mean by add them together? Do you mean summation of all elements in each array, or summing corresponding elements in the 2 arrays to form a 3rd array?
i wanted to ask user to give numbers and array 1[0] adds with array2[0]

kinda like adding matrix in algebra class...
Then you only need 1 for loop each for input and then output

1
2
3
4
5
6
7
8
9
for(i=0;i<arrayLength;i++)
{
     cin >> a[i] >> b[i];
}

for(j=0;j<arrayLength;j++)
{
     cout << a[i]+b[i] << endl;
}
alright thanks guys

problem was solved
Topic archived. No new replies allowed.