Answer the question
In order to leave comments, you need to log in
Fill a two-dimensional array with random numbers and print their sum?
Hello everyone, I played tricks here with the "program". The task was as follows: given a two-dimensional array 3x3, fill it with random and calculate the sum of all elements of the array. I wrote something, but in my opinion it does not work correctly. Can you please tell me where is the mistake?
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
#include "iostream"
#include "conio.h"
#include "ctime"
using namespace std;
void main()
{
int mas[3][3];
int i, j, sum;
srand(time(NULL));
sum = 0;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
mas[i][j] = 0 + rand();
sum = sum + mas[i][j];
}
}
cout << mas[i][j] << endl;
cout << sum << endl;
_getch();
}
Answer the question
In order to leave comments, you need to log in
wrong here is
cout << mas[i][j] << endl;
it needs to be inserted inside the cycle for j
otherwise it looks normal.
it is not very clear why add 0
If you are talking about the fact that negative amounts can be displayed, it is because of the overflow when it rand()
generates large numbers. For beauty, you can generate numbers up to one hundred, for example.
#include <iostream>
using namespace std;
int main()
{
int mas[3][3];
int i, j, sum;
srand(time(NULL));
sum = 0;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
mas[i][j] = rand() % 100;
sum = sum + mas[i][j];
cout << mas[i][j] << "\t";
}
cout << endl;
}
cout << "sum: " << sum << endl;
cin.get();
}
$ g++ -pedantic -Wall -Wextra test.c
$ ./a.out
97 40 3
32 81 26
30 15 6
sum: 330
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question