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

Lecture 02

The document provides an overview of C++ programming concepts, including the use of header files, data types, variable declaration, input/output operations, and control flow. It explains the importance of header files for code reuse and organization, as well as basic syntax for defining functions and using standard libraries. Additionally, it covers arithmetic operators, type conversion, and boolean expressions, emphasizing the structure and rules for writing effective C++ code.

Uploaded by

M T
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)
5 views

Lecture 02

The document provides an overview of C++ programming concepts, including the use of header files, data types, variable declaration, input/output operations, and control flow. It explains the importance of header files for code reuse and organization, as well as basic syntax for defining functions and using standard libraries. Additionally, it covers arithmetic operators, type conversion, and boolean expressions, emphasizing the structure and rules for writing effective C++ code.

Uploaded by

M T
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/ 53

Computer

Programming

• Course Code: CSC-113


• Course Instructor: Mehreen Tariq
• Email: [email protected]
C++ Header Files
Why Do we Use Header Files ? Header files are used in C++ so that you don’t have to write the code for every single
thing. It helps to reduce the complexity and number of lines of code. It also gives you the benefit of reusing the
functions that are declared in header files to different .cpp files and including a header file is way easier than writing
the implementations. By using a header file, you keep the program precise and focused, which makes it manageable.
What Are C++ Header Files? These are those files that store predefined functions. It contains definitions of functions
that you can include or import using a preprocessor directive #include. This preprocessor directive tells the compiler
that the header file needs to be processed prior to the compilation. For example, the <iostream> header file in C++
contains the definition of input-output functions.
Types of Header Files
o Standard library header files
o User-defined header files
• Standard library header files: These are those header files that are already present in the compiler of C++; you
just need to import them to use them.
• User-defined header files: These are those header files defined by the user and can be used by including them in
the program using #include.
Header File
We used the #include<iostream> statement to tell the compiler
to include an iostream header file library which stores the
definition of the cin and cout methods that we have used for
input and output. #include is a preprocessor directive which
import header files.
Syntax:
#include <library_name>
Namespace
• In C++, using namespace std; is used to avoid repeatedly writing std:: before standard library
functions and objects, such as cout, cin, and string.
• The C++ Standard Library is organized under the namespace std. This includes commonly used
components like std::cout, std::cin, std::string, and many others.
Without using namespace std
std::cout << "Hello, World!" << std::endl;
With using namespace std
using namespace std;
cout << "Hello, World!" << endl;
Main Function
we defined the main function as int main(). The main function is the most important part
of any C++ program. The program execution always starts from the main function. All
the other functions are called from the main function. In C++, the main function is
required to return some value indicating the execution status.

Syntax:
int main()
{
... code ....
return 0;
}
Blocks
• Blocks are the group of statements that are enclosed within { } braces.
They define the scope of the identifiers and are generally used to
enclose the body of functions and control statements.
• The body of the main function is enclosed within { }.
• Syntax:
{ // Body of the Function return 0; }

7
Semicolon symbol
• As you may have noticed by now, each statement in the above code is
followed by a ( ; ) semicolon symbol. It is used to terminate each line
of the statement of the program. When the compiler sees this
semicolon, it terminates the operation of that line and moves to the
next line.
• Syntax:
any_statement ;

8
Basic Data Types
Data Type Size Description

boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII values


int 4 bytes Stores whole numbers, without decimals
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7
decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15
decimal digits
string 1 byte Store zero or more characters or sequence of chracters.
per
character

9
Examples
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String

10
Variable Declaration
• A variable is a memory address where data can be stored and
changed.
• Declaring a variable means specifying both its name and its data type.

• Syntax
data_type Variable_Name ;

11
What Does a Variable Declaration
Do?
• A declaration tells the compiler to allocate enough memory to hold a value of
this data type, and to associate the identifier with this location.

int ageOfDog;
char middleInitial; 
float taxRate;
Variable Declaration
• All variables must declared before use.
• At the top of the program
• Just before use.
• Commas are used to separate identifiers of the same type.
int count, age;
• Variables can be initialized to a starting value when they are declared
int count = 0;
int age, count = 0;
Variable Initialization
• Syntax
data_type variable_name = value;

14
Basic Output cout
We used the cout method which is the basic output method in C++ to
output the sum of two numbers.
• Syntax:
cout << result << endl;

15
What is an Identifier?
• An identifier is the name to denote labels, types,
variables, constants or functions, in a C++
program.
• C++ is a case-sensitive language.
• Work is not work

• Identifiers should be descriptive


• Using meaningful identifiers is a good programming practice
Rules of Identifier
• Identifiers must be unique
• Identifiers cannot be reserved words (keywords)
• double main return
• Identifier must start with a letter or underscore, and be followed by zero or
more letters (A-Z, a-z), digits (0-9), or underscores
• VALID
age_of_dog _taxRateY2K
PrintHeading ageOfHorse
• NOT VALID
age# 2000TaxRate Age-Of-Dog main
What is an Expression in C++?
• An expression is a valid arrangement of variables, constants, and
operators.
• In C++, each expression can be evaluated to compute a value of a
given type

• In C++, an expression can be:


• A variable or a constant (count, 100)
• An operation (a + b, a * 2)
Assignment Operator
• An operator to give (assign) a value to a variable.
• Denote as ‘=‘
• Only variable can be on the left side.
• An expression is on the right side.
• Variables keep their assigned values until changed by another
assignment statement or by reading in a new value.
Assignment Operator Syntax
• Variable = Expression
• First, expression on right is evaluated.
• Then the resulting value is stored in the memory location of Variable on left.
Assignment Operator Mechanism
• Example:
0
int count = 0;
int starting; 12345 (garbage)
starting = count + 5; 5
Input and Output
• C++ treats input and output as a stream of characters.
• stream : sequence of characters (printable or nonprintable)
• The functions to allow standard I/O are in iostream header file or
iostream.h.
• Thus, we start every program with
#include <iostream>
using namespace std;
Keyboard and Screen I/O
#include <iostream>

input data output data

executing
Keyboard program Screen

cin cout

(of type istream) (of type ostream)


Insertion Operator ( << )
• Variable cout is predefined to denote an output stream that goes to
the standard output device (display screen).

• The insertion operator << called “put to” takes 2 operands.


Output Statements
SYNTAX

cout << Expression << Expression . . . ;

cout statements can be linked together using << operator.


These examples yield the same output:

cout << “The answer is “ ;


cout << 3 * 4 ;

cout << “The answer is “ << 3 * 4 ;


Output Statements (String constant)
• String constants (in double quotes) are to be printed as is, without the
quotes.
cout<<“Enter the number of candy bars ”;
OUTPUT: Enter the number of candy bars
• “Enter the number of candy bars ” is called a prompt.
• All user inputs must be preceded by a prompt to tell the user what is
expected.
• You must insert spaces inside the quotes if you want them in the output.
Output Statements (Expression)
• All expressions are computed and then outputted.
cout << “The answer is ” << 3 * 4 ;
OUTPUT: The answer is 12
Escape Sequences
• The backslash is called the escape character.
• It tells the compiler that the next character is “escaping” it’s typical
definition and is using its secondary definition.
• Examples:
• new line: \n
• horizontal tab: \t
• backslash: \\
• double quote \”
Newline
• cout<<“\n” and cout<<endl both are used to insert a blank line.
• Advances the cursor to the start of the next line rather than to the
next space.
• Always end the output of all programs with this statement.
Extraction Operator (>>)
• Variable cin is predefined to denote an input stream from the
standard input device (the keyboard)
• The extraction operator >> called “get from” takes 2 operands.
Input Statements
SYNTAX

cin >> Variable >> Variable . . . ;

cin statements can be linked together using >> operator.


These examples yield the same output:

cin >> x;
cin >> y;

cin >> x >> y;


How Extraction Operator works?
• Input is not entered until user presses <ENTER> key.
• Allows backspacing to correct.
• Skips whitespaces (space, tabs, etc.)
• Multiple inputs are stored in the order entered:
cin>>num1>>num2;
User inputs: 3 4
Assigns num1 = 3 and num2 = 4
C++ Data Type String
• A string is a sequence of characters enclosed in double quotes

• string sample values


“Hello” “Year 2000” “1234”

• The empty string (null string) contains no displayed characters and is


written as “”
C++ Data Type String (cont.)
• string is not a built-in (standard) type
• it is a programmer-defined data type
• it is provided in the C++ standard library
• Need to include the following two lines:
#include <string>
using namespace std;
• string operations include
• comparing 2 string values
• searching a string for a particular character
• joining one string to another (concatenation)
• etc...
Arithmetic Operators
• Operators: +, -, * /
• For floating numbers, the result as same as Math operations.
• Note on integer division: the result is an integer. 7/2 is 3.
• % (remainder or modulo) is the special operator just for integer. It
yields an integer as the result. 7%2 is 1.
• Both / and % can only be used for positive integers.
• Precedence rule is similar to Math.
Arithmetic Expressions
• Arithmetic operations can be used to express the mathematic
expression in C++:

b 2  4ac b *b  4* a *c
x( y  z ) x * ( y  z)
1
2 1 /( x * x  x  3)
x  x 3
a b ( a  b) /( c  d )
c d
Type compatibilities
• C++ allows us to convert data of one type to that of another. This is
known as type conversion.
• There are two types of type conversion in C++:
• Implicit Conversion
• Explicit Conversion (also known as Type Casting)
Type compatibilities (Implicit
Conversion)
• The type conversion that is automatically done by the compiler is known as implicit type
conversion. This type of conversion is also known as automatic conversion. It can convert
lower data type to higher data type.
• All short and char can be convert into integer. But int can’t be converted into char and short.
• Example
int x= ‘z’; Valid
char x = 2678; Invalid
• Promotes to the smallest type that can hold both values.
• If assign float to int will truncate
int_variable = 2.99; // results in 2 being stored in int_variable
• If assign int to float will promote to double:
double dvar = 2; // results in 2.0 being stored in dvar
Type compatibilities (Explicit
Conversion)
• Casting - forcing conversion by putting (type) in front of variable or expression. Used to insure
that result is of desired type. Used for converting higher data type to lower
• Example: If you want to divide two integers and get a real result you must cast one to double so
that a real divide occurs and store the result in a double.
int r;
r = 5/2; not valid
r = (float) 5/2; valid
e.g. x= int(7.5) covert it into 7. truncate 0.5.
Simple Flow of Control
• Three processes a computer can do:
• Sequential
expressions, insertion and extraction operations
• Selection (Branching)
if statement, switch statement
• Repetition/Iteration (Loop)
while loop, do-while loop, for loop
bool Data Type
• Type bool is a built-in type consisting of just 2 values, the constants
true and false
• We can declare variables of type bool
bool hasFever; // true if has high temperature
bool isSenior; // true if age is at least 55
• The value 0 represents false
• ANY non-zero value represents true
Boolean Expression
• Expression that yields bool result
• Include:
6 Relational Operators
< <= > >= == !=
3 Logical Operators
! && ||
Relational Operators
are used in boolean expressions of form:
ExpressionA Operator ExpressionB
temperature > humidity
B * B - 4.0 * A * C > 0.0
abs (number) == 35
initial != ‘Q’
• Notes:
o == (equivalency) is NOT = (assignment)
o characters are compared alphabetically. However, lowercase letters are higher ASCII value.
o An integer variable can be assigned the result of a logical expression
Relational Operators
int x, y ;
x = 4;
y = 6;
EXPRESSION VALUE
x<y true
x+2<y false
x != y true
x + 3 >= y true
y == x false
y == x+2 true
y=x+3 7
y=x<3 0
y=x>3 1
Logical Operators
are used in boolean expressions of form:
ExpressionA Operator ExpressionB
A || B (true if either A or B or both are true. It is false otherwise)
A && B (true if both A and B are true. It is false otherwise)

Notes:
Highest precedence for NOT, AND and OR are low precedence.
Associate left to right with low precedence. Use parenthesis to override priority or for clarification
• x && y || z will evaluate “x && y ” first
• x && (y || z) will evaluate “y || z” first
Logical Operators
int age ;
bool isSenior, hasFever ;
float temperature ;
age = 20;
temperature = 102.0 ;
isSenior = (age >= 55) ; // isSenior is false
hasFever = (temperature > 98.6) ; // hasFever is true

EXPRESSION VALUE
isSenior && hasFever false
isSenior || hasFever true
!isSenior true
!hasFever false
Precedence Chart
• ++, --, ! Highest

• *, /, %
• + (addition), - (subtraction)
• <<, >>
• <, <=, >, >=
• ==, !=
• &&
• ||
•= Lowest
Boolean Expression (examples)
taxRate is over 25% and income is less than $20000

temperature is less than or equal to 75 or humidity is less than 70%

age is between 21 and 60

age is 21 or 22
Boolean Expression (examples)
(taxRate > .25) && (income < 20000)

(temperature <= 75) || (humidity < .70)

(age >= 21) && (age <= 60)

(age == 21) || (age == 22)


Constants
• Syntax: const type identifier = value;
• Ex: const double TAX_RATE = 0.08;
• Convention: use upper case for constant ID.
Const….

Const Variable initialization Traditional Variable initialization


#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {
const int a= 10; int a= 10;
a = 20; Error a = 20;
cout<<"a is "<<a; cout<<"a is "<<a;
return 0; return 0;
} }
Why use constants?

• Clarity: Tells the user the significance of the number. There may be
the number 0.08 elsewhere in the program, but you know that it
doesn’t stand for TAXRATE.
• Maintainability. Allows the program to be modified easily.
• Ex: Program tax compute has const double TAXRATE=0.0725. If taxes rise to
8%, programmer only has to change the one line to const double
TAXRATE=0.08
• Safety: Cannot be altered during program execution
Summary:
Second week content, I forget to mention lecture content
yesterday, so that I mentioned here as whole.
C++ Header Files, Standard library header files, User-defined
header files, Main Function, Structure of C++, Data Types, What
Does a Variable Declaration Do?, What is an Identifier? ,
Expression in C++?, Assignment Operator, Operators in C++,
Keyboard and Screen I/O, Output Statements (String constant),
Escape Sequences, Arithmetic Expressions

You might also like