chapter2
chapter2
Variables
It is a named location in memory that is used to hold a value or data. So variables are
located in particular places in the computer’s memory. When a variable is given a value, that
value is actually placed in the memory space assigned to the variable.
Syntax: < type> < variable name>;
Example: int number;
Variable names
For naming variables you can use upper and lowercase letters, digits or underscore (_)
character. The first character must be a letter or underscore.
C++ keywords (predefined words)can’t be used as a variable name Example : int
const ; is wrong declaration because const is a keyword in c++
Compliers distinguish between upper and lower case letters
Example: int num;
int Num ; here num and Num are treated as separate variable names and
will be allocated separate memory location.
Count will be incremented first before multiplication but if we had use postfix
notation (count++) multiplication will be performed first and then count will be
incremented
Example (for decrement case)
--count;
Count--;
It has the same definition as before except here the value reduces by one.
Example
What is the output of the following program?
#include<iostream>
using namespace std;
int main()
{
int count=10;
cout<<”count=”<<count<<endl;
cout<<”count=”<<++count<<endl;
cout<<”count=”<<count<<endl;
cout<<”count=”<<count++<<endl;
cout<<”count=”<<count<<endl;
return 0;
}
Exercise on chapter two
1. If you have two fractions, a/b and c/d their sum can be obtained from the formula
a c a*d + b*c
--- + --- = -----------
b d b*d
For example; 1/4 plus 2/3 is
1 2 1*3 + 4*2 3 + 8 11
--- + --- = ----------- = ------- = ----
4 3 4*3 12 12
Write a program that encourages the user to enter two fractions, and then displays their
sum in fractional form. (You don’t need to reduce it to lowest terms.) The interaction of
program with the user might look like this:
Enter first fraction: 1/2
Enter second fraction: 2/5
Sum = 9/10
2. You can convert temperature from degrees Celsius to degrees Fahrenheit by multiplying
by 9/5 and adding 32. Write a program that allows the user to enter a floating-point number
representing degrees Celsius, and then displays the corresponding degrees in Fahrenheit.