0% found this document useful (0 votes)
20 views36 pages

FPCPP C1

This document provides an introduction to programming in C++. It discusses how C++ was built on C and includes object-oriented programming features like classes, inheritance, and polymorphism. It also covers templates, compilation, execution of C++ programs, and basic elements like comments, identifiers, and data types.
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)
20 views36 pages

FPCPP C1

This document provides an introduction to programming in C++. It discusses how C++ was built on C and includes object-oriented programming features like classes, inheritance, and polymorphism. It also covers templates, compilation, execution of C++ programs, and basic elements like comments, identifiers, and data types.
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/ 36

1

FUNDAMENTALS OF

1
PROGRAMMING IN C++
INTRODUCTION
C++ and It’s Features 2
• C++ was built on the older language C, and there's a lot of
C code still around.
• C++ embraces the strong quality of C like efficiency and
portability.
• Beside that C++ includes more strong qualities like OOP
features, exception handling and templates.
• Templates are a relatively new addition to C++.
• They allow us to write generic classes and functions that
work for several different data types.
• E.g. demonstrate templates using max function design to
support different data types.
C++ and It’s Features 3
• C had one major problem, it was a procedural-oriented programming language.
• Procedural-oriented programming
• the operations are separated from the data they use.
• lacks reusability, makes debugging complicated and inconsistency are major problems of this paradigm.
• C++ is mainly meant to resolve C’s problem, C++ supports object-oriented programming.
• data abstraction, that is, the creation of classes to describe objects
• data encapsulation for controlled access to object data
• inheritance by creating derived classes (including multiple derived classes)
• polymorphism (Greek for multiform), that is, the implementation of instructions that can have varying
effects during program execution.
Programs from conception to execution 4
• C++ is a high-level programming language that allows a software engineer to efficiently code a
program.
• A program is a set of instruction, written using a programming language, to solve a specific
problem.
• Programming language can be high-level, assembly or low-level.
• Programs starts out as an idea in the programmers mind.
• He writes down his idea in paper, it becomes algorithm.
• Then code the algorithm using a programming language it becomes a program.


� Discuss program Vs Algorithms

Programs from conception to execution 5
• C++ programs are written in a high-level language using letters, numbers, and the other symbols
you find on a computer keyboard.
• The writing is done using stand alone editors or IDE(integrated development environment).
• Computers actually execute a very low-level language called machine code (a series of numbers).
• Therefore, how letters, numbers and symbols are understood?

• 💡 a program can be used, it must undergo several transformations called compilation and
So, before
execution.
• Compilation is a process of translating a program written in high-level programming language into its
equivalent machine(or object) code.
• Execution is a process of assigning computational resources to the executable machine code and
perform the operations specified on the data provided.
Compilation and executions 6
1. Editors: we use this to create and save the source code to
source file. Modern compilers have integrated editors.
2. Loaders: prior to compilation header files are loaded to
the source file using loader.
3. Compilers: are software, designed to translate a source
file to object file containing machine code.
4. Linkers: finally, the linker combines the object file with
other modules to create the executable file.
Note: compilation starts from the very first line in the source
code, while execution starts from the main function.
Anatomy of C++ programs 7
• The first line, #include <iostream>, is called preprocessor
#include <iostream> directive. It directs the preprocessor to include all the
functionalities from iostream library.
using namespace std;
• E.g. cin and cout functions
int main() • The second line, using namespace std, is a using directive
{ used to allow direct access to the names(key-words)
reserved by C++ from std dictionary.
cout<< “Hello C++!" << endl;
• E.g. if, else, int, for…
return 0; • The third line, int main(), indicates where program
} execution starts from.
• Note: C++ is case-sensitive.
Elements of programming 8
1. Comment: provides the programmer with a clear, easy-to-read description of how and what the
program does.
 Comments are not going to be compiled and executed.
 Mostly comments contain:
 Headings: tells what the program does and how.
 Author: Credits for the programmer.
 File formats, References, Error handling techniques and etc.
 C++ supports two types of comments
i. Single line comment started using double slash (//) and spans a single line
ii. Multiple line comment started using (/*) and spans several lines and terminated with (*/)

// This is single line comment /* This is multiple line


comment style */
Cont… 9
2. Identifiers: are names used in program to designate variables and functions.
 We can not arbitrarily give names to variables and functions in C++, instead there are rules to follow
while naming:
i. C++ key-words can not be used as an identifiers.
ii. The first character of an identifier must be a letter or underscore.
iii. Identifiers can contain a series of letters, numbers, or underscore characters ( _ ).
iv. German umlauts and accented letters are invalid.
v. C++ is case sensitive; that is, upper and lowercase letters are different.
vi. There are no restrictions on the length of a name

Valid identifiers Invalid identifiers


1. Num1 1. $num
2. num1 2. 12num
3. _num1 3. #num
4. NUM 4. -12num
Cont… 10
3. Data types: A program can use several data to solve a given problem, for example, characters,
integers, or floating-point numbers.
 Since a computer uses different methods for processing and saving data, the data type
must be known.
 Data types define:
i. the internal representation of the data, and
ii. the amount of memory to allocate.
 Data types can be:
i. Built-in like int, float, char, bool…
ii. User defined like string, pointers, structure and etc.
Cont… 11
 Summary of built-in (fundamental) data types
Built-in data types Size Range
char 1 byte ASCII
Characters
wchar_t 2 byte Unicode
Short -32,768 to +32,767
2 byte
unsigned short 0 to 65,535
-32,768 to +32,767
Int 2 or 4 byte -2,147,483,648 to +2,147,483,647
Integers
unsigned int 2 or 4 byte 0 to 65,535
0 to 4,294,967,295
long -2,147,483,648 to +2,147,483,647
4 byte
unsigned long 0 to 4,294,967,295

 For 16 bit computers int is equivalent with short and for 32 bit computers int is
equivalent to long.
Cont… 12
 Summary of built-in (fundamental) data types
Data type Size Range Precision

float 4 bytes ±1.18 x 10-38 to ±3.4 x 1038 9 digits

Floating points double 8 bytes ±2.23 x 10-308 to ±1.80 x 10308 18 digits

Long
16 bytes ±3.36 x 10-4932 to ±1.18 x 104932 36 digits
double

 Floating points used for storing numbers with fractions.


Cont… 13
4. Variables: C++ allows you to store values in variables at global or local scope.
 Each variable is identified by
 Identifiers- names of a variable
 Data types- tells C++ what data is going to be stored in it.
 Variables must be declared or initialized before use.
 Declaring a variable means introducing it to the compiler.
 The process of declaring or introducing a variable to the compiler is called variable declaration.
 Syntax of variable declaration:
Type Name;
int age; char gender; Int, float, string, bool, char…
float c_gpa;
string name;
int pin; string ID; Identifier or name you give …
Cont… 14
 Initialization is a process of assigning value to a variable while declaring it.
 Values are assigned left to right using assignment operator.
 Syntax of variable initialization:
Type Name = value;
Value can be any constant…

Initialization
Or other variable…
int age=28; char gender=‘M’;
float c_gpa=3.81;
string name=“Shewangizaw Melaku”;
int pin=age; string ID=1888;
Cont… 15
5. Constants: are also called literals.
 Constants can not be declared and assigned values later.
 Constants must be initialized.
 Constants are created using “const” key-word and can not be modified.
 Syntax:
 Major categories of constants:
const Type Name = value;
 Boolean constant: are initialized with true or false as a value.
 Integral constant: are initialized with integers as a value.
 Decimal, Octal or Hexadecimal constants.
 Floating point constants: are initialized with numbers with fractions as a value.
 Character constants: are initialized with characters enclosed by ‘’ as a value.
 String constants: are initialized with sequence of characters enclosed by “” as a value.
Cont… 16
6. Operators: Operators are symbols that perform operations on variables and values. There are 6-
types of operators
1. Arithmetic Operators: used to perform arithmetic operations on variables and data.
Operator Operation
+ Addition

- Subtraction

* Multiplication

/ Division

Modulo Operation (Remainder


%
after division)
Cont… 17
2. Assignment Operators: used to assign values to variables.

Operator Example Equivalent to


= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;
Cont… 18
3. Relational Operators: used to check the relationship between two operands.

Operator Meaning Example


== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true


Cont… 19
4. Logical Operators: used in decision making

Operator Example Meaning

Logical AND.
&& expression1 && expression2
True only if all the operands are true.

Logical OR.
|| expression1 || expression2
True if at least one of the operands is true.

Logical NOT.
! !expression
True only if the operand is false.
Cont… 20
5. Bitwise Operators: used to perform operations on individual bits. They can only be used alongside char and int
data types.

Operator Description

& Binary AND

| Binary OR

^ Binary XOR

~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right


Cont… 21
6. Other Operators
Operator Description Example
sizeof returns the size of data type sizeof(int); // 4
string result = (5 > 0) ? "even" :
?: returns value based on the condition
"odd"; // "even"

& represents memory address of the operand &num; // address of num

. accesses members of struct variables or class objects s1.marks = 92;

-> used with pointers to access the class or struct variables ptr->marks = 92;

<< prints the output value cout << 5;


>> gets the input value cin >> num;
Expressions 22
 C++ expression consists of operators, constants, and variables which are arranged according to
the rules of the language.
 It can also contain function calls which return values.
 An expression can consist of one or more operands, zero or more operators to compute a value.
 Every expression produces some value which is assigned to the variable with the help of an
assignment operator.
 Constant expressions
 Integral expressions
 Float expressions
 Pointer expressions
 Relational expressions
 Logical expressions
 Bitwise expressions
Control Statements 23
 Statements are individual instructions of a program terminated with semi-colon.
 Control statements used to change the control flow of a program with branching statements and
looping statements.
1. Branching statements cause one section of code to be executed or not, depending on a conditional clause.
1. If statements
2. If-else statements
3. Nested if-else statements
4. Switch statement
5. Conditional operators (cond? true : false)
2. Looping statements are used to repeat a section of code a number of times or until some condition occurs.
1. For-loop
2. While-loop
3. Do-while loop
4. Continue and break
Arrays and Strings 24
 An array is a data structure ( a runtime memory management technique) used to process a collection
of data all of which are of the same type.
 Properties of arrays:
 Static
 Contiguous
 Zero-bound
 Index oriented access
 homogenous
 Declaring arrays:
 Syntax: datatype arrayName [size of the array] ;
 Initializing arrays:
 Syntax: datatype arrayName [ ] = {data1, data2, data3, …};
 Types of arrays:
 One dimensional, two dimensional and multi dimensional arrays
… 25
 Strings are data structures designed to store words or texts.
 In C++ strings can be defined using:
 C-string variable- array of characters
 String class
 Declaring arrays:
 Syntax: datatype arrayName [size of the array] ;
 Initializing arrays:
 Syntax: datatype arrayName [ ] = {data1, data2, data3, …};
C-strings 26
 C-strings are old fashioned C ways of handling strings as array of characters.
 Example:
char name[20];
 Note:
 This maximum size of 20 characters is not required to be always fully used.
 It may be lesser, therefore a convention to indicate end of string called null character (‘\0’) is
applied.
 Example: we could store “Hello” or “Studying C++” in the following ways.
Initializing C-strings 27
 Two ways of initializing C-strings are:
char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char mystring [] = "Hello";
 On the first, ‘\0’ must be added explicitly by the programmer just like ordinary array initialization,
 On the second, ‘\0’ will be implicitly added by the compiler.
 Note: the above two techniques are legal only during initialization of a C-string.
mystring[] = “this is an error”;
mystring[] = {‘E’, ‘r’, ‘r’, ‘o’,
’r’, ’\0’}
Assigning C-strings 28
 One way of assigning to C-strings is:
mystring[0] = 'H';
mystring[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0’;
 But this way is too impractical,
 therefore predefined functions from cstring library will be more helpful in manipulating C-strings
… 29
 String copy (strcpy) function:
strcpy ( string1 , string2 );
 This copies the content of string2 into string1.
 String2 can be either an array, a pointer, or a constant string.
 Hence, assigning the constant string "Hello" to mystring will be:
strcpy (mystring, "Hello");
 C-strings can also directly assigned from the user via the input stream ( cin ) during program
execution.
 Syntax:
cin.getline ( char mystring [], int length , char delimiter = ' \n');
 Where:
 Length is size of the string and delimiter is a character to mark end of inputting.
Other functions… 30

Function Purpose
strcpy(s1, s2); Copies string s2 into string s1.

strcat(s1, s2); Concatenates string s2 onto the end of string s1.

strlen(s1); Returns the length of string s1 without the null character.

strcmp(s1, s2); Returns 0 if s1 and s2 are the same; -1 if s1<s2; 1 if s1>s2.

strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.

strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1


String class 31
 The library called string, which is part of the "Standard Template Library" in C++, contains a
class called string
 Strings are declared as regular variables (not as arrays), and they support:
 the assignment and comparison operators (=, ==, !=, >= and etc)
 the + operator for concatenation
 a variety of other member functions.
 Declaration:
Syntax: string stringName;
 Initialization:
string fName = “Menelik”;
 Assignment: assume we have a declaration, string fName;
fName = “Taytu”; or fName(“Taytu”);
Manipulating string objects 32
 Standard comparison operators can be applied:
if (s1 == s2)
cout << "The strings are the same";
if (s1 < s2)
cout << "s1 comes first lexicographically";
 The ordering on strings is a lexicographical ordering, which goes by ASCII values of the
characters.
… 33
 The + operator is overloaded in this library to perform string concatenation.
 It takes two strings,
 concatenates them,
 and returns the result.
 Example:
string s1 = “Atse";
string s2 = “Menelik";
string s3;
s3 = s1 + “ “ + s2; // s3 is now “Atse Menelik"
Input and output 34
 The string library also includes versions of the insertion and extraction operators, for use with
string objects.
 The insertion operator is used as with any other variable, and it will print the contents of the
string:
string s1 = "Hello, world";
string s2 = "Goodbye, ";
cout << s1; // prints "Hello, world"
cout << s2 + " now";// prints "Goodbye, now"
 The extraction operator, like the one for c-strings, will skip leading white space, then read up to
the next white space (i.e. one word only):
string s3;
cin >> s3; // will read one word
… 35
 To read more than one word, use getline similar with c-strings,
 but the syntax is a little different.
string addr; // string object
getline(cin, addr);
// reads up to newline, for string object
getline(cin, addr, `,');
// reads up to comma, for string object
 For the string object version of getline,
 the first parameter is the input stream (like cin),
 the second is the string object,
 and the third optional parameter is the delimiter.
 Note: you don't need a size parameter.
Reading… 36

Read and practice other


string class member
functions!

You might also like