I need to write a program that sums all values in an array row that the user can choose. The program sums correctly but instead of only outputting one row's sum, it sums up all of the rows up until the input row and adds them all together. I can't figure out whats wrong with it.
Thanks in advance

#include <iostream>
#include <cstdlib>
#include <ctime> 
using namespace std
;
int main()
{
	srand(time(0));
	int values[40][40]={0};
	int rows, columns;
	

	int alpha[] = {1,2,3,4,5,6,7,8,9};


	for (rows = 0;rows<40;rows++)
	{
		
		for(columns=0;columns<40;columns++)
		{
			values[rows][columns] = alpha[rand()%9];
			cout<<" "<<values[rows][columns];
		}
		cout<<endl;
	}


	int sumnumber,j,answer=0;
	

	cout<<"Which row would you like to sum? (0-39)\n"; cin>>sumnumber;
		
	for(rows = 0; rows < sumnumber; rows++) 
	{
		for(columns=0;columns<40;columns++)
		{
			answer += values[rows][columns];
		}

	}

	cout<<answer;

}

The code is doing exactly what you have asked it to do.

Your for loop on line 33 is the culprit.

Remove the for loop and use

answer += values[sumnumber][columns];

on line 37. (retain the inner loop)

The program sums correctly but instead of only outputting one row's sum, it sums up all of the rows up until the input row and adds them all together.

This appears to be your problem:

cout<<"Which row would you like to sum? (0-39)\n"; cin>>sumnumber;
		
for(rows = 0; rows < sumnumber; rows++) 
{
	for(columns=0;columns<40;columns++)
	{
		answer += values[rows][columns];
	}
}

cout<<answer;

It does exactly what you say it does... starts at row 0 and goes to row sumnumber - 1 , summing everything along the way. Once you have sumnumber , you don't need to spin over all the rows; you know which row you need to sum:

cout<<"Which row would you like to sum? (0-39)\n"; cin>>sumnumber;
		
for(columns=0;columns<40;columns++)
{
	answer += values[sumnumber][columns];
}

cout<<answer;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.