0% found this document useful (0 votes)
43 views43 pages

Variables and Operators: C++ Basics

Here are the errors in the original program: 1. main() should return int, not void. 2. num2 is undeclared - needs to be declared like num1. 3. sum is declared as 2sum which is invalid. 4. cin >> "num1" is invalid - don't use quotes with variables. 5. Num2 has incorrect case - it should match the declaration. 6. endl is used incorrectly with cin. The corrected version declares all variables, uses cin correctly to read into variables, and fixes other syntax errors.

Uploaded by

Besho .m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views43 pages

Variables and Operators: C++ Basics

Here are the errors in the original program: 1. main() should return int, not void. 2. num2 is undeclared - needs to be declared like num1. 3. sum is declared as 2sum which is invalid. 4. cin >> "num1" is invalid - don't use quotes with variables. 5. Num2 has incorrect case - it should match the declaration. 6. endl is used incorrectly with cin. The corrected version declares all variables, uses cin correctly to read into variables, and fixes other syntax errors.

Uploaded by

Besho .m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Variables and operators

C++ Basics
In this lecture we will see
• Variable
–What
–Declaration
–Initialization
• By the programmer
• Input by the user
In this lecture we will see (cont)
• Operator
–What
–Types of operators
–Operator rules
Example – adding 2 numbers
• Yousof: Hey Khalifa, I just learned how to add two numbers together.
• Khalifa: Cool!
• Yousof : Give me the first number.
• Khalifa: 2.
• Yousof : Ok, now give me the second number.
• Khalifa: 5.
• Yousof : Ok, here's the answer: 2 + 5 = 7.
• Khalifa: Wow! Yousof you are AMAZING!

after Khalifa says “2”, Yousof has to keep this number in his mind.

after Khalifa says “5”, Yousof also needs to keep this number in his mind.

First number: 2 Second number: 5 Sum: 7


Variables

 A variable refers to memory location associated


with a memory address where a value of a
specified type may be stored
 The value of a variable can be changed during the
program execution
 The variable is referred to by a name
Variable: what for?

–To get input values from the users/files and


store these values into the defined variables
–To extract the content of these variables and
produce the output values
–To modify and change the content of these
variables to some other values
Variables Types
• Common data types
– Numeric types (NT) and Non-Numeric types (NNT)

Data types Description Size in Bytes example


int Integer 4 1234
float Single floating point 4 (6 Decimal Digits) 15.345
NT double Double floating point 8 (15 Decimal Digits) 7.883774
bool Boolean (true, false) 1 true/false
char Characters 1 ‘A’

– An integer type is a number without a fractional part


• Will be stored exactly (Example: 3, 7, 999, 100000)
– A floating-point type is a number with a fractional part
• Will be rounded off (Example: 5.54, 3.22)
Variables Declaration
 Variables can be declared anywhere in the program
 Usually after the main() function directly
 Variables MUST be declared with a data type and a name
BEFORE they can be used

 Single variable declaration statement:


 Syntax: <datatype> <variable_name>;
 Example: int x;
 Declares a variable named x of type int

 Multiple variables declaration statement of same type


 Syntax: <datatype> <var1>, <var2>, <var3>;
 Example: int x,y,z;
Variables Declaration (cont)

– When you declare a variable, the compiler:


• Reserves a memory location in which to store the value of
the variable.
• Associates the name of the variable with the memory
location. (You will use this name for referring to the constant
or variable.)
• Specifies the type of the information that will be stored in
that location and defines its size.
Variables: Exercise-1
 We want to write a program that computes and displays
the area of a circle. Show what variables you will need
and how you will declare them, assuming you have done
the following analysis

Input: Radius of the circle


output: Area of the circle
Process : Compute the area
Variables: Exercise-1
- One variable for the radius, type : real number ;
- One variable for the area, type : real number ;

float Radius, Area ;


Comments about Variables naming
• Variables should be descriptive of what they stand for
–Example: to store a POBox number, you can declare it as:
int POBox;

• Rules for naming Variables


–Can only contain letters (A-Z,a-z), digits (0-9), underscores (_) and
dollar sign ($) in new versions
–Must starts with letters, underscore (_) or $
–Cannot begin with digit
–Cannot contain special characters (except for $)
–Cannot contains spaces or dot (.)
–Cannot use reserved words of C++ language
–Case sensitive
Comments about Variables naming

 Cannot use C++ reserved words


C++ contains many reserved words and each keyword has a
predefined purpose in the language.

bool, break, case, char, const,


continue, do, default, double, else,
false, float, for, if, int, long,
namespace, return, short, static,
struct, switch, true, void, while
Examples
Variable VALID? REASON IF INVALID

integer1

Integer_1

integer$ Some special char are not


integer& allowed

integer.1/ integ 1 No(.) or spaces

1integer Cannot begin with digit

if, while, void Reserved words


Variable Initialization (1)
• First Way (programmer): Using the assignment operator (=)
–Assigns value to variable
–Used to store values results from expression to variables
variable = expression;

–Variables can be declared and then initialized


<datatype> <variable>;
<variable> = initial_value;
int sum; /* the value of sum can be anything (garbage) */
sum = 7;

–Variables can be declared and initialized simultaneously


<datatype> <variable> = initial_value;
int sum = 1;
Variables: Exercise-2
 Write the instructions that declare and
initialize to 0, the variables defined in
exercise 1
OR
float Radius, Area ;
float Radius =0 ;
Radius =0;
float Area =0 ;
Area = 0;
Constant Declarations
• Constants are used to store values that never change during
the program execution.
• Constant variables must be initialized at the same time of
declaration
• Constants must be declared before the main function
• Syntax:
const <type> <identifier> = <expression>;
<type> const <identifier> = <expression>;

Examples:
const float pi = 3.1415;
float const pi = 3.1415;
Variables: Exercise-3
• Using the variables of exercise-2, write a
program that computes the area of circle.
Assume the following:
• The program uses a constant for PI
• The value of radius is assigned by the
programmer at the initialization
Variables: Exercise-3
#include <iostream>
using namespace std;
const float PI = 3.1415; // PI constant declaration
int main()
{
float Area =0; //declaration and initialization of the area
float Radius =2.5; // declaration of the variable and assigning of
//a value to it by the programmer
Area = PI*Radius*Radius;
cout << “The Area is ”<< Area<<endl ; // prints the Area
return 0;
}
Variable Initialization (2)
• Second Way (by the user): using Standard Input Stream
object cin (see-in) with the stream extraction operator >>:
–>> is used with cin (see-in)
–It waits for user to input value (the keyboard by default), then process
the data once the Enter (Return) key has been pressed
–It stores value in variable to right of operator
–Skips over white spaces (space, tab, newline).

–Example:
int num1;
cin >> num1;

20
Example
• Write a C++ program that reads two integer
numbers add them and print the result of addition

• The program must ask the user to enter the first


number and the second number

• The program must also display the result of the


addition of the two numbers
Variable Initialization (2)
• Correct Way

/* Variables must be declared before */


/* being used. */
int num1, num2;

/* Variable Initialization by a user */


/* Request two values from the user */
/* First Way: Separate lines */
cin >> num1;
cin >> num2;

/* OR: Second Way: a single line */


cin >> num1 >> num2;
Variable Initialization (2)
 Incorrect Way (generates syntax error)
 Using the insertion operator (wrong direction) with cin
cin << num1 << num2;
 Using comma between the two variables instead of >>
cin >> num1, num2;

 Using endl or \n with the cin is not allowed


cin >> endl;
cin >> "\n";

 Putting variables within double quotation marks " "


cin >> "num1";
#include <iostream>

using namespace std;

int main()
Notice how cin is used to get the user input.
{ int num1, num2, sum; //declaration

cout << “ Please enter first number \n” ; // prompt

cin >> num1; // read the first integer

cout << “ Please enter second number \n” ; // prompt

cin >> num2; // read the second integer

Variables can be output using cout << variableName.


Please enter first number
sum = num1 + num2; // assignment
4

Please enter second


cout << number
“The sum is ”<<sum<<endl ; // print the value of sum
5
return 0;
Find the errors in this program
/* This is a practice example

Find the errors in this program. */

#include <iostream>

using namespace std;

void main()

{ int num1; num2; 2sum;

cout << "Please enter two numbers \n";

cin >> "num1">>endl;

cin >> Num2;


Correct version
/* This is a practice example

Solution . */

#include <iostream>

using namespace std;

int main()

{ int num1, num2, sum;

cout << "Please enter two numbers \n" ;

cin >> num1;

cin >> num2;


Memory Concept
num1 4

cin >> num1;

Assume user entered: 4


num1 4

num2 5

cin >> num2;

Assume user entered: 5


num1 4

num2 5

sum 9
sum = num1 + num2;
Operators
• Symbols telling the compiler to perform a
specific arithmetic or logical operations
• Arithmetic operators
• Assignment operators
• Logical operators
• And more…
Arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
C ++ o p e ra tio n Arith m e tic Alg e b ra ic C ++ e xp re ssio n Exa m p le
o p e ra to r e xp re ssio n
Addition + x+7 x + 7 x = 4 + 2;
Subtraction - x–y x – y x = 4 - 2;
Multiplication * x*y x * y x = 4 * 2;
Division / x / y x / y x = 4 / 2;

Modulus % x mod y x % y x = 4 % 2;
Modulus (%)
• Modulus (%) returns the remainder of the division
–cout<< 3 % 2; // evaluates to 1
–cout<< 4 % 2; // evaluates to 0
–cout<< 6 % 2; // evaluates to 0
–cout<< 7 % 2; // evaluates to 1
–cout<< 8.0%2; // compiler error

• Note that both operands must be integers

• Modulus can only be used with integer types


Assignment operator =
Preliminary:
What is an expression?
An expression is any combination of variable, constants
and operators:
Examples:
2*Num1 + Num2 + 3
Num1+ 5
Num1/Num2
7–5
5
Assignment operator =
Syntax:
Variable_name = expression ;

Notes:
- It is not the equality operator
- It assigns the value of the expression to a variable ;
Examples:
Area = Side*Side ;
Average = (Num1 + Num2)/2 ;
Num = 7 ;
Assignment operator =
Rule: The left side and the right side of an assignment
operation must be of the same type
int Num1;

left-side right-side
double Num2 ; =

Num2 = 3.75 ;
What is wrong in this code?

Num1 = Num2 ;
Operator precedence
 5+Num*7
Which operation is performed first ?

 *, /, % are at higher level of preference than + and –

 If you want to impose a given operation to be executed


first, use the parenthesis
Example: (5 + Num1)* 7
Logical operators
&& logical AND
|| logical OR
! Logical NOT

When Logical operations are evaluated they can only give


true (non zero) or false (zero) value.
Logical Operators
X Y !X X && Y X || Y

True True False True True


True False False False True
False True True False True
False False True False False

36
Logical Operators

Examples

37
Comparison operators
Operator Meaning
=========================
< less than
> greater than
<= less than or equal
>= greater than or equal
== equals to
!= not equals to
Comparison operators
 Comparison operators used to form conditions that are evaluated by
the compiler to either true or false
 Example: assume num1 = 3 and num2 =5, how the compiler will
evaluate each of these expressions:
num1 < num2
num1 <= num2
num1 > num2
num1 >= num2
num1 == num2
num1 != num2
Increment/Decrement operators
Increment operator ++
This operator adds 1 to a variable

Num++ ; // is equivalent to Num = Num +1;

Decrement operator --

This operator subtracts 1 from a variable

Num-- ; // is equivalent to Num =Num -1;


Operators Precedence (2)
Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses If the parentheses are nested, the expression in the


High
innermost pair is evaluated first. If there are several
Priority pairs of parentheses “on the same level” (i.e., not nested),
they are evaluated left to right.
!, - Not, negative

*, /, or % Multiplication Division Evaluated left to right.


Modulus Arithmetic
+ or - Addition Evaluated left to right.
Subtraction
>, <, >=, <= Rational Operators
Relation
==, != Equality Operator
Equality
&& Logical AND
Logical
|| Logical OR
low
= Assignment Operator
41 Assignment
Priority
Example 1
• Given a = 2, b = 3, c = 6

• (a*2 > b && c < 10)


–True
• (c*b % 2)
–False
• (!true && true && false)
• (true || true && false)
–True
END

You might also like