Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Programming For Engineers Lecture 02

This document provides an introduction to some key concepts in C++ programming: 1. It discusses different variable types in C++ including bool, char, integers, floating point numbers, and examples of each. 2. It explains the concept of memory and how variable names correspond to locations in computer memory, with each variable having a name, type, size and value. Assigning a new value to a variable replaces the previous value. 3. It provides an overview of some basic C++ programs, demonstrating how to print text to the screen using cout and escape sequences like newline. Multiple lines can be printed with one statement using newlines.

Uploaded by

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

Programming For Engineers Lecture 02

This document provides an introduction to some key concepts in C++ programming: 1. It discusses different variable types in C++ including bool, char, integers, floating point numbers, and examples of each. 2. It explains the concept of memory and how variable names correspond to locations in computer memory, with each variable having a name, type, size and value. Assigning a new value to a variable replaces the previous value. 3. It provides an overview of some basic C++ programs, demonstrating how to print text to the screen using cout and escape sequences like newline. Multiple lines can be printed with one statement using newlines.

Uploaded by

Malik Adnan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

What we have learned ?

• High level PL…?


• Low level PL...?
• Spaghhetti Code…?
• General purpose Programming Language…?
• System Programming…?
• #include…?
• Cout…?
• Case sensitivity…?
Train your mind……….!!!
Introduction to C++ Programming

• The C++ language facilitates a structured and disciplined approach to


computer program design

• Following are several examples that illustrate many important


features of C++. Each example is analyzed one statement at a time.
1 // Fig. 1.2: fig01_02.cpp
Outline
2 // A first program in C++
Comments
3 #include <iostream> Written between /* and */ or following a //
Improve program readability and do not cause the
4
computer to perform any action 1.19 Printing a line of text
5 int main()

6 {
preprocessor directive
7 std::cout << "Welcome to C++!\n"; Message to the C++ preprocessor
Lines beginning with # are preprocessor directives
8
#include <iostream> tells the preprocessor to
9 return 0; C++
// indicate that program programs
include
ended the contain of
contents
successfully onetheorfile
more functions, exactly
<iostream>, which
one of which must be main
includes input/output operations (such as printing to
10 } Parenthesis
the screen).used to indicate a function
int means that main "returns" an integer value.
More in Functions topics
Welcome to C++!
Prints the string of characters contained between the
return is one a way toquotation
exit a marks.
function. Left brace { begins the body of every function
return 0, in this case,The entire
means line, including std::cout, the <<
that and a right brace } ends it
the program terminatedoperator,
normally.the string "Welcome to C++!\n" and
the semicolon (;), is called a statement.

All statements must end with a semicolon.

 2000 Deitel & Associates, Inc. All rights


A Simple Program:
Printing a Line of Text
• std::cout
• standard output stream object
• “connected” to the screen
• we need the std:: to specify what "namespace" cout belongs
to
• we shall remove this prefix with using statements

• <<
• stream insertion operator
• value to the right of the operator (right operand) inserted into
output stream (which is connected to the screen)
std::cout << " Welcome to C++!\n"

•\
• escape character
• indicates that a “special” character is to be output
A Simple Program:
Printing a Line of Text (II)
Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.

• There are multiple ways to print text


• Following are more examples
1 // Fig. 1.4: fig01_04.cpp
Outline
2 // Printing a line with multiple statements

3 #include <iostream>

4 1. Load <iostream>
5 int main()

6 { 2. main
7 std::cout << "Welcome ";

8 std::cout << "to C++!\n"; 2.1 Print "Welcome"


9

10 return 0; // indicate that program ended successfully


2.2 Print "to C++!"
11 }

2.3 newline
Welcome to C++!

Unless new line '\n' is specified, the text continues 2.4 exit (return 0)
on the same line.

 2000 Deitel & Associates, Inc. All rights


1 // Fig. 1.5: fig01_05.cpp

2 // Printing multiple lines with a single statement


Outline
3 #include <iostream>

4 1. Load <iostream>

5 int main()
2. main
6 {

7 std::cout << "Welcome\nto\n\nC++!\n";


2.1 Print "Welcome"
8

9 return 0; // indicate that program ended successfully 2.2 newline

10 }
2.3 Print "to"

Welcome
2.4 newline
to

C++!
2.5 newline

Multiple lines can be printed with one


statement 2.6 Print "C++!"

2.7 newline

 2000 Deitel & Associates, Inc. All rights 2.8 exit (return 0)
using statements
• eliminate the need to use the std:: prefix
• allow us to write cout instead of std::cout
• at the top of the program write
using std::cout;
using std::cin;
using std::endl;
to use those functions without writing std::
The keyword using technically means, use this whenever you can.
This refers, in this case, to the std namespace. So whenever the
computer comes across cout, cin, endl or anything of that matter, it
will read it as std::cout, std::cin or std::endl.
How do addressing works in a housing society ?
Memory Concepts
• Variable names correspond to locations in the
computer's memory.
• Every variable has a name, a type, a size and a value.
• Whenever a new value is placed into a variable, it replaces the
previous value - it is destroyed
• reading variables from memory does not change them
• A visual representation

integer1 45
C++ Variable Types

• A variable provides us with named storage that our programs can


manipulate. Each variable in C++ has a specific type, which
determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of
operations that can be applied to the variable.

• The name of a variable can be composed of letters, digits, and the


underscore character. It must begin with either a letter or an
underscore. Upper and lowercase letters are distinct because C++ is
case-sensitive −
There are following basic types of variable in
C++
Sr.No Type & Description

1 bool
Stores either value true or false.

2 char
Typically a single octet (one byte).

3 int
The most natural size of integer for the machine.

4 float
A single-precision floating point value.

5 double
A double-precision floating point value.
typedef Declarations
• You can create a new name for an existing type using typedef. Following is the simple
syntax to define a new type using typedef −

• typedef type newname;


• For example, the following tells the compiler that feet is another name for int −

• typedef int feet;


• Now, the following declaration is perfectly legal and creates an integer variable called
distance −

• feet distance;
Enumerated Types
• An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each
enumerator is a constant whose type is the enumeration.

• Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is −

• enum enum-name { list of names } var-list;


• Here, the enum-name is the enumeration's type name. The list of names is comma separated.

• For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is assigned the value
"blue".

• enum color { red, green, blue } c;


• c = blue;
• By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and so on. But you can give a name, a
specific value by adding an initializer. For example, in the following enumeration, green will have the value 5.

• enum color { red, green = 5, blue };


• Here, blue will have a value of 6 because each name will be one greater than the one that precedes it.
The following table shows the variable type, how much memory it takes to store the
value in memory, and what is maximum and minimum value which can be stored in
such type of variables.
Type Typical Bit Width Typical Range
char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255


signed char 1byte -127 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 Range 0 to 65,535

signed short int Range -32768 to 32767


long int 4bytes -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 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character


Following is the example, which will produce correct
size of various data types on your computer.
• #include <iostream>
• using namespace std;

• int main() {
• cout << "Size of char : " << sizeof(char) << endl;
• cout << "Size of int : " << sizeof(int) << endl;
• cout << "Size of short int : " << sizeof(short int) << endl;
• cout << "Size of long int : " << sizeof(long int) << endl;
• cout << "Size of float : " << sizeof(float) << endl;
• cout << "Size of double : " << sizeof(double) << endl;

• return 0;
•}

sizeof() operator to get size of various data types.


Another Simple Program:
Adding Two Integers
• Variables
• location in memory where a value can be stored for use by a
program
• must be declared with a name and a data type before they can be
used
• Must appear before variable is used
• Some common data types are:
• int - integer numbers
• char - characters
• double - floating point numbers
• Example: int myVariable;
• Declares a variable named myVariable of type int
Example: int variable1, variable2;
• Declares two variables, each of type int
Another Simple Program:
Adding Two Integers (II)

• >> (stream extraction operator)


• When used with cin, waits for user to input a value and stores the value in the variable to
the right of the operator.
• user types number, then presses the Enter (Return) key to send the data to the computer
• Example:
int myVariable;
cin >> myVariable;
• waits for user input, then stores input in myVariable

• = (assignment operator )
• assigns value to a variable
• binary operator (has two operands)
sum = variable1 + variable2;
Addition operator
Program
Code
Write a program to add three numbers
And show its output on screen
Solve following
• 2+3*4 = 2+12 = 14. Note that the multiplication is carried out before the addition.
• (2+3)*4 = 5*4 = 20. You use parentheses to specify that the addition be carried out first.
• 10 - 4 - 2 = 6 - 2 = 4. You carry out the subtractions working from left to right.
• 10 - (4-2) = 10-2 = 8. You use parentheses to carry out the rightmost subtraction first, which
alters the answer.
• 12/3+3 = 4+3 = 7. Division comes first.
• 12/(3+3) = 12/6 = 2. The parentheses indicate that you want the addition to be carried out first.
• 2^3*3 = 2*2*2*3 = 24. The power is evaluated first, and the result is multiplied with 3.
• 2^(3*3) = 2^9 = 2*2*2*2*2*2*2*2*2 =512. The parentheses indicate that the exponent is the
product 3*3=9.
• 12/2*3 = 6*3 = 18. Multiplication and division have the same precedence, and we work from left
to right.
• 12/2/3 = 6/3 = 2. Again, we work from left to right.
• 18/3^2 = 18/9=2. The power has a higher priority than the division, and is evaluated first. Note
that 3^2 means 3*3, but if we replace 3^2 with 3*3 we get a different result: 18/3*3 = 6*3 = 18.
• (18/3)^2 = 6^2 = 36. The parentheses indicate that the base equals 18/3=6.
Arithmetic

• Arithmetic calculations are used in most programs


• special notes:
• use * for multiplication and / for division
Integer division: 9/5 = 1
• integer division truncates remainder
7 / 5 evaluates to 1
Floating-point division:
• modulus operator returns the remainder
7 % 5 evaluates to 2
9.0/5.0 = 1.800000
Mixed division: 9.0/5 =
• Operator precedence
• some arithmetic operators act before others (i.e., multiplication before addition)
1.800000
• be sure to use parenthesis when needed
• Example: Find the average of three variables a, b and c
• do not use: a + b + c / 3
• use: (a + b + c ) / 3
Compute quotient and remainder
by writing a C++ program
Relational Operators
• In C++ Programming, the values stored in two variables can be
compared using following operators and relation between them can
be determined.
• Various C++ relational operators available are-
• Operator, Meaning
> ,Greater than
>= , Greater than or equal to
== , Is equal to
!= , Is not equal to
< , Less than or equal to <= , Less than [/table]
Arithmetic (II)

• Arithmetic operators:
C ++ o p e ra tio n Arith m e tic Alg e b ra ic C ++ e xp re ssio n
o p e ra to r e xp re ssio n
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y

Modulus % r mod s r % s

• Rules of operator precedence:


Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the


expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Evaluated second. If there are several, they re
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
Decision Making: Equality and Relational Operators

• if structure - decision based on truth or falsity of condition. If condition met execute, otherwise ignore.
• Equality and relational operators:
Standard algebraic equality C++ equality Example Meaning of
operator or or relational of C++ C++ condition
relational operator operator condition

Relational operators

> > x>y x is greater than y


< < x<y x is less than y
>= x >= y x is greater than or equal to
>_ y
<_ <= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
= != x != y x is not equal to y
• These operators all have lower precedence than arithmetic operators
• C++ Relational Operators are used to compare values of two variables.
Here in example we used the operators in if statement.

• Now if the result after comparison of two variables is True, then if


statement returns value 1.

• And if the result after comparison of two variables is False, then if


statement returns value 0.
Write a program which determines
If two read numbers are equal or not
Program Code
ELIGIBILITY TO BE A VOTER in
Pakistan
• A person, who is a citizen of Pakistan
• is not less than 18 years of age on the first day of January of the year
in which the rolls are prepared or revised,
• is not declared by a competent court to be of unsound mind
• and is or is deemed to be a resident of an electoral area,
• Only citizens registered on the Electoral Rolls are eligible to cast their
votes.
• can get him/herself enrolled as a voter in that electoral area.
How can we make such a C++ program to
determine Voter eligibility???

Using C++ Logical Operator


C++ Logical Operator

• Logical Operators are used if we want to compare more than one


condition.

• Depending upon the requirement, proper logical operator is used.


Table shows us the different C++ operators
available.

Name of the
Operators Type
Operator
AND
&& Binary
Operator
|| OR Operator Binary
! NOT Operator Unary
C++ Program Logic
ELIGIBILITY TO BE A VOTER in
Pakistan
• Are you a citizen of Pakistan?
• is your age not less than 18 years on the first day of January of the
year in which the rolls are prepared or revised,
• Are you declared by a competent court to be of unsound mind
• Are you a resident of an electoral area,
• Are you registered on the Electoral Rolls are eligible to cast their
votes.
• You are enrolled as a voter in that electoral area ?
Complete code to be written on your lecture pad and personalize all
code

You might also like