0% found this document useful (0 votes)
8 views61 pages

C++ Programming Basics and Concepts

This document provides an introduction to basic concepts of C++ programming, including variables, data types, operators, and the process of converting C++ code into machine language. It outlines the roles of various components like the text editor, preprocessor, compiler, linker, and loader in program execution. Additionally, it covers syntax, programming best practices, and examples of simple C++ programs.

Uploaded by

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

C++ Programming Basics and Concepts

This document provides an introduction to basic concepts of C++ programming, including variables, data types, operators, and the process of converting C++ code into machine language. It outlines the roles of various components like the text editor, preprocessor, compiler, linker, and loader in program execution. Additionally, it covers syntax, programming best practices, and examples of simple C++ programs.

Uploaded by

sisaymiki799
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Fundamentals of

Programming
Chapter Two
Basic Concepts of C++ Programming
Chapter Objectives
Understand what variables and constants are.
List and discuss fundamental C++ data types.
Use basic mathematical, assignment, and comparison
operators.
Write, compile, debug, and run simple C++ programs.
INTRODUCTION TO C++ :
 C++ is an object oriented programming language.
 It is developed by “BJARNE STROUSTRUP” at
AT&T Bell Laboratories in [Link] initially
called the new language “C with classes “.However,
later in 1983, the name to C++.
 C++ is a superset of C. The idea of C++
comes from the increment operator ++.
 The most important facilities that C++ adds
on to C are Class, Inheritance, Function
Overloading and operator overloading.

powered by
jpwebdevelopers
Converting C++ programs in to
machine language
 Text Editor
 Preprocessor
 Compiler
 Linker
 Loader

Dec 13, 2025 ES036 QMR/RE 4


Converting C++ in to machine language
 Text Editor
 The program is written using the text editor is
known as source code.
 The source code (human readable instructions)
is saved on to the secondary storage section of
the computer system (disk) with an extension
‘.cpp’ to let the compiler know that it is written in
C++ language.
 The source code needs to be grammatically
correct
Dec 13, 2025 ES036 QMR/RE 5
Converting C++ in to machine language
 Preprocessor: A program that modifies the source
code by adding other files and performing various
text replacements
 It executes automatically before the translation period
starts.
 Examples:
 #include <iostream> adds a file called a header file
to the source code. It contains, among other things,
the prototypes for cin and cout functions.
 #define PI 3.141593 replaces all instances of PI in a
program with 3.141593.
 Compilation (step 3) follows immediately after the
preprocessing, so, none can access the modifications
made by the preprocessor
Dec 13, 2025 ES036 QMR/RE 6
Converting C++ in to machine language
 Compiler translates preprocessed source
code into an object code that contains
machine readable instructions
 The object code is saved on to the disk by the
compiler with an extension ‘.obj’ along with
the same source-code name
 This file is basically a binary file

Dec 13, 2025 ES036 QMR/RE 7


Converting C++ in to machine language
 Linker:
 scans the standard library,
 selects the needed function (precompiled) and
 upon linking them into the object file, produces an
executable file with extension ‘.exe’ (for UNIX based
system it is ‘.out’) and stores it on to the disk.
 Libraries are a collection of functions/objects
 Examples:
 The linker adds the precompiled (in binary form)
function definitions for cin, cout, etc.
 If one separates his program into more than one source
file, the object code for each source file is added.

Dec 13, 2025 ES036 QMR/RE 8


Converting C++ in to machine language

 Loader: The loader places the executable


file on to the primary storage location
(RAM) of the computer system, from
where the CPU executes the program,
instruction by instruction

Dec 13, 2025 ES036 QMR/RE 9


Converting C++ in to machine language
Text Editor
/* [Link] */
#include <iostream>
int main() Preprocessor adds iostream text
{ (prototype for cout)
cout<<"hello world\n";
return 0;
Compiler converts to machine code
}

[Link] Object code

Linker
-add library
-add cout object code
-add object code for
other functions

[Link] Executable
image

Loader copies file to RAM


and CPU executes the
program when the icon is
Program Example double-clicked, for example

Dec 13, 2025 ES036 QMR/RE 10


Converting C++ in to machine language
 Integrated Development Environment (IDE)
program:
 Itmanages all the previously discussed steps and
combines an editor, compiler, linker and debugger
into a single development environment.
 Advantage: all the pieces are designed to work
together; for example, if the compiler detects an error,
the system is switched to the editor with the file
positioned at the problem line.
 Debugger: The debugger locates the problem in
the program during the compilation time

Dec 13, 2025 ES036 QMR/RE 11


SIMPLE PROGRAM OF C++ :

 #include<iostream.h>
 int main()
 {
 cout << “HELLO WORLD”;
 return 0;
 }
 OUTPUT –
 HELLO WORLD

powered by
jpwebdevelopers
>>. The above example contains only one
function main().

>>. The only statement in above program is an


output statement.

>>. The operator << is a called the insertion or


put in operator.

>> The header file iostream.h should be


included at the beginning of all program.

powered by
jpwebdevelopers
C++ SYNTAX :
 using namespace std; --->>>[namespace]
 #include<iostream.h> --->>>[library/header inclusion]
 int main() { ---->>>[main function of the
program (int have return type)]
 cout <<“hello world”; ---->>> [cout used for display the
output]
 return 0; ---->>> [value must be return at the end of the
program.]
 }

powered by
jpwebdevelopers
//The first C++ Program
#include <iostream> //preprocessor directive
using namespace std; //”using” directive

// entry point
int main() //first function called in C++

{// function body begins with curly bracket

cout << “Hello world!"; /* printing a string on the


standard output*/

return 0; /*represents successful termination of


the program*/

} // function body ends with curly bracket


Dec 13, 2025 ES036 QMR/RE 15
Comments in C++
 Comments allow us to put some descriptions in our
code
 Compiler completely ignores them
 // this is a comment
 Starting from ‘//’ to the end of the line
 /* this is also a comment */
 Everything
between ‘/*’ and ‘*/’
 a = b /* comment inside a statement */ + c;

Dec 13, 2025 ES036 QMR/RE 16


Preprocessing Directive
 The line begins with ‘#’ characters are known as
preprocessor directives.
 #include <iostream> causes the preprocessor to
include a copy of the standard input /output file
iostream (this is a C++ system file)
 The angle bracket indicates that this file is
available at a system dependent place.
 The iostream file contains information on the
function cout used in the program

Dec 13, 2025 ES036 QMR/RE 17


Function main

 Every C++ (and C) program executes its instructions


from the function called main. This is the first
function, called in C++ environment.
 Any function in C++ has a prototype as,
Return_data_type Function_name (Argument_list_with_data_types)

Dec 13, 2025 ES036 QMR/RE 18


Curly Brackets
 The left curly bracket begins the body of each
function
 This right curly bracket ends the body of each
function.
 A function definition looks like the following:

Return_data_type Function_name(Argument_list_with_data_types)
{
Body of the function;
}

Dec 13, 2025 ES036 QMR/RE 19


Producing Output With cout
 cout
 is an ostream object
 streams output to standard output
 uses the << (output) operator
 General Form:
 cout << expression << expression;
 Note: An expression is any C++ expression
(string constant, identifier, formula or function
call)

Dec 13, 2025 ES036 QMR/RE 20


return 0
 return is a keyword for C++ (and C)
programming language
 A returned zero value is interpreted as
successful termination of the program.
 Non-zero values are interpreted as
unsuccessful termination

Dec 13, 2025 ES036 QMR/RE 21


Good Programming Approach
 Purpose of a program
 it presents the computer with a set of instructions and
 it provides the programmer a clear, easy to read
description of what it does.
 The goal of a programmer
 Create a simple and easy to read programs.
 Make the program as clear, concise and simple as
possible

Dec 13, 2025 ES036 QMR/RE 22


Good Programming Approach
 Comment the program
 Pick meaningful names for the variables
 Indentation
 Clarity
 Simplicity
 Do not write a long function
 Avoid complex logics
 Write many short statements instead of a very long
one
 Make the program as simple and easy to understand
as possible

Dec 13, 2025 ES036 QMR/RE 23


C++ Variables (Objects)
 Variables are boxes that can hold things
 Each box has a name (“identifier”)
 Size of the box depends on the “type” of things
you are planning to put there
 You have to tell the compiler in advance
(“declare”),
 Names of each of the boxes you want
 The type of things that will go in each box

Dec 13, 2025 ES036 QMR/RE 24


Why Use Types
 Computer sees everything in 1’s and 0’s
 “Type” is how we interpret these patterns
 What is 1101101?
 Integer (int): it is 109
 Character (char): it is ‘m’
 Floating point (float): it is 1.53x10-43

Dec 13, 2025 ES036 QMR/RE 25


Declaring Objects
Type Name
 Tell the compiler in  int alice;
advance  float bob, chad;
 Types  int alice = 10;
 Names
 int alice(10);
 Names can have A-Z, a- 
z, 0-9 and ‘_’ float bob, chad =
2.4;
 Case sensitive  float bob(1.5),
 Cannot start with a digit chad(2.4);
 Cannot be a reserved  Element atom;
word

Dec 13, 2025 ES036 QMR/RE 26


Identifier sum
Box 75 Built in type

Holds int type objects


Size is 32 bits (4 bytes)

Identifier atom

Outer box Na
User defined type
11
Inner boxes 22.989770

Holds Element type objects


Size is 10 bytes
Dec 13, 2025 ES036 QMR/RE 27
Some Built In Types
Data Type Range of Values Size
char -128 to 127 1 byte
int -2,147,483,648 to 2,147,483,647 4 bytes
float 6 Digits of Precision 4 bytes
±3.402823x10±38
double 15 Digits of Precision 8 bytes
± 1.797693x10±308
boolean True or False 1 byte

Dec 13, 2025 ES036 QMR/RE 28


Mixing types:
 avg = (a + b)/2;
 avg, a and b must be same type
 Exception
 It is OK to mix numerical types
 i.e. int, float, double
 Be careful not to loose precision

Dec 13, 2025 ES036 QMR/RE 29


C++ Reserved Words
asm, auto, bool, break, case, catch, char, class,
const, const_cast, continue, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern, false,
float, for, friend, goto, if, inline, int, long, mutable,
namespace, new, operator, private, protected, public,
register, reinterpret_cast, return, short, signed, sizeof,
static, static_cast, struct, switch, template, this, throw, true,
try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t, while

Dec 13, 2025 ES036 QMR/RE 30


Where to Declare
 Immediately prior to use  At the beginning

int main() int main()


{ {
… int sum;
int sum; …
sum = a + b; sum = a + b;
… …
return 0; return 0;
}
}

Dec 13, 2025 ES036 QMR/RE 31


C++ Statements
 One C++ instruction int sum(0), a(5),
that ends with a b(10);
semicolon sum = a + b;
 Can take more than
one line float temp_c(0);
 Declaration
float temp_f(78);
statements
temp_c = (temp_f –
 Assignment
statements 32)*5/9;

Dec 13, 2025 ES036 QMR/RE 32


Compound Statements
 Use { and } to group {
any number of cout << “Hello”;
statements return 0;
 This block is treated }
as one statement

Dec 13, 2025 ES036 QMR/RE 33


Concepts Presented So Far
 How to write a simple C++ program?
 What is a variable?
 How to tell the compiler what variables I
want?
 What is a C++ statement?

Dec 13, 2025 ES036 QMR/RE 34


#include <iostream> Pre-processor directives
using namespace std; “using” directives

// entry point
int main() main: single C++ statement !
{
float w_lb, w_kg; A declaration statement

cout << "Enter weight (lb): ";


cin >> w_lb;

w_kg = w_lb * 0.454; An assignment statement


cout << “Weight is " << w_kg << “kg\n";
return 0;
} // end function main
Dec 13, 2025 ES036 QMR/RE 35
#include <iostream>
// without “using namespace std;”

// entry point
int main()
{
float w_lb, w_kg;

std::cout << "Enter weight (lb): ";


std::cin >> w_lb;

w_kg = w_lb * 0.454;


std::cout << “Weight is " << w_kg << “kg\n";
return 0;
} // end function main
Dec 13, 2025 ES036 QMR/RE 36
Symbolic Constants
 Objects that won’t let you change the initial
value
 So, they must be given a value in its declaration
 As a matter of style, names are all caps
 E.g. const double PI = acos(-1.0);
 Always use to these to represent numeric values
within your program
 Or for anything that you know will not change

Dec 13, 2025 ES036 QMR/RE 37


Calculating Things
 Using calculator
 4-2+5-1 = ?
 +, - *, / and = are the operators
 3+2*5 vs (3+2)*5
 Need to consider operator precedence
 * and / have higher precedence than +, -
 C++ operators have these and more

Dec 13, 2025 ES036 QMR/RE 38


C++ Operators
 Operators take one or more input values
and produce one output value
 E.g. + , - , * , / , < , > , <= , >= , && , ||
 Operators come in three flavours
 Unary operators – take one input value
 Binary operators – take two input values
 Ternary operators – take three input values

Dec 13, 2025 ES036 QMR/RE 39


C++ Operator Map
Operators
Binary Unary
Arithmetic Logical Bitwise Comparison Arithmetic
+ - add && - and & - and < - less-than - - negate
- - sub || - or | - or > - gt.-than ++ - increment
* - mul ^ - xor <= - less-or-eq -- - decrement
/ - div >= - gt-or-eq Logical
% - mod Copy == - equal ! - negate
= != - not-equal Bitwise
+=, -=, *=, /=, %= ~ - negate
&&=, ||=, &=, |=, ^=
Pointer * , &
Dec 13, 2025 ES036 QMR/RE 40
Unary Operators
int a(9);
 Negate: -a gives -9
 Logical-invert: !a gives 0
 * and & are pointer operations (discussed
later)
 Increment: ++
 Decrement: --

Dec 13, 2025 ES036 QMR/RE 41


More Unary Expressions
int a(9), b;
 Pre-Increment :
b = ++a; b is 10 and a is 10
 Post-Increment:
b = a++; b is 9 and a is 10
 Pre-Decrement :
b = --a; b is 8 and a is 8
 Post-Decrement:
b = a--; b is 9 and a is 8

Dec 13, 2025 ES036 QMR/RE 42


Arithmetic Operators: + - * / %
 a+b, a-b, a*b, a/b
 Integer division: 11/4 gives 2
 Floating point division:
 11.0/4 gives 2.75
 Modulo operator: % (only for integers)
 11%4 gives 3
 10%5 gives 0

Dec 13, 2025 ES036 QMR/RE 43


Copy Operator (Assignment operator)
 Simple copy: a = b;
 Overwrites the left object (l-value) with the
result of the expression on the right (r-value)
 l-value must be writable
 Copy with add
a += b; is the same as a = a + b;
 Other copy-with-subtract, multiplication,
division behaves the same
a -= b; a *= b; a /= b; etc

Dec 13, 2025 ES036 QMR/RE 44


Comparison Operators
 < , > , =<, =>, ==, !=
 All yield Boolean true (1) or false (0)
 11<4 is false. 11<11 is false
 11>4 is true. 11>11 is false
 11>=11 and 11<=11 both are true
 4==4 is true. 4!=4 is false
 Don’t use floating-point values with == or !=

Dec 13, 2025 ES036 QMR/RE 45


Logical Operators
 Logical AND: &&
 exp1 && exp2 && exp3 && exp3
 Yields true if all the expressions are true
 If an expression is false, skips the rest
 Logical OR: ||
 exp1 || exp2 || exp3 || exp3
 Yields true if any expression is true
 If an expression is true, skips the rest
 These are called “short-circuit” operators

Dec 13, 2025 ES036 QMR/RE 47


Examples of Logical Operators
 (-6<0)&&(12>=10) true && true
results in true

true || false
 (3.0 >= 2.0) || (3.0 >= 4.0) results in true

 (3.0 >= 2.0) && (3.0 >= 4.0)


true && false
results in false

Dec 13, 2025 ES036 QMR/RE 48


Expressions
 A series of operators x 3 4
and their inputs 
 E.g.
5 y 3
x+3-y+5
 Evaluated from left-to- is not the same as
right x 3/ 5 4/ y 3
 Be careful with
division Correct form:
 Pay attention to (x+3)/5 + 4/(y+3)
operator precedence

Dec 13, 2025 ES036 QMR/RE 49


Operator Precedence
 Use parenthesis if you are not sure!
 Unary (++, --, !, -)
 Arithmetic (*, /, %, +, -)
 Comparison (< , <= , > , >=, ==, !=)
 Logical (&&, ||)
 Assignment (= , +=,-=,*= ,/= ,%=, etc)

Dec 13, 2025 ES036 QMR/RE 50


Expression Examples
2 3y
 2*x*x-3*y/5*y+6 2x  y 6
 Should really be 5
 2*x*x-(3*(y/5)*y)+6
2
 (2*x*x-3*y)/(5*y+6)
2x  3y
5y  6

Dec 13, 2025 ES036 QMR/RE 51


Expressions With Side Effects
 r = x + y--; is equivalent to
 r = x + y; y = y-1; (two actions!)
 r = ++x - y; is equivalent to
 x = x+1; r = x - y; (two actions!)
 Keep it simple
 Not r = --x + y++;

Dec 13, 2025 ES036 QMR/RE 52


Using Standard Utilities
 C++ compilers comes with a vast
collection of utilities: i/o, math etc
 This is called the “standard library”
 You need to:
 Includeproper header files. E.g.
#include<iostream>
 Use using namespace std; statement
 Or use std:: prefix

Dec 13, 2025 ES036 QMR/RE 53


Standard Input and Output
 Called the i/o stream objects
 #include <iostream>
 Input is usually from keyboard
 Output is usually to a console window
 cout object is the output stream (ostream)
 cin object is the input stream (istream)

Dec 13, 2025 ES036 QMR/RE 54


Producing Output With cout
 cout
 is an ostream object
 streams output to standard output
 uses the << (output) operator
 General Form:
 cout << expression << expression;
 Note: An expression is any C++ expression
(string constant, identifier, formula or function
call)

Dec 13, 2025 ES036 QMR/RE 55


//Example1 for input and output
#include <iostream>
#include <string> 1
using namespace std; 2
int main() 4.5
{ output
int i, j; 1,2,
double x; 4.5 cm
string units = “ cm”;
cin >> i >> j;
cin >> x;
cout << “output \n”;
cout << i << ‘,’ << j << ‘,’ << endl
<< x << units << endl;
return 0;
} // Input stream:

Dec 13, 2025 ES036 QMR/RE 56


Changing cout behaviour
 Use setf() and unsetf() to set following attributes
 E.g. [Link](ios::scientific);

Flag Meaning
ios::showpoint display the decimal point
ios::fixed fixed decimal notation
ios::scientific scientific notation
ios::right right justification
ios::left left justification

Dec 13, 2025 ES036 QMR/RE 57


cout Precision and justification
 With #include <iomanip> you can use
 setw(n) and setprecision(n)
 E.g.
cin >> n;
cout << setprecision(4)
<< “Sqrt with 4 digits: ” << sqrt(n)
<< endl << “Sqrt right justified: ”
<< setw(10) << sqrt(n) << endl;

Dec 13, 2025 ES036 QMR/RE 58


Characters and input with cin
 >> discards leading whitespace
 get() method is used to input whitespace
characters 45
 Example: c
int x; 39
char y; b
cin >> x >> y;
x: 45 y: ‘c’
cin >> x;
[Link](y); x: 39 y: ‘\n ’

Dec 13, 2025 ES036 QMR/RE 59


Math Functions with <cmath>
abs(x) computes absolute value of x
sqrt(x) computes square root of x, where x >=0
pow(x,y) computes xy
ceil(x) nearest integer larger than x
floor(x) nearest integer smaller than x
exp(x) computes ex
log(x) computes ln x, where x >0
log10(x) computes log10x, where x>0

Dec 13, 2025 ES036 QMR/RE 60


Trigonometric Functions
sin(x) sine of x, where x is in radians
cos(x) cosine of x, where x is in radians
tan(x) tangent of x, where x is in radians
asin(x) sine-1(x), returns angle in radians [-π/2, π/2]
acos(x) cosine-1(x), returns angle in radians [0,π]
atan(x) tan-1(x), returns angle in radians [-π/2, π/2]
atan2(y,x) tan-1(y/x), returns angle in radians [-π, π]
sinh(x) Hyperbolic sine of x
cosh(x) Hyperbolic cosine of x
tanh(x) Hyperbolic tan of x

Dec 13, 2025 ES036 QMR/RE 61


Next Step
 Chapter 3
 Control Structures
 if-else statements
 switch statements
 while and do-while loops
 for loops
 break and continue statements

Dec 13, 2025 ES036 QMR/RE 62

You might also like