Arithmetic Operators Operation Operator Example Addition = 9 Subtraction = 1 and = -1 Multiplication * 5 * 4 = 9 Division (integer) / 15 / 3 = 5 and 12 / 5 = 2 Modulus % 12 % 5 = 2, 15 % 3 = 0, and 3 % 5 = 3
Fundamental C++ Variables TypeSize in Bytes Values integer variables unsigned short int20 to 65,535 short int2-32,768 to 32,767 unsigned int40 to 4,294,967,295 int4-2,147,483,648 to 2,147,483,647 unsigned long int40 to 4,294,967,295 long int4-2,147,483,648 to 2,147,483,647 long long int to floating-point variables float41.2e-38 to 3.4e38 double82.2e-308 to 1.8e308 logical variablebool1true or false character variablechar1256 character values
(Sum of digits) Make a program that reads a three-digit and then calculates sum of the digits. (Hint: Use the modulus (%) and integer division (/) operators.)
#include using namespace std; int main() { int num,a,b,c,sum; cout<<"Enter 3 digit integers"<<endl; cin >> num; a=(num%10); b=(num %100)/10; c=num/100; sum = a+b+c; cout <<a<<“+”<<b<<“+”<<c<<“=“<<sum<<endl; system("PAUSE"); return 0; }
Using Text Files as Input and Output C++ provides two functions to read from a text file and to write into a text file. Those functions are ifstream() and ofstream(). Both functions are declared in the header. ifstream opens an existing input file whereas, ofstream creates or recreates and opens the output file. After you have finished with the input and output files you should close them so that their resources become available again for the system. close() function is used to close the open files.
#include using namespace std; int main() { ifstream fin("numbers.in"); //open input file ofstream fout("numbers.out");//create and open output file int num1, num2; fin >>num1 >>num2; //read two integers from the input file. fout <<"sum is "<<num1+num2<<endl; fout <<"difference is "<<num1-num2<<endl; fout <<"product is "<<num1*num2<<endl; fout <<"integer quotient is "<<num1/num2<<endl; fout <<"floating-point quotient is "<<(float)num1/num2<<endl; fin.close(); //close the input file fout.close(); //close the output file system("PAUSE"); return 0; } The following program read two integers (num1 and num2) from the file numbers.in. Computes sum, difference, product and quotient of those two numbers and then writes the result into the file numbers.out
HOMEWORK (Sum of digits) Make a program that reads a four-digit integer from the file "number.in" and then calculates sum of the digits and writes the result into the file "sum.out". (Hint: Use the modulus (%) and integer division (/) operators.)