0% found this document useful (0 votes)
11 views

Week03Varialbe Data Types, Operators

The document discusses C++ programming concepts including printing text, comments, preprocessor directives, functions, input/output statements, and variable data types. It provides examples and explanations of these core programming elements.

Uploaded by

mdfxksa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Week03Varialbe Data Types, Operators

The document discusses C++ programming concepts including printing text, comments, preprocessor directives, functions, input/output statements, and variable data types. It provides examples and explanations of these core programming elements.

Uploaded by

mdfxksa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Week 3

CS 131
PROGRAMMING I

2023-2024
First Program in C++:
Printing a Line of Text

You can use:


using namespace std;
cout<<“Welcome to C++”;
instead of
std::cout<<“Welcome to C++”
C++ comments
• // indicates that the remainder of each line is a comment.
• You insert comments to document your programs and to help other people
read and understand them.
• Comments are ignored by the C++ compiler and do not cause any
machine-language object code to be generated.
• A comment beginning with // is called a single-line comment
because it terminates at the end of the current line.
• You also may use comments containing one or more lines
enclosed in /* and */for multiple-lines comment.
Preprocessor directive
• A preprocessing directive is a message to the C++ preprocessor.
• Lines that begin with # are processed by the preprocessor
before the program is compiled.
• #include <iostream> notifies the preprocessor to include
in the program the contents of the input/output stream header
file <iostream>.
• This header is a file containing information used by the compiler when
compiling any program that outputs data to the screen or inputs data from
the keyboard using C++-style stream input/output.
main function
• main is a part of every C++ program.
• The parentheses after main indicate that main is a program
building block called a function.
• C++ programs typically consist of one or more functions and
classes.
• Exactly one function in every program must be named main.
• C++ programs begin executing at function main, even if main is
not the first function defined in the program.
• The keyword int to the left of main indicates that main
“returns” an integer (whole number) value.
• A keyword is a word in code that is reserved by C++ for a specific use.
• For now, simply include the keyword int to the left of main in each of
your programs.
main function
• A left brace, {, must begin the body of every function.
• A corresponding right brace, }, must end each function’s
body.
• A statement instructs the computer to perform an action.
• Together, the quotation marks and the characters between
them are called a string, a character string or a string literal.
• We refer to characters between double quotation marks
simply as strings.
• White-space characters in strings are not ignored by the compiler.
• Most C++ statements end with a semicolon (;), also known
as the statement terminator.
• Preprocessing directives (like #include) do not end with a
semicolon.
output statment
• Typically, output and input in C++ are accomplished with streams
of characters.
• When a cout statement executes, it sends a stream of characters
to the standard output stream object—std::cout—which is
normally “connected” to the screen.
• The std:: before cout is required when we use names that
we’ve brought into the program by the preprocessing directive
#include <iostream>.
• The notation std::cout specifies that we are using a name, in this case
cout, that belongs to “namespace” std.
• The names cin (the standard input stream) and cerr (the standard error
stream) also belong to namespace std.
output statement
• In the context of an output statement, the << operator is
referred to as the stream insertion operator.
• The value to the operator’s right, the right operand, is
inserted in the output stream.
• The characters \n are not printed on the screen.
• The backslash (\) is called an escape character.
• It indicates that a “special” character is to be output.
• When a backslash is encountered in a string of characters,
the next character is combined with the backslash to form
an escape sequence.
• The escape sequence \n means newline.
• Causes the cursor to move to the beginning of the next line on the
screen.
by Pearson
Education,
Inc. All Rights
Reserved.
Return Statement
• When the return statement is used at the end of
main the value 0 indicates that the program has
terminated successfully.
• According to the C++ standard, if program execution
reaches the end of main without encountering a
return statement, it’s assumed that the program
terminated successfully—exactly as when the last
statement in main is a return statement with the
value 0.
2.3 Modifying Our First C++ Program
• Welcome to C++! can be printed several ways.
Printing multiple lines
• A single statement can print multiple lines by using newline
characters.
• Each time the \n (newline) escape sequence is encountered in
the output stream, the screen cursor is positioned to the
beginning of the next line.
• To get a blank line in your output, place two newline characters
back to back.
by Pearson
Education,
Inc. All Rights
Reserved.

Printing multiple lines


2.4 Another C++ Program: Adding Integers
• The next program obtains two integers typed by a user at the
keyboard, computes the sum of these values and outputs the
result using std::cout.
• Figure 2.5 shows the program and sample inputs and outputs.
by Pearson
Education,
Inc. All Rights
Reserved.
Input statement
• A cin statement uses the input stream object cin (of
namespace std) and the stream extraction operator, >>, to
obtain a value from the keyboard.
• Using the stream extraction operator with std::cin takes
character input from the standard input stream, which is usually
the keyboard.
Receiving user inputs
• When the computer executes an input statement that
places a value in an int variable, it waits for the user
to enter a value for variable number1.
• The user responds by typing the number (as
characters) then pressing the Enter key (sometimes
called the Return key) to send the characters to the
computer.
• The computer converts the character representation of
the number to an integer and assigns (i.e., copies) this
number (or value) to the variable number1.
• Any subsequent references to number1 in this
program will use this same value.
Assignment statement
• In this program, an assignment statement adds the values of
variables number1 and number2 and assigns the result to
variable sum using the assignment operator =.
• Most calculations are performed in assignment statements.
• The = operator and the + operator are called binary operators
because each has two operands.
stream manipulators
• std::endl is a so-called stream manipulator.
• The name endl is an abbreviation for “end line” and belongs
to namespace std.
• The std::endl stream manipulator outputs a newline, then
“flushes the output buffer.”
• This simply means that, on some systems where outputs accumulate in the
machine until there are enough to “make it worthwhile” to display them
on the screen, std::endl forces any accumulated outputs to be
displayed at that moment.
• This can be important when the outputs are prompting the user for an
action, such as entering data.
Insertion operator
• Using multiple stream insertion operators (<<) in a single
statement is referred to as concatenating, chaining or cascading
stream insertion operations.
• Calculations can also be performed in output statements.
Types of program errors
• Compile or syntax error
• is caused when the compiler cannot recognize a statement

• Run-time
• E.g. division by zero

• Logical
• E.g. write addition operator instead of multiplication
Variable, Data types
and operators

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
 A C++ identifier is a name used to identify a variable, function,
class, module, or any other user-defined item. An identifier starts
with a letter A to Z or a to z or an underscore (_) ,$, followed by zero
or more letters, underscores, and digits (0 to 9).

 C++ does not allow punctuation characters such as @, !, and %


within identifiers.
 C++ is a case-sensitive programming language. Thus, Area and
area are two different identifiers in C++.

 Here are some examples of valid identifiers −


mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
 Here are some examples of invalid identifiers −
1a for a-3 A2! A*2

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename

class for return union


const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template

You can not use keyword to name identifiers (variables, functions,…)

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
 Before using a variable, you must declare it

1. Data_Type Identifier;
 int width; // width of rectangle
 float area; // result of calculating area stored in it
 char separator; // word separator
2. Data_Type Identifier = Initial_Value;
 int width = 10; // width of rectangle
 float area = 255; // result of calculating area stored in it
 char seperator = ‘,’; // word separator
3. Data_Type Identifier, Identifier, Identifier ,….;
 int width, length, temporary;
 float radius, area = 0;
 A scope is a region of the program and broadly
speaking there are three places, where variables can be
declared :
 Inside a function or a block which is called local
variables,
 In the definition of function parameters which is
called formal parameters.
 Outside of all functions which is called global
variables.
 We will learn what is a function and it's parameter in
subsequent lectures. Here let us explain what are local
and global variables.

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
©1992-2014 by Pearson Education, Inc. All Rights
Reserved.
C++ offers the programmer a rich collection of built-in as well as user defined data
types. Following table lists down seven basic C++ data types −

Type Keyword
Boolean bool
Character char The size and range of
Integer int these data types may
vary among processor
Floating point float
types and compilers
Double floating point double

Valueless void

Several of the basic types can be modified using one or more of


these type modifiers −
•Signed, unsigned, short, long
Type Typical Bit Width Typical Range

char 1byte -128 to 127 or 0 to 255

unsigned char 1byte 0 to 255


signed char 1byte -128 to 127
int 4bytes -2147483648 to
2147483647
unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to


2147483647
short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 4/8 bytes -2,147,483,648 to


2,147,483,647

signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15


digits)
long double 8/16 bytes by Pearson Education,+/-
©1992-2014 1.7e
Inc. All +/- 308 (~15
Rights
digits)Reserved.
 Base 10: 1 915 +8 -90
 Base 8: 074 0123 084
 Base 16: 0x1 0X5 0x7fab
 Base 2: 0b1101

 unsigned: 5000u 4U
 long: 123456789l 56L
 unsigned long: 536489ul
 long long : 5361254865LL 25lL

 Example :
 0xABu 0123uL 017LL
 A floating-point value contains a decimal point
 33.5 0.0 -657.983 .2 6.

 For example, the value 150.4582 is represented


in scientific notation as
 1.504582 X 102

 and is represented in exponential notation (by


the computer) as
 1.504582E+02
 This notation indicates that 1.504582 is multiplied by 10
raised to the second power (E+02)
 The E stands for “exponent”
 Char
char c;
c = 'A'; // d = 65;

 String
cout<<"string is array of char!!!";
cout<<“example of escape sequence is \n";
 Constants provide a way to define a variable
which cannot be modified by any other part in
the code
 #define: without memory consume
 const: memory consume

 #define Identifier constant_value


 #define PI 3.14
 #define ERROR "Disk error "
 #define ERROR "multiline \
message"
 #define ONE 1
#define TWO ONE + ONE
• const Data_Type Identifier = constant_value;
 const int p = 3; // const int p = 3;
 const p;
p = 3.14; // compile error
 const float p = 3.14;
 Most programs perform arithmetic calculations.
 C++ arithmetic operators (+ - * / %).
◦ The asterisk (*) indicates multiplication.
◦ The percent sign (%) is the modulus operator that will be discussed
shortly.
◦ C++ provides the modulus operator, %, that yields the remainder
after integer division.
◦ The modulus operator can be used only with integer operands.
 The arithmetic operators are all binary operators.
 Integer division (i.e., where both the numerator and the
denominator are integers) yields an integer quotient.
◦ Any fractional part in integer division is discarded (i.e., truncated)—
no rounding occurs.

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
Arithmetic operators

increment and decrement operators

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
 Arithmetic expressions in C++ must be entered into the
computer in straight-line form.
 Expressions such as “a divided by b” must be written
as a / b, so that all constants, variables and operators
appear in a straight line.
 Parentheses are used in C++ expressions in the same
manner as in algebraic expressions.
 For example, to multiply a times the quantity b + c we
write a * ( b + c ).

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
 C++ applies the operators in arithmetic expressions in a
precise sequence determined by the following rules of
operator precedence, which are generally the same as
those followed in algebra.

What is the value of:

2+3*5 ???
Is it 25 or 17

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
operator precedence

What is the operation precedence of following expressions:


• 3/4+5)-6*2
• 3/((4+5)-6)*2
• 3/(4+5)-6*2
• 3/4+(5-6)*2
 There is no arithmetic operator for exponentiation in
C++, so x2 is represented as x * x.
 Figure 2.11 illustrates the order in which the operators
in a second-degree polynomial are applied.
 As in algebra, it’s acceptable to place unnecessary
parentheses in an expression to make the expression
clearer.

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
Example

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
Example
#2

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
a=20, b=10,c=15, d=5

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
 The division of variables of type integer will
always produce a variable of type integer as
the result
Since b is declared as an integer, the
result of a/2 is 3, not 3.5
 Example
int a = 7, b;
float z;
b = a / 2; b = 3, z = 3.500000
z = a / 2.0;
cout<<"b = “<<b<<“, z =“<<z<<“\n”;
 You could only use modulus (%) operation on
integer variables (int, long, char)
o z = a % 2.0; // error
o z = a % 0; // error Modulus will result in
the remainder of a/2.
 Example
7 2
int a = 7, b, c; - a/2
b = a % 2; 6 3
integral
c = a / 2; 1
a%2
cout<<"b =“<<b<<“\n"; remainder
cout<<"c = “<<c<<“\n";
 lvalue = rvalue;
int i;
float f;
i = 2; // *&i = 2;
2 = i; // error: invalid lvalue in assignment
f = 5.6;
i = f; // i = 5;
i = -5.9; // i = -5;
 Assignment operators are used to combine the '=' operator
with one of the binary arithmetic or bitwise operators
Operator Expression Equivalent Statement Results

+= c += 7; c = c + 7; c = 16
-= c -= 8; c = c – 8; c=1
 Example :
 c = 9; *= c *= 10; c = c * 10; c = 90
/= c /= 5; c = c / 5; c=1
%= c %= 5; c = c % 5; c=4
&= c &= 2 ; c = c & 2; c=0
^= c ^= 2; c = c ^ 2; c = 11
|= c |= 2; c = c | 2; c = 11
<<= c <<= 2; c = c << 2; c = 36
>>= c >>= 2; c = c >> 2; c=2
 The if statement allows a program to take alternative
action based on whether a condition is true or false.
 If the condition is true, the statement in the body of the if
statement is executed.
 If the condition is false, the body statement is not executed.
 Conditions in if statements can be formed by using the
equality operators and relational operators summarized in
Fig. 2.12.
 The relational operators all have the same level of
precedence and associate left to right.
 The equality operators both have the same level of
precedence, which is lower than that of the relational
operators, and associate left to right.

©1992-2014 by Pearson Education, Inc. All Rights


Reserved.
©1992-2014 by Pearson Education, Inc. All Rights
Reserved.
Relational Operators - Example
Assume variable A holds 10 and variable B holds 20, then −
Operator Description Example

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition
becomes true.
!= Checks if the values of two operands are (A != B) is true.
equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand, if
yes then condition becomes true.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand, if yes then
condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of right
operand, if yes then condition becomes
true.
<= Checks if the value of left operand is less (A <= B) is true.
than or equal to the value of right
operand, if yes then condition becomes
©1992-2014 by Pearson Education, Inc. All Rights
Reserved.
true.
©1992-2014 by Pearson Education, Inc. All Rights
Reserved.
 C++ provides logical operators that are used to form
more complex conditions by combining simple
conditions. ©
19

 The logical operators are && (logical AND), || 92


-
20
(logical OR) and ! (logical NOT, also called logical 14
by
Pe
negation). ar
so
n
Ed
uc
ati
on
,
Inc
.
All
Ri
gh
ts
Re
se
rv
ed
.
Logical OR (||) Operator
 The || (logical OR) operator determines if either or both of
two conditions are true before we choose a certain path of ©
19
execution. 92
-
 Figure 5.16 is a truth table for the logical OR operator (||). 20
14
by
 The && operator has a higher precedence than the || operator. Pe
ar
so
 Both operators associate from left to right. n
Ed
 An expression containing && or || operators evaluates only uc
ati
on
until the truth or falsehood of the expression is known. Inc
,

◦ This performance feature for the evaluation of logical AND and logical .
All
OR expressions is called short-circuit evaluation. Ri
gh
ts
Re
se
rv
ed
.
 There are following logical operators supported by C++
language.
 Assume variable A holds 1 and variable B holds 0, then −

Operato Description Example


r
&& Called Logical AND operator. If (A && B) is false.
both the operands are non-zero,
then condition becomes true.
|| Called Logical OR Operator. If any (A || B) is true.
of the two operands is non-zero,
then condition becomes true.
! Called Logical NOT Operator. Use !(A && B) is true.
to reverses the logical state of its
operand. If a condition is true,
then Logical NOT operator will
make false.

You might also like