I am a very beginner in c++. i am just learning abc of this language.. i created this small program that would add:
#include <iostream>
using namespace std;
float add(float a, float b){
return a+b;
}
int main(){
float num1;
float num2;
cout<<"add...enter digits \n";
cout<<"first digit: ";
cin>>num1;
cout<<"\n Second number: ";
cin>>num2;
cout<< "your sum is: "<<add(num1, num2)<<endl;
system("pause");
}
this above code is my very first usable application of c++
now i wanted that when some one wants to again add then this program starts again... i thoughts of using loops, i but cannot think how to use in such a way. i mean what conditions i should use.
please tell me
thanks.
Here is how we do :
#include <iostream>
using namespace std;
float add(float a, float b){
return a+b;
}
int main(){
float num1;
float num2;
while(true)
{
cout<<"add...enter digits \n";
cout<<"first digit: ";
cin>>num1;
cout<<"\nSecond number: ";
cin>>num2;
cout<< "your sum is: "<<add(num1, num2)<<endl;
char ch = 'n';
cout << "Start Again, [y/n] ? ";
cin >> ch;
if (ch == 'Y' || ch == 'y')
continue;
else
break;
}
return 0;
}
If we were to take "start from the beginning" literally, we can call main() again when we get to the end!
#include <iostream>
using namespace std;
float add(float a, float b){
return a+b;
}
int main(){
float num1;
float num2;
cout<<"add...enter digits \n";
cout<<"first digit: ";
cin>>num1;
cout<<"\n Second number: ";
cin>>num2;
cout<< "your sum is: "<<add(num1, num2)<<endl;
system("pause");
return main(); // <---- starts again from beginning of main()!!
}
(This will eventually crash when the program runs out of stack space, but the user will almost certainly get tired of adding numbers long before then. Of course, a clever compiler would realize this is tail recursion, and use a goto instead of a function call.)
You can try putting the main part of your 'adding' in an endless loop.
I suggest use a post condition loop, meaning one that will execute it's body at least once (then it will check the condition and so on), because you'll be wanting to add some numbers at least once.
Example:
do {
// do stuff here
} while (true) // always true condition -> makes the loop infinite
So I guess you'll ask how do you stop this. You can ask the user if he wants to continue.
Add this to the loop's body:
int lock = 0;
cout << "Do you want to continue? (0 = no, 1 = yes)" << endl;
cin << lock;
if (lock == 0) break; // stops the loop immeadiately
You can do the same with lock being char with values 'y' or 'n'.
Since you are starting, I am going to suggest changing your code a little bit:
#include <iostream>
using namespace std;
float add(float a, float b)
{
return a+b;
}
// Function that does the core work.
void read_input_print_sum()
{
float num1;
float num2;
cout<<"add...enter digits \n";
cout<<"first digit: ";
cin>>num1;
cout<<"\n Second number: ";
cin>>num2;
cout<< "your sum is: "<<add(num1, num2)<<endl;
}
int main()
{
read_input_print_sum();
system("pause");
}
Now, you can add various methods to call the core function repeatedly. One has been suggested in the answer by Rakibul Hassan.
That can be implemented with:
int main()
{
while (true)
{
read_input_print_sum();
}
system("pause");
}
Another way: Ask the use whether they want do the work again.
bool getRepeat()
{
cout << "Do you want to repeat? (Y/N): ";
int yesno = cin.getc();
return ( yesno == 'Y' || yesno == 'y' );
}
int main()
{
bool repeat = true;
while (repeat)
{
read_input_print_sum();
repeat = getRepeat();
}
system("pause");
}
Another way: Ask the number of times they wish to repeat the computation before you start.
int main()
{
int N = 0;
cout << "How may times do you want to add numbers: ";
cin >> N;
for ( int i = 0; i <= N; ++i )
{
read_input_print_sum();
}
system("pause");
}
The following code will do that:
#include <iostream>
using namespace std;
float add(float a, float b){
return a+b;
}
int main(){
float num1;
float num2;
while( true ){
cout<<"add...enter digits \n";
cout<<"first digit: ";
cin>>num1;
cout<<"\n Second number: ";
cin>>num2;
cout<< "your sum is: "<<add(num1, num2)<<endl;
}
system("pause");
}
above code will run forever. If you want to give user a choice, then apply a loop break condition.
char repeat = 'y';
while( repeat == 'y'){
// do as previous
//.....
//finally give user a choice
cout<< "Do you want to repeat?(y/n):";
cin>> repeat;
}
system("pause");
}
Just call main(); again..
in your code will be like this:
#include <iostream>
using namespace std;
float add(float a, float b){
return a+b;
}
int main(){
float num1;
float num2;
cout<<"add...enter digits \n";
cout<<"first digit: ";
cin>>num1;
cout<<"\n Second number: ";
cin>>num2;
cout<< "your sum is: "<<add(num1, num2)<<endl;
main();
}
Related
I am a new contributor and here I am trying to make a simple calculator but having errors in my code. When I compile the code I get:
Error: C:\Users\IJLAL\Documents\collect2.exe [Error] ld returned 1 exit status while compiling
In case it could help, here is the screen shot of error when I pressed compile button or F11 in Dev C++:
Here is my code:
#include<iostream>
using namespace std;
void fun(float a, float b);
int main()
{
float a, b, sum, sub, mul, divide, mod;
char op;
//operands and operators are enterd by the user
cout<<"Enter any two operands with operator=";
cin>>a>>op>>b;
fun(a, b);
return 0;
}
void op(float a, float b)
{
if(a+b)
{
float sum=a+b;
cout<<"\nAddition of two numbers is="<<sum;
}
else if(a-b)
{
float sub=a-b;
cout<<"\nSubtraction of two numbers is="<<sub;
}
else if(a*b)
{
float mul=a*b;
cout<<"\nMultiplication of two numbers is="<<mul;
}
else if(a/b)
{
float divide=a/b;
cout<<"\nDivision of two number is="<<divide;
}
else
{
cout<<"\nInvalid operator.......";
}
}
Please tell me the solution of this problem, so that I can compile the code successfully. If there is any better solution to make a simple calculator on beginner level please mention it in answer.
You're not so far from a result. The problem is that you have not defined the function fun(). Furthermore, in the function op() that you have defined, you do not use the operator of the input.
So first thing to do is to change the signature of the function:
void fun(char op, float a, float b);
Then you need to invoke your function in main(), passing also the operation that was requested by the user:
fun(op, a, b);
Finally you need to change all your if to check if op is the matching operator:
void fun(char op, float a, float b)
{
if(op=='+')
{
...
}
else if(op=='-')
{
...
You should then get the expected result.
Online demo
Aditional infos
if (a+b) just calculates the expression using the two values of the user, and if it's non zero, it's considered as true.
once you got this program to work, you can look for the switch statement
You can use additional functions to make a better calculator. You can use this code. Hope this code will be helpful for you.
The header <iomanip> is part of the Input/output library of the C++ Standard Library and <math.h> is used when we perform mathematical operations.
#include<iostream>
#include<conio.h>
#include<math.h>
#include<iomanip>
char op;
using namespace std;
void sum()
{
int sum = 0;
int n;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout<< "Enter number "<<i<<":\n\n" ;
cin>>n;
sum+=n;
}
cout<<"sum is: "<< sum<<endl<<endl;
}
void diff()
{
int diff;
int n1,n2;
cout<<"enter two numbers to find their difference:\n\n";
cout<<"enter first number:";
cin>>n1;
cout<<"\nenter second number:";
cin>>n2;
diff=n1-n2;
cout<<"\ndifference is:"<<diff<<endl<<endl;
}
void pro()
{
int pro=1;
int n;
int numberitems;
cout<<"enter number of items:\n";
cin>>numberitems;
for(int i=0;i<=numberitems;i++)
{
cout<<"\nenter item "<<i<<":";
cin>>n;
pro*=n;
}
cout<<"product is:"<<pro<<endl<<endl;
}
void div()
{
int div;
int n1;
int n2;
cout<<"enter 2 numbers to find their quotient\n\n";
cout<<"enter numerator:";
cin>>n1;
cout<<"\nenter denominator:";
cin>>n2;
div=n1/n2;
cout<<"\nquotient is:"<<div<<endl<<endl;
}
void power()
{
long int p;
int res=1,n;
cout<<"enter number:";
cin>>n;
cout<<"\nenter power:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=n*res;
}
cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
}
void sq()
{
float s;
int n;
cout<<"enter number to find its square root:";
cin>>n;
s=sqrt(n);
cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
}
void fact()
{
long int f=1;
int c=1,n;
cout<<"enter number to find its factorial:";
cin>>n;
while(c<=n)
{
f=f*c;
c+=1;
}
cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;
}
void expo()
{
long double res=1,p;
double e=2.718281828;
cout<<"enter power of exponential function:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=e*res;
}
cout<<" e^ "<<p<<" is :"<<res<<endl;
}
int main()
{
system("cls");
do
{
system("pause");
system("cls");
cout<<"***which operation you want to perform***\n";
cout<<"press 0 for exit\n";
cout<<"press 1 for addition \n";
cout<<"press 2 for subtraction\n";
cout<<"press 3 for multiplication\n";
cout<<"press 4 for division\n";
cout<<"press 5 for power calculation\n";
cout<<"press 6 for square root \n";
cout<<"press 7 for factorial calculation\n";
cout<<"press 8 for exponential calculation\n";
cout<<"press option:";
cin>>op;
switch(op)
{
case '1':
sum();
break;
case '2':
diff();
break;
case '3':
pro();
break;
case '4':
div();
break;
case '5':
power();
break;
case '6':
sq();
break;
case '7':
fact();
break;
case '8':
expo();
break;
case '0':
exit(0);
default:
cout<<"invalid input" ;
system("cls");
}
}
while(op!='0');
getch();
}
Hey I'm still a newbie on c++ but hope this would help, I used while loop to loop the calculator but I don't have a good error handler for example when users try to input a letter instead of numbers.
#include <iostream>
#include <cmath>
using namespace std;
int result (int a, int b, char op);
int main()
{
char optr, choice;
int nr1, nr2;
while (true){
cout << "Enter first number: ";
cin >> nr1;
cout << "Enter an operator (+ - / * %) : ";
cin >> optr;
cout << "Enter second number: ";
cin >> nr2;
result (nr1, nr2, optr);
cout<<"Would you like to perform other calculation?(Y/N): ";
cin >> choice;
if (choice =='N'||choice =='n'){
break;
}
}
}
int result (int a, int b, char op)
{
int result;
if (op == '+'){
result = a + b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '-'){
result = a - b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '*'){
result = a * b;
cout << "Result to " << a << " * " << b << " = " << result << endl;
} else if (op == '/'){
result = a / b;
a / b;
cout << "Result to " << a << " / " << b << " = " << result << endl;
} else if (op == '%'){
result = a % b;
cout << "Remainder to " << a << " % " << b << " = " << result << endl;
} else {
cout <<"Error 404: " << a << op << b <<" Wrong input format. Program terminated." << endl;
// i still dont know how to properly use error handling
}
}
I won't criticize your solution as I have a better solution as you mentioned "please mention a better solution in answer"
Here's my solution with comments to make you understand what each statement does.
#include <iostream>
using namespace std;
// I am going to show How to Design a program
// We have to break down our progress a bit by bit
// and do the progress of one thing with function
// For calculator we have to take input from user keyboard twice,
// And an opperator from user
int userInput() // this requires to get input from user keyboard
{
cout << "Enter a number: ";
int no{};
cin >> no;
return no;
}
char userOpr() // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
{
cout << "Enter opperator: ";
char opr{};
cin >> opr;
return opr;
}
int calculate(int input1, char opper, int input2)
{
if (opper == '+')
{
return input1 + input2;
}
else if (opper == '-')
{
return input1 - input2;
}
else if (opper == '*')
{
return input1 * input2;
}
else if (opper == '/')
{
return input1 / input2;
}
return 0;
}
int main()
{
// get the first no. from user
// getUserInput();
// get the math oppperator from the user
// getMathOpperator();
// get the second no. from the user
// getUserInput();
// calculate the values
// calculateResults();
// print out the results
// printResults();
cout << "Hello This is a simple calculator program Designed by Shankhui!\n\n";
while (true)
{
int input1{ userInput() };
int input2{ userInput() };
char opper{ userOpr() }; // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
cout << input1 << " " << opper << " " << input2 << " = " << calculate(input1, opper, input2) << '\n' << '\n';
}
return 0;
}
Just copy this code and modify however you want to.
#include <iostream>
int main() {
int math_ques_1, math_ques_2;
std::cout << "What is the base of the question?" << std::endl;
std::cin >> math_ques_1;
std::cout << "What do you want to add to the base?" << std::endl;
std::cin >> math_ques_2;
std::cout << "The answer is " << math_ques_1 + math_ques_2 << "." << std::endl; }
So here is the code.
Please tell me what is wrong in this code and why does this stop after taking cin>>a;
#include <iostream>
using namespace std;
int x;
int y;
int main(){
cout<<"What do you want to do:-"<<endl<<"add"<<endl<<"sub"<<endl<<"mul"<<endl<<"div"<<endl;
string a;
cin >> a;
if('a' =='add')
{
cout<<"working"<<endl;//this was used to check whether was working or not but it didn't
cin>>x;
cin>>y;
cout<< x+y <<endl;
}
if('a' =='sub')
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x-y <<endl;
}
if('a' =='mul')
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x*y <<endl;
}
if('a' =='div')
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x/y <<endl;
}
return 0;
}
So it perfectly builds.I am using eclipse ide.
Thank you
You code exits because all of these if statements are wrong. You compare a character a with a multi character constant div for example. What you really want to do is compare strings. More precisely the string stored in the variable a and a string constant.
The following should work:
#include <iostream>
using namespace std;
int x;
int y;
int main(){
cout<<"What do you want to do:-"<<endl<<"add"<<endl<<"sub"<<endl<<"mul"<<endl<<"div"<<endl;
string a;
cin >> a;
if(a =="add")
{
cout<<"working"<<endl;//this was used to check whether was working or not but it didn't
cin>>x;
cin>>y;
cout<< x+y <<endl;
}
if(a =="sub")
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x-y <<endl;
}
if(a =="mul")
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x*y <<endl;
}
if(a =="div")
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x/y <<endl;
}
return 0;
}
You see:
a is accessed by dropping ' and a string constant needs " " instead of ' '.
I hope this helps!
Greetings
Try to use strcmp function present in string.h header to compare strings in the if statement.
if(strcmp(a, "add") == 0) {
// Addition code here...
}
I know most of people may find this too easy but i am still very new to programming so i need a program that allows the user to enter 100 numbers and the program finds their sum , i have tried this:
#include <iostream>
using namespace std;
int main ()
{
float x;
int counter=0 , sum=0;
cout<<"enter a number\n";
cin>>x;
do {
sum+=x;
cout<<"sum="<<sum<<endl;
counter++;
}
while ( counter<=100 );
}
i found this making 'x' has the value that i entered first time but i need to enter different value every time it repeats (entering 100 different values) what should i add?
Simply move the input prompt and cin into the loop
do
{
cout << "enter a number\n";
cin >> x
sum += x;
cout << "sum=" << sum << endl;
counter++;
}
while (counter < 100);
Take note that it should be counter < 100 instead of counter <= 100 if you want it to be exactly 100 times.
You just have put the cin into the loop so that in every iteration it asks for an input.
Also note that the variable sum is an integer, while the variable x is a float.
So you probably should make sum a float or make x an integer to avoid getting unexpected results .
#include <iostream>
using namespace std;
int main () {
float x,sum=0;
int counter=0 ;
do {
cout<<"enter a number\n";
cin>>x;
sum+=x;
cout<<"sum="<<sum<<endl;
counter++;
} while ( counter<=100 );
}
You can use a For loop also for simplicity. Make sure to use long int data type for storing sum because the sum of 100 integers may lead to integer overflow.
#include <iostream>
using namespace std;
int main() {
int x, num;
long int sum=0;
cout<<"Enter the number you want to find the sum:";
cin>>num; // Like 100
for(int counter=1;counter<=num;counter++)
{
cout<<"Enter a number:";
cin>>x;
sum+=x;
}
cout<<"Sum of "<<num<<" numbers is:"<<sum;
return 0;
}
You could also do it in a for loop:
float input, sum;
for(int i = 0;i < 100; i++){
cout << "Enter a number << endl;
cin >> input;
sum += input;
cout << "sum is: << sum << endl;
}
Look out at the condition of your while. You are saying this -> counter<=100, and counter is initialized to 0. So, you will enter from 0 to 100(included) = 101 times. If you only want to enter 100 times, the condition should be
do
{
cout << "enter a number\n";
cin >> x
sum += x;
cout << "sum=" << sum << endl;
counter++;
}
while (counter < 100);
or initialize counter to 1, and then you can use the same while as you had.
I am trying to write a program that accepts inputs of even numbers until the user enters a odd number then it stops and adds all the even inputs.
The problem I am having is that I'm intending to use an if statement to determine if the number is even or not but once the program has run I need it to run again so the user can keep inputting numbers until they input a odd one.
Here's what I have so far:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int value;
cout << "Please enter a possitive number: ";
cin >> value;
if (value%2 == 0) { // divides the value entered by 2 too determine whether or not its even.
cout << "Please enter another even number: ";
}
else
{
}
cin.get();
return 0;
}
You need a loop in order to ask for input again in case the value is even.
You will enter the while loop only if value is even. And you will loop until value input is even.
You then need another int which represents the sum and add the value to the sum each time you enter the loop (each time you have an even number)
Note that with this solution you don't need an if statement. The condition is in the while loop
#include <iostream>
using namespace std;
int main()
{
int value;
int sum=0;
cout << "Please enter a possitive number: "<<endl;
cin >> value;
while (cin && value%2 ==0){
sum+=value;
cout << "Please enter another even number: "<<endl;;
cin >> value;
}
cout<<"Sum of even number: "<<sum<<endl;
return 0;
}
Just do it.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int value;
vector<int> inputs;
cout << "Please enter a possitive number: ";
while (cin >> value) { // loop while successfully read an integer
if (value%2 == 0) { // divides the value entered by 2 to determine whether or not its even.
inputs.push_back(value);
cout << "Please enter another even number: ";
}
else
{
break; // get out of this loop
}
}
// add all the even inputs
int sum = 0;
for (vector<int>::iterator it = inputs.begin(); it != inputs.end(); it++) {
sum += *it;
}
cout << sum << endl;
return 0;
}
Alternatively, you can do the addition inside the loop.
#include <iostream>
using namespace std;
int main()
{
int value;
int sum = 0;
cout << "Please enter a possitive number: ";
while (cin >> value) { // loop while successfully read an integer
if (value%2 == 0) { // divides the value entered by 2 to determine whether or not its even.
sum += value;
cout << "Please enter another even number: ";
}
else
{
break; // get out of this loop
}
}
cout << sum << endl;
return 0;
}
something like this?
int value;
bool run = true;
cout << "Please enter a possitive number: ";
while(run)
{
cin >> value;
if (value%2 == 0) { // divides the value entered by 2 too determine whether or not its even.
cout << "Please enter another even number: ";
}
else
{
run=false
}
}
It is sudo code modeled similar to your loop, so not the best way, also most likely there might be syntax error, but should give you an idea
one more way to check whether it is even or odd is to check lowest bit:
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
int enteredValue = 0;
std::vector<int> result;
do {
std::cout<<"Please enter even number : ";
std::cin>>enteredValue;
result.push_back(enteredValue);
std::cout<<'\n';
}while(!(enteredValue & 0x01)); //check the lowest bit
std::for_each(result.begin(), result.end(), [](int x){ std::cout<<x<<' '; });
return 1;
}
I am trying to do a modulus operation. I ask the user to input two numbers, since modulus only works with integers, I have a while loop that checks if the inputs are integers. Then the while loop ask the user to re-enter the two numbers. But the while loop keeps on repeating and does not allow the user a chance to re-enter the numbers. What will be the proper to go about doing this?
#include <iostream>
using namespace std;
int Modulus (int, int,struct Calculator);
struct Calculator
{
int per_numb1, per_numb2;
int per_Result; };
int main ()
{
Calculator Operation1;
cout << "\nPlease enter the first number to calculate as a modulus: ";
cin >> Operation1.per_numb1;
cout << "\nPlease enter the second number to calculate modulus: ";
cin >> Operation1.per_numb2;
while ( !( cin >> Operation1.per_numb1) || !( cin >> Operation1.per_numb2))
{
cout << "\nERROR\nInvalid operation \nThe first number or second number must be an integer";
cout << "\n\nPlease re-enter the first number to begin Modulus: ";
cin >> Operation1.per_numb1;
cout << "\nPlease re-enter the second number to begin Modulus: ";
cin >> Operation1.per_numb2;
}
Operation1.per_Result = Modulus(Operation1.per_numb1, Operation1.per_numb2, Operation1);
cout << "\nThe result is: " << Operation1.per_Result << endl;
}
int Modulus (int n1, int n2, struct Calculator)
{
int Answer;
Answer = n1 % n2;
return Answer;
}
Refactor to something like this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
class Calculator
{
public:
static int Modulus (int n1, int n2);
};
int Calculator::Modulus (int n1, int n2)
{
return n1 % n2;
}
int getInt(string msg)
{
int aa;
cout << msg;
cin >> aa;
while (cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cerr << "Input was not an integer!" << endl;
cout << msg;
cin >> aa;
}
return aa;
}
int main ()
{
int num1 = getInt("Enter first value: ");
int num2 = getInt("Enter second value: ");
int value = Calculator::Modulus(num1,num2);
cout << "Answer:" << value << endl ;
}
When the input parsing fails, invalid input data will remain in the stream. You need to
clear the stream error state by calling cin.clear().
and skip the remaining invalid input.
See the answer to this question.