c++ calculations in the nested for loop - c++

I've been trying to do this program but I'm stuck, I'm still a beginner, any help would be appreciated.
I need the program to do
Print a 10 X 10 table in which each entry in the table is the sum of the row and column number
Include an accumulator that will calculate the sum of all the table entries.
what I'm having a problem with is when I try to calculate the row and column for each entry and the total sum.
Each time I put any calculation in the nested for loop it messes up. Here's with no calculations:
Here's with the calculations:
The code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// r= row, c= column, s= sum(row+column), ts= sum of all entries
int r, c, s = 0, ts = 0;
for (r = 1; r <= 10; r++)
{
for (c = 1; c <= 10; c++)
s = r + c; ** This one
ts = ts + s; ** and this
cout << setw(3) << c;
cout << endl;
}
cout << "the total sum of all table entries is " << ts << endl;
system("pause");
return 0;
}

Note that a loop will repeat the next statement. When you do it "without calculations", I assume you mean
for (c = 1; c <= 10; c++)
cout << setw(3) << c;
cout << endl;
Here, the first cout statement is repeated and prints out the table in your first screenshot. (Notice the indentation here which indicates what code is "inside" the for loop.)
Now when you add the calculations, you have
for (c = 1; c <= 10; c++)
s = r + c; ** This one
ts = ts + s; ** and this
cout << setw(3) << c;
cout << endl;
Even if you indent to show what you intend to repeat, the program will only repeat the statement immediately following the for loop header. In this case, you are repeating the calculation s = r + c; over and over. (Since this result is never used, the compiler most likely just throws it away.)
In order to repeat multiple statements, you need to wrap them in a "compound statement" which means using curly braces:
for (c = 1; c <= 10; c++)
{
s = r + c; ** This one
ts = ts + s; ** and this
cout << setw(3) << s;
}
cout << endl;
I also assume that you want to print out the sum of the row and column.
I strongly suggest that you always use curly braces, even when you repeat a single statement. This makes it easier to add more statements inside a loop because you don't have to remember to add the curly braces later.

I think you need to enclose the inner loop in curly brackets like so:
for (r = 1; r <= 10; r++)
{
for (c = 1; c <= 10; c++)
{
s = r + c;
ts = ts + s;
cout << setw(3) << c;
cout << endl;
}
}
Otherwise you will only run the
s = r + c;
line in the inner loop.

You need a pair of curly brackets for your for loop
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int r, c, s = 0, ts = 0; // r= row, c= column, s= sum(row+column), ts= sum of all entries
for (r = 1; r <= 10; r++)
{
for (c = 1; c <= 10; c++) { // <- was missing
s = r + c; ** This one
ts = ts + s; ** and this
cout << setw(3) << c;
cout << endl;
} // <- was missing
}
cout << "the total sum of all table entries is " << ts << endl;
system("pause");
return 0;
}
Without the {}, only s = r + c will be considered part of the for loop.
Incidentally this is the cause of the goto fail bugs: http://martinfowler.com/articles/testing-culture.html

Related

nested looping C++

i want to asking this problem.
this output is the expected output
*
*#
*#%
*#%*
*#%*#
*#%*#%
and this is my solution
#include <iostream>
using namespace std;
int main(){
int a,b,n;
cout << "Input the row";
cin >> n;
for (a = 1; a <= n; a++){
for(b = 1; b <= a; b++){
if (b == 1 || b == 1 + 3){
cout << "*";
}
if (b ==2 || b == 2 + 3){
cout << "#";
}
if (b ==3 || b == 3 + 3){
cout << "%";
}
}
cout << endl;
}
}
this solution is only work if the n = 6. what should i do if i want this work in every row when user input the row to the n
thank you in advance.
Here, I tried using the modulo "%" on your if's
#include <iostream>
using namespace std;
int main(){
int a,b,n;
cout << "Input the row";
cin >> n;
for (a = 1; a <= n; a++){
for(b = 1; b <= a; b++){
// After every first digits will cout #
if (b % 3 == 2){
cout << "#";
}
// The first after the third digit will cout *
if (b % 3 == 1){
cout << "*";
}
// The third digit after the second digit will cout %
if (b % 3 == 0){
cout << "%";
}
}
cout << endl;
}
}
To make your solution work for any value of n, you can use the modulo operator % to check whether a given value of b is the first, second, or third element of each row.
Here is one way you could modify your code to do this:
#include <iostream>
using namespace std;
int main() {
int a, b, n;
cout << "Input the row: ";
cin >> n;
for (a = 1; a <= n; a++) {
for (b = 1; b <= a; b++) {
// Use the modulo operator to check whether b is the first, second, or third element of each row
if (b % 3 == 1) {
cout << "*";
} else {
if (b % 3 == 2) {
cout << "#";
} else {
cout << "%";
}
}
}
cout << endl;
}
return 0;
}
With this change, the code will output the correct pattern for any value of n.
Just adding a nice optimisation (note: C++ loops naturally go up from 0 to not including n, i.e. for(int i = 0; i < n; ++i) – this is especially relevant if you are indexing arrays which have a first index of 0 and last of n - 1, while n already is invalid!).
While you do use b % 3 to decide which character and you indeed can use this by chaining if(){} else if(){} else{} (where a switch() { case: case: default: } actually would have been preferrable) you can have a much more compact version as follows (and even more efficient as it avoids conditional branching):
for(int b = 0; b < a; ++b)
{
std::cout << "*#%"[b % 3];
}
The C-string literal "*#%" actually represents an array of char with length four (including the terminating null character) – and you can index it just like any other array you have explicitly defined (like int n[SOME_LIMIT]; n[7] = 1210;)...

Need to pass 2D array to function and find sum of row c++

So I need to create a function to find the sum of rows in my 2D array. Array is fixed, matrix[5][5], and user inputs 25 integers.
I know how to find the sum of my rows using the following code:
//for sake of ease lets say user inputs numbers 1-25
for (r = 0; r < 5; r++)
{
for (c = 0; c < 5; c++)
{
sum = sum + matrix[r][c]
}
cout << "\n" << sum;
sum = 0;
}
//the code above will display the sum of each row as follows:
15
40
65
90
115
I want to display the totals for each row as
Row 1:
Sum =
Row 2:
Sum =
etc...
How do I pass the array to a function in order to find the sum of each row and how do I separate the individual sum of rows to display like I want?
I have read a chapter on passing multidimensional arrays to functions like 4 times over in a c++ beginners book, I have read and looked at many different forums online and maybe it is because I have been starring at it for too long I am not seeing the answer but I have given myself a headache. I really just want to understand how to pass it. I have tried to modify the passing of an array to a function to find the sum of all the integers in the array but I could not get it to work for what I needed.
ETA(10/7/2017 1535 PCT):
So I am trying the following to try and pass my 2D array to a function and calculate the sum...
void total(int matrix[][5], int n, int m)
{ // I am getting an error here though that states "expected a ';' "
for (r = 0; r < n; r++)
{
int sum = 0;
for (c = 0; c < m; c++)
sum += matrix[r][c];
}
cout << "Row " << r << " = " << sum << endl;
}
Is this even how you create a function with a 2D array?
ETA (10/7/2017 2100 PCT)
So I think I figured out how to pass the array, but I cannot seem to get it to do the proper math, meaning this does not sum up the rows....
#include "stdafx.h"
#include "iostream"
using namespace std;
int total( const int [][5], int, int);
int main()
{
int c, r, matrix[5][5];
cout << "Please input any 25 numbers you'd like, seperated by a space, then press enter:" << endl;
for (r = 0; r < 5; r++)
{
for (c = 0; c < 5; c++)
{
cin >> matrix[r][c];
}
}
getchar();
cout << endl << "Matrix: " << endl;
for (r = 0; r < 5; r++)
{
cout << endl;
for (c = 0; c < 5; c++)
{
cout << matrix[r][c] << "\t";
}
cout << endl;
}
cout << "Please press the enter key to get the sums of each row << endl;
getchar();
cout << "Sum = " << total << endl; //this displays "Sum = 013513F2"
system("PAUSE");
}
int total(const int matrix[][5], int R, int C)
{
int sum = 0;
for (int r = 0; r < R; r++)
{
for (int c = 0; c < C; c++)
{
sum = sum + matrix[r][c];
}
}
return sum;
}
Passing an array of any dimension can be done by using the syntax: type (&name)[numElements] by reference. Or by pointer you would replace the & with a *. Below is a basic example that compiles, which passes the array by reference to the pass2Darray function. Alternatively, you could simply use a regular array with size [5 * 5] to ensure that it's entirely contiguous. Since a 2D array is not natively something that exists in C++. And then, since you're working with matrices, you can access it in column major by [row * i + col] or in row major by [col * j + row].
#include <iostream>
// Reference to multiArray
// int (&someName)[num][num]
// Pointer to multiArray
// int (*someName)[num][num]
void pass2Darray(int (&passed)[1][1]) {
std::cout << passed[0][0];
}
int main() {
int arr[1][1] = { {1} };
pass2Darray(arr);
return 0;
}
Just to help the future readers this is what I came up with. Took a lot of research and a million different trial and errors but here it is:
int math(int a[5]) //The function the array has been passed to
{
//Declaring the variables in the function
int sum = 0;
double average = 0;
int min = 0;
int max = 0;
min = a[0]; //setting the minimum value to compare to
for (int C = 0; C < 5; C++) //Creates the loop to go through the row elements
{
sum = sum + a[C]; // calculates the sum of each row
if (a[C] < min) min = a[C]; //assigns the element of lowest value from row
if (a[C] > max) max = a[C]; //assigns the element of highest value from row
}
average = sum / 5; //calculates the average of each row
cout << "Sum = " << sum << endl; //Outputs sum
cout << "Average = " << average << endl; //Outputs average
cout << "Min = " << min << endl; //Outputs min
cout << "Max = " << max << endl; //Oututs max
cout << endl;
return 0; //return value for function
}
Down the line that calls the function and displays the output I was looking for:
for (r = 0; r < 5; r++) //sets up row loop for display
{
cout << "Row " << r+1 << ":" << endl;
math(matrix[r]); //displays calculations done in math function
cout << endl;
}
Hope this helps someone down the road...

Creating a Table of Powers with C++

I'm working on a project to print out a table of exponential numbers using nested for-loops. Users specify the number of rows to print and the number of powers. For example, if the users specifies 2 rows and 3 powers, the program should print 1,1,1 and 2,4,9 (2^1,2,3 etc). I should note this is for class and we aren't allowed to use cmath, otherwise I would use pow(). I can't seem to figure out the correct function in a nested for loop that can change both values of the base and the exponent. Here's what I have so far. Thanks for your help!
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.\nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
for (int q = 1; q <= i; q++)
{
a = (q * q); //This only works for static numbers...
cout << setw(8) << a;
}
cout << endl;
}
}
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
int a = 1;
for (int q = 1; q <= r; q++)
{
a = (a * i);
cout << setw(8) << a;
}
cout << endl;
}
Several things to note. First, you can compute the powers by maintaining the variable a and multiplying it by i for each power. Also, I think you want the upper bound on your second loop to be r and not i.
You need couple to change the way accumulate the values of raising a number to a power.
Also, you are using the wrong variable to end the loop in the inner for-loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.\nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
a = 1; // Start with 1
for (int q = 1; q <= p; q++) // That needs to <= p, not <= i
{
a *= i; // Multiply it by i get the value of i^q
cout << setw(8) << a;
}
cout << endl;
}
}

Convert integers to characters [duplicate]

This question already has answers here:
How to convert a number to string and vice versa in C++
(5 answers)
Closed 9 years ago.
I am trying to get my program to print letters instead of numbers. I used char c = static_cast<char>(N); to attempt to do this but it wont work, instead it prints character images that are not (a-z) How can I get the numbers to be printed as letters?
#include <cstdlib>
#include <iostream>
using namespace std;
// Function getUserInput obtains an integer input value from the user.
// This function performs no error checking of user input.
int getUserInput()
{
int N(0);
cout << endl << "Please enter a positive, odd integer value, between (1-51): ";
cin >> N;
if (N < 1 || N > 51 || N % 2 == 0)
{
cout << "Error value is invalid!" << "\n";
cout << endl << "Please enter a positive, odd integer value, between (1-51): ";
cin >> N;
system("cls");
}
cout << endl;
return N;
} // end getUserInput function
// Function printDiamond prints a diamond comprised of N rows of asterisks.
// This function assumes that N is a positive, odd integer.
void printHourglass(int N)
{
char c = static_cast<char>(N);
for (int row = (N / 2); row >= 1; row--)
{
for (int spaceCount = 1; spaceCount <= (N / 2 + 1 - row); spaceCount++)
cout << ' ';
for (int column = 1; column <= (2 * row - 1); column++)
cout << c;
cout << endl;
} // end for loop
// print top ~half of the diamond ...
for (int row = 1; row <= (N / 2 + 1); row++)
{
for (int spaceCount = 1; spaceCount <= (N / 2 + 1 - row); spaceCount++)
cout << ' ';
for (int column = 1; column <= (2 * row - 1); column++)
cout << c;
cout << endl;
} // end for loop
// print bottom ~half of the diamond ...
return;
} // end printDiamond function
int main()
{
int N = 1;
while (N == 1)
{
printHourglass(getUserInput());
cout << endl;
cout << "Would you like to print another hourglass? ( 1 = Yes, 0 = No ):";
cin >> N;
}
} // end main function
The letters are not numbered with A starting at 1 or anything like that. You're likely on an ASCII/UTF-8 system. So, in printHourglass, replace cout << N with
cout << static_cast<char>('A' + count - 1);
C functions, itoa
C++, using stringstream
boost::lexical_cast
Actually for your case, you can directly print it out. cout << N

Is there a way to observe values of variables in each iteration?

I'm new to learning how to code and I was wondering if there's a way to see values during each iteration of a loop. Here's a code I'm trying to understand. I know some of it but as it gets deeper, I get confused.
#include <iostream>
#include <string>
using std::cin; using std::endl;
using std::cout; using std::string;
int main()
{
cout << "Please enter your first name: ";
string name = "Jae";
const string greeting = "Hello, " + name + "!";
const int pad = 1;
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
cout << endl;
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
while (c != cols) {
if (r == pad + 1 && c == pad + 1) {
cout << greeting;
c += greeting.size();
} else {
if (r == 0 || r == rows - 1 ||
c == 0 || c == cols - 1)
cout << "*";
else
cout << " ";
++c;
}
}
cout << endl;
}
}
You can debug your code. If you debug, you can see values during each iteration of a loop
if r is your iterator, write inside the loop this line:
cout << r;
Google is your friend.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide
Simply you can execute your program line-by-line by pressing F10 key. And hovering mouse over variables shows their current value.