C++: How to print a multiplication table using nested loop? - c++

I am running a program in c++ which prints the multiplication table from 1 to 40 but it starts from 13*10=130 to 40 so whats the reason behind this?

Below is the formatted version of the code you posted:
#include<iostream>
using namespace std;
int main() {
for (int i = 1; i <= 40; i++) {
for (int j = 1; j <= 10; j++) {
cout << i << " * " << j << " = " << i*j << endl;
}
cout << endl;
}
return 0;
}
It starts printing at 13 * 10. What's the reason for this?
Notably, we can see the variables of both loops (i and j) are initialized to 1 when the loop starts. Because of this, you would be right in expecting the first loop-through to print 1 * 1 = 1.
This suggests, as PRIME has pointed out, that the environment (such as the Windows Console) that you are printing to may not have a large enough buffer to store and display the 440 lines of output the program will try to print.
How can I get around this?
You can try re-sizing your printing environment's internal buffer (if it allows) to allow for 440 lines of print. In MS-DOS, for example, you can manually change this by right-clicking the title-bar, going into Properties, then the Layout tab, and changing the Screen Buffer width and height to values that suit.
Alternatively, you could conserve print-space by replacing endl statements with regular spaces, a la:
for (int i = 1; i <= 40; i++) {
for (int j = 1; j <= 10; j++)
cout << i << " * " << j << " = " << i*j << ' ';
}
You also have the option of outputting to a file instead of your current printing environment:
#include <fstream>
using namespace std;
int main() {
ofstream Output("Output.txt"); //Creates a file "Output.txt"
if (Output.is_open()) { //If the file is open, proceeed
for (int i = 1; i <= 40; i++) {
for (int j = 1; j <= 10; j++)
Output << i << " * " << j << " = " << i*j << '\n';
Output << '\n'; //^^^Write multiplication table to the file
}
}
return 0;
}

Related

How can I print 2D arrays with four columns

I am struggling with printing an array with 4 rows and 4 columns, when I initialized the array and entered all the values. Then, I used for loop to get all the values together so I can print them. But I get is an array that companied all the values in one row.
I have attached the output when I run the code.
Here is a portion of my code, it is long code but I am struggling in specific part:
#include <iostream>
using namespace std;
int main()
{
cout << "The martix before I flipped it: " << endl;
cout << endl;
int array[4][4] = { 16,3,2,13,5,10,11,8,9,6,7,12,4,5,14,1 };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << array[i][j] << " ";
}
}
return 0;
The standard output utility std::cout is a stream from the stl and, as such, its << operator does not usually automagically append a linebreak.
Which is quite practical since, otherwise, you would not be able to print multiple numbers on a single line.
That being, said, you'll need to add the linebreak manually, like so :
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
Alternatively, you can consider printing lines 4 at a time since your matrix is of constant size :
for (int i = 0; i < 4; i++) {
std::cout << array[i][0] << " "
<< array[i][1] << " "
<< array[i][2] << " "
<< array[i][3] << " " << std::endl;
}
Have a great day,

How to call a function to search an element an a 2D array?

I'm trying to get my homework done, but there is something is going wrong.
If a 2D array was in the main function, and I want to call a function, which its task is searching for an element in the 2D array, which the user enters the wanted element in the main function. If the wanted element was found, call a function to find its factorial then print the result in the main function, otherwise, call another function to show that the wanted element was not found.
I've tried the lines of code using Visual Studio 2019 as well as Dev C++.
My program does about 13 tasks which I organized them in a Switch Statement,
and the case of doing that task is Case number 9.
But once I enter the element I want to search in the console.
if the element existed in the array, the output always shows up like this:
"
Number 3 Found at position: 4
Factorial of 3 is: 6
3
"
whether the user entered 3 or else number.
Even if it was not found, the output is the same.
#include <iostream>
using namespace std;
// declaring a function to search within B1 array.
int search_B1(int[][3], int, int);
// declaring a function to find the fatorial of the found element.
int fact_num(int);
// declaring a function to print out a searching error.
void search_error();
// This is the main function. Program execution begins and ends here.
int main()
{
int B1[3][3], i, j;
cout << " - Please enter the elements of B1 array: \n";
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
cout << "B1[" << i << "]" << "[" << j << "] = ";
cin >> B1[i][j];
}
}
...
...
...
case 9:
{
int num;
cout << endl << " Enter the element to search in B1 array: ";
cin >> num;
cout << endl << search_B1(B1, 3, num) << endl;
break;
}
}
/**********************************************************************/
// This function is called when user inserts '9'
int search_B1(int B1[][3], int num , int)
{
int i, j, flag = 0;
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
if (num == B1[i][j])
{
flag = 1;
cout << " Number " << num << " Found at position: " << j + 1 << endl;
fact_num(num);
break;
}
}
}
if (flag == 0)
{
search_error();
}
return num;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
int fact_num(int num)
{
int fact = 1, f;
for (f = 1; f <= num; f++)
{
fact *= f;
}
cout << " Factorial of " << num << " is: " << fact;
return fact;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
void search_error()
{
cout << " The wanted number was not Found in the array!";
}
/**********************************************************************/
I expected the output of searching will be like this:
Example:
If the user entered the elements of the array as '1 2 3 4 5 6 7 8 9' and searched about the element '9'
IF THE WANTED ELEMENTS WAS FOUND:
the output will be :
"Number 9 Found at position: 4
Factorial of 9 is: 362880"
IF THE WANTED ELEMENTS WAS NOT FOUND:
the output will be :
"The wanted number was not Found in the array!"
You have undefined behaviour filling and searching the array
for (i = 1; i <= 3; i++) // B[3][j] is never an element
{
for (j = 1; j <= 3; j++) // B[i][3] is never an element
Array indices start from 0. If you want to display indices from 1, do arithmetic in the output
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
std::cout << "B1[" << (i + 1) << "]" << "[" << (j + 1) << "] = ";
std::cin >> B1[i][j];
}
}

Multiplying elements in 2d array

I'm having a problem with the last row of my program. I can't figure out how to multiply the last row by the first row in my program. The multiplication table
works by multiplying the first row by the second, second by third, and so on.
int main() {
int temp;
const int row = 10;
const int col = 5;
int arr[row][col];
int arr2[10][5];
srand(((unsigned)time(0)));
cout << "Original" << endl;
for (int i = 0; i<10; i++) {
for (int j = 0; j<5; j++) {
temp = 1 + rand() % 99;
arr[i][j] = temp;
int arr2 = arr[i][j];
cout << setw(4) << arr2<< setw(5) << " | ";
}
cout << endl;
}
cout << "\n\nMultiplied rows" << endl;
for (int i = 0; i<row; i++) {
for (int j = 0; j < col; j++) {
if (i < 9)
arr[i][j] *= arr[i + 1][j];
else if (i == 9)
cout << setw(4) << arr[i][j]<< setw(5) << " | ";
}
cout << endl;
}
return 0;
}
(it's the last else statement I'm having a problem with)
i tried arr[i][j]=arr[1][i]*arr[9][j]
but that didn't work
First, the answer to your question.
You cant really multiply the last row with the first one because you overwrote it already when arr[i][j] *= arr[i + 1][j]; line executed for i = 0 and j = 0 to 9
The naive solution would be to either store the multiplied numbers in a new array, or don't overwrite the old array and just print the computed values.
Even with that, you will have to make other fixes but I am not really going to do your homework for you.
Just FYI, if you are handing this to an instructor they will call out a number of issues, like the fact that you have const int row and col defined but you only use them once .You should just use those variables; so instead of typing things like 10 , 5 and 9 you should type row, col , row -1.
Also the first arr2 variable is unused and the one in the loop could just as easily not be there and your code would be cout << setw(4) << arr[i][j]<< setw(5) << " | ";
I could go on but I will leave you to find the rest...
Good luck.

C++ Displaying An Organized List of Words

I am making a 20 questions game in C++ and have everything working, except for the displayWords function. The code I currently have keeps breaking. Any explanation would be appreciated! Thank you!
void displayWords()
{
int x = 0;
string words[50] = {"LCHS","Shark","Pencil","Pizza","New York","Fish","Car","Ice Cream","Los Angeles","Bird","Basketball","Fried Chicken",
"Dog","Tiger","Penguin","Plane","Rock","Barbecue Sauce","Mustard","Ketchup","Hot sauce","Peppers","Salt","Tacos","Shrimp","Pickels",
"Tomatos","Bannanas","Burger","Computer","Iphone","Motorcycle","Bicycle","Skateboard","Lightbulb","Golf Ball","Surfboard","Luggage",
"Rollercoaster","Cat","Lion","Cockroach","Grasshopper","Beach","Theme Park","Swimming Pool","Bowling Ally","Movie Theater","Golf Course","Shopping Mall"};
cout << "The following list of words are what the computer is capable of guessing" << endl;
cout << endl;
while(x < 50)
{
for (int y = 0; y <= 5; y++)
{
cout << words[x] << ", ";
if(x<50)
x++;
}
cout << endl;
}
}
I would like it to display the list of 50 words in an organized fashion.
By example, as:
for( int x = 0; x<sizeof(words)/sizeof(*words); x++ ) {
if( x%5==0 ) cout << endl; else cout << ", ";
cout << words[x];
}
take into account the problematic of the array's size calculation: see this link How do I find the length of an array?
If I understand correctly, you want your list displayed as 5 columns. Simplest way, use a nested for loop and proper formatting with std::setw (must #include <iomanip>):
for(size_t i = 0; i < 10; ++i)
{
for(size_t j = 0; j < 5; ++j)
{
std::cout << std::setw(20) << std::left << words[i * 5 + j];
}
std::cout << std::endl;
}
Your actual loop is incorrect, as it will lead to repetitions.
Maybe I'm not interpreting your question correctly but if you want to just print out the 50 words then you can use something like the code below. Not sure of the reason that the nested for loop iterating y was there.
Edit
void displayWords()
{
int x;
string words[50] = {"LCHS","Shark","Pencil","Pizza","New York","Fish","Car","Ice Cream","Los Angeles","Bird","Basketball","Fried Chicken",
"Dog","Tiger","Penguin","Plane","Rock","Barbecue Sauce","Mustard","Ketchup","Hot sauce","Peppers","Salt","Tacos","Shrimp","Pickels",
"Tomatos","Bannanas","Burger","Computer","Iphone","Motorcycle","Bicycle","Skateboard","Lightbulb","Golf Ball","Surfboard","Luggage",
"Rollercoaster","Cat","Lion","Cockroach","Grasshopper","Beach","Theme Park","Swimming Pool","Bowling Ally","Movie Theater","Golf Course","Shopping Mall"};
cout << "The following list of words are what the computer is capable of guessing" << endl;
cout << endl;
for(x = 0; x < words.size();x++)
{
cout << words[x]<< ", ";
}
}
Also some information on how the code is breaking, like are any errors being thrown or has debugging caused issues so far?

Need help printing a sequence, without spaces, on the same line

so here is what i'm working with.
#include <iostream>
using namespace std;
int main()
{
int i, h = -1;
for (i = 0; i < 8; i++) {
h = h + 1;
cout << h << endl;
} // while
return 0;
} // main
I need my output to look like
1 2 3 4 5 6 7
but I am getting
1
2
3
4
...
Is there anything besides endl you can use to print to the same line with spaces? thanks and sorry for the noob question. i'm am slowly learning c++.
It sounds like you want to print every number with a space in between. If so then use an actual space instead of the end of line character
cout << h;
cout << ' ';
Then at the end of the loop explicitly add a new line
cout << endl;
Full Sample
int i;
for (i = 0; i < 8; i++)
{
h = h +1 ;
cout << h << ' ';
}
cout << endl;
cout << h << " "; will do the trick
endl is what prints the newline, so you should place that outside of the loop. Sample:
for (i = 0; i < 8; i++)
{
h = h + 1;
cout << h;
}
cout << endl;