Need Quick Help
hi guys could any one please solve this problem for me because it is urgent
find and display the sum of all the values,
which are ending with 2 (i.e., units place is 2). in an array of given size(two dimensional)
Here are some hints.
You need two loops to iterate through the matrix, in the form:
1 2
|
for(int i=0; i < row; i++)
for(int j=0; j < column; j++)
|
You can access each element via
You can get the last digit of a number via
You can compare that number with 2 by using the == operator for instance
|
myNumber == anotherNumber
|
The result is best stored in a vector, as you may have more than one number that ends with 2:
1 2 3
|
#include <vector>
...
std::vector v;
|
You take the sum of all numbers by iterating through the vector and adding all values to sum
1 2 3
|
int sum = 0;
for(int i=0; i < v.size(); i++)
...
|
Edit: Even better, just leave out the vector and add the value to the sum right after you've checked that it ends with two.
Last edited on
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
|
#include <iostream>
#include <stdlib.h>
#include <ctime>
using namespace std;
int main()
{
const int row = 5, col = 5;
int sum = 0;
srand(static_cast <unsigned int> (time(0))); //seed using current time as non-negative int
int array[row][col];
//random data in array
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
array[i][j] = rand() % 500 + 1; //numbers 1 - 500
//search array
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
if(array[i][j] % 10 == 2) //find numbers that end with 2
{
sum += array[i][j];
cout << array[i][j] << endl;
}
cout << "-----\nSum = " << sum << endl;
return 0;
}
|
Thank you that solved my problem
Topic archived. No new replies allowed.