How to use looping in C++ - c++

I am new to C++ and I am making a program to generate a multiplication table. Here is he code.
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number to find Multiplication Table ";
cin >>num;
for(int a=1;a<=10;a++)
{
cout<<num<<" x "<<a<<" = "<<num*a<<endl;
}
cout << "Press ENTER to continue...\n";
cin.get();
getchar();
return 0;
}
I want that after the multiplication table of one number is displayed , the user should have an option of entering another number or exiting.
Like press "n" to enter a new number or "e" to exit

This may be what you want. (this is the implementation of main function)
int num;
char command;
bool exit=false;
while(!exit)
{
cout << "Enter a number to find Multiplication Table ";
cin >>num;
for(int a=1;a<=10;a++)
{
cout<<num<<" x "<<a<<" = "<<num*a<<endl;
}
cout << "Press n to continue or e to exit\n";
cin >> command;
while(command != 'n' && command != 'e')
{
cout << "Just press n to continue or e to exit!\n";
cin >> command;
}
if (command == 'e')
{
exit=true;
}else
{
exit=false;
}
}
return 0;

#include <iostream>
using namespace std;
int main()
{
int num;
char ch;
do{
cout << "Enter a number to find Multiplication Table";
cin >> num;
for(int a=1;a<=10;a++)
{
cout<<num<<" x "<<a<<" = "<<num*a<<endl;
}
cout << "Press \"n\" to enter a new number or \"e\" to exit\n";
}while(cin>>ch && ch=='n');
return 0;
}

Related

I need to delete an element in an array everytime a user press , but when is being output after deletion I got long number like ; 124352919

int main ()
{
int a[]={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,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75};
char ans;
int i = 0;
int pos = 0;
cout<<"Press y to generate number"<<"\n";
cin >> ans;
while(ans=='y'||ans=='Y')
{
cout<<"\n\nEnter position to Delete number :: ";
cin>>pos;
--pos;
for(i=pos;i<=size-1;i++)
{
a[i]=a[i+1];
cout<<" "<<a[i]<<" ";
}
cout<<"\nNew Array is :: \n\n";
for(i=0;i<size-1;i++)
{
}
cout<<"Press y to generate number"<<"\n";
cin >> ans;
}
cout << "\n\n";
//I need to delete an element in the array ,for example ; if I input position 67 ,it deletes position 67 but when the array is being after deletion , I got 1312123131 at the end
You can't delete an element from an array, but you can delete a vector element like this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> nums = { 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,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75 };
char ans;
int pos = 0;
cout << "Press y to generate number: ";
cin >> ans;
while (ans == 'y' || ans == 'Y')
{
cout << "\n\nEnter position to Delete number: ";
cin >> pos;
--pos;
nums.erase(nums.begin() + pos);
cout << "\nNew Array is:\n\n";
for (const auto& element : nums)
{
std::cout << element << '\n';
}
cout << "Press y to generate number" << "\n";
cin >> ans;
}
}

alphabetic inputs run infinite loop

I wrote a function to squire number and try to cover all the input possibilities.
Overall it works fine with numeric input, but it starts a infinite loop of printing statements on screen when I enter alphabetical input.As all we know that inside computer single character like "A or a or b or B" so on is represented by integers and as i learned from my teacher that we can store single characters into a variable with integer data type. i am not talking about strings which means collection of characters . this program create problem with single character !
#include <iostream>
#include <string>
using namespace std;
void squire();
int main() {
squire();
}
void squire() {
double num = 1.0, pow = 1.0, Squire_Number = 1.0;
char ans;
reStart:
cout << "please Enter the Number: \n";
cin >> num;
cout << "please enter the nmber you want to power the number with: \n";
cin >> pow;
if (num > 0 && pow>0) {
for (int i = 1; i <= pow; i++) {
Squire_Number *= num;
}
cout << pow << " power of " << num << " is equil to : " << Squire_Number;
goto option;
}
else
{
cout << "Please enter Positve Integers. \n" ;
option:
cout<< "\nPease type 'Y' to Enter the values again OR type 'c' to Exit ! \n";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
goto reStart;
} else if (ans == 'c' || ans == 'C') {
cout << "thank you for using our function. \n";
}
}
return;
}
Better try to read the input in an std::string, then parse the string to check if you only have numeric characters and then use std::atoi to convert the string in integer. One last recomendation, avoid to use goto instructions, this practice make a code difficult to read.
#include <iostream>
#include <string>
#include <cstdlib>
bool OnlyNumeric(const std::string& numStr)
{
size_t len= numStr.length();
int i;
for (i=0;i<len && numStr[i] <='9' && numStr[i] >='0';i++) ;
return i == len;
}
int main()
{
std::string inputStr;
int num;
do{
std::cout << "Input number:\n";
std::cin >> inputStr;
}
while (!(OnlyNumeric(inputStr) && (num=std::atoi(inputStr.c_str())) ));
std::cout << "Your number is : " << num;
return 0;
}

C++ total keeps going up

Hello this is my first program with a do-while loop and its taken me a little while to get it down. I need to have the user enter 2 numbers, and raise the first number to the second number. I have finally got the coding to ask if "they would like to raise another number by a power?" and when they say yes and enter 2 new numbers the total adds the total from the first 2 numbers entered with the second set of numbers and so on. Can someone help me out with this problem? Here is the coding and a picture to help y'all out!
#include <iostream>
using namespace std;
int main()
{
int num;
int pow;
int p;
int power = 1;
char yesno = 'y' || 'Y';
do
{
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno != true);
}
The problem of the ever-increasing answer is that power is not being reset inside the do-while loop, so the last value is being carried forward into the next loop. You need reset it at the top of the loop.
Another problem with the code is that the exit condition would never occur.
Try this instead:
int main()
{
int num;
int pow;
int p;
int power;
char yesno;
do
{
power = 1; // <<<<<< reset power here
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno == 'y' || yesno == 'Y'); // <<<<< test for 'yes' response
}
When you reach line } while (yesno != true); and loop back to do {, the variable power still holds the previous num^pow. You will need to assign power = 1 after do {.
#include <iostream>
// you also need
#include <cmath> // for pow()
using namespace std;
int main()
{
// int num; Declare variables where they're used. As locally as possible.
// int pow;
// int p;
// int power = 1;
// char yesno = 'y' || 'Y'; I don't know what you were trying to do here
// the expression 'y' || 'Y' will always be true
// and evaluate to some value different from null
// wich will be assigne to yesno. But with no con-
char yesno; // sequences since it later gets overwritten by
do // cin >> yesno; There is no need to initialize
{ // this variable.
cout << "Enter a number: ";
int num;
cin >> num; "\n"; // the statement "\n"; has no effect.
cout << "Enter the power to raise: ";
int pow;
cin >> pow; "\n"; // again. no effect.
// for (p = 1; p <= pow; p++) as user4581301 has pointed out in the
// comments it is more ... natural in C
// to loop from 0 to < max:
int power = 1; // now its time to declare and define power ;)
for(int p = 0; p < pow; ++p) // notice that you can declare variables
{ // in the init-statement of a for-loop
// power = power * num; shorter:
power *= num;
}
cout << "The total is: " << power << /* endl; + 2 x '\n' gives: */ << "\n\n\n";
// cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
// } while (yesno != true); that condition will most likely always be true
// since the user would have a hard time to input
// a '\0' character, which would evaluate to false
// better:
} while(yesno == 'y' || yesno == 'Y' );
}
done.
Without clutter:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char yesno;
do {
cout << "Enter a number: ";
int num;
cin >> num;
cout << "Enter the power to raise: ";
int pow;
cin >> pow;
int power = 1;
for(int p = 0; p < pow; ++p)
power *= num;
cout << "The total is: " << power << "\n\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while(yesno == 'y' || yesno == 'Y' );
}

why is loop stuck

Only problems remaining now are that my choice while loop is infinite since the break statements dont seem to be breaking out of the loop at all, so the program doesn't read the answer loop. Also, "Invalid Entry" displays every other incorrect input instead of displaying everytime an invalid character is entered
#include <iostream>
#include <cctype>
using namespace std;
int getAges(int age, const int SIZE);
char getChoice();
void displayInOrder(int numbers[], const int SIZE, char choice);
void displayInReverse(int numbers[], const int SIZE, char choice);
int main()
{
const int SIZE = 5;
int numbers[SIZE] = { 1, 2 ,3 ,4, 5 };
char answer = 0;
int age = 0;
char choice = 0;
while (choice = getChoice())
{
if (toupper(choice) == 'O')
{
displayInOrder(numbers, SIZE, choice);
break;
}
else if (toupper(choice) == 'R')
{
displayInReverse(numbers, SIZE, choice);
break;
}
else
{
cout << "Invalid entry! - Must be O or R\n\n";
break;
}
}
while (toupper(answer) == 'Y')
{
system("cls");
age = getAges(age, SIZE);
choice = getChoice();
displayInOrder(numbers, SIZE, choice);
displayInReverse(numbers, SIZE, choice);
cout << "Run program again (Y or N)? ";
cin >> answer;
if (toupper(answer) == 'N')
{
exit();
}
}
return 0;
}
int getAges(int age, const int SIZE)
{
cout << "Enter " << SIZE << " ages: \n\n";
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
return age;
}
char getChoice()
{
char choice;
cout << "How do you want to see the ages displayed? \n\n Enter O for In Order, or R for In Reverse.\n\n";
cin >> choice;
return choice;
}
void displayInOrder(int numbers[], const int SIZE, char answer)
{
cout << "Here are the ages in order: \n\n";
for (int i = 0; i < SIZE; i++)
{
cout << numbers[i] << endl;
}
}
void displayInReverse(int numbers[], const int SIZE, char answer)
{
cout << "Here are the ages in reverse order: \n\n";
for (int i = SIZE - 1; i >= 0; i--)
{
cout << numbers[i] << endl;
}
}
1."Invalid Entry" displays every other incorrect input: you have a getChoice() call inside the while loop, here:
else
{
cout << "Invalid entry! - Must be O or R\n\n";
choice = getChoice();
}
which is followed by a getChoice() call in the
while (choice = getChoice())
Hence the previous getChoice() is not processed.
2."I'm not sure how to close the program if the user enters N for answer", You should think about if you can ever reach the second while loop and where you are setting the answer variable or basically where you are taking the user input for ending the program? You should see if it can it be taken care of in the first while loop ?

How would I give the choice to do multiple math problems without having to copy and paste the code each time?

My code allows for the user to either input some numbers or read them from a document. How would I also allow the user to pick from a choice of math problems to perform on those numbers without having a bunch of code in my main.
Here is my code so far:
#include <iostream>
#include <cmath>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
int main()
{
//ask for file input or manual input
cout << "Press 1 to enter numbers or 2 to read them from a list." << "\n";
int choice;
cin >> choice;
if (choice == 1)
{
int numberswanted;
cout << "How many numbers would you like to enter?" << "\n";
cin >> numberswanted;
vector<double> list;
for (int i = 0; i < numberswanted; i++)
{
cout << "Enter your numbers: " << "\n";
double x;
cin >> x;
list.push_back(x);
}
}
else if (choice == 2)
{
ifstream doc;
float output;
doc.open("input.txt");
while (!doc.eof())
{
vector<double> list;
double x;
doc >> x;
list.push_back(x);
}
doc.close();
}
return 0;
}
May be you can try something like this :
int main() { cout << "Press 1 to enter numbers or 2 to read them from a list." << "\n";
int choice;
cin >> choice;
if (choice == 1)
{
choice1();
}
else if (choice == 2)
{
choice2();
}
return 0;}
when choice1 contains int [...] list.push_back(x);}
etc...