SlideShare una empresa de Scribd logo
1 de 66
University of Gondar
Institute of Technology
Department of Computer Engineering
Course name: intermediate computer programming
Course code: CoEng2111
Course instructor: Wondimu B.
Email: wondimubantihun2005@gmail.com
1
 Review of C++ Basics
 Arrays and Strings
◦ Introduction to Array
◦ Implementing array
◦ Multidimensional array
◦ Using arrays with functions
◦ Recursion functions
◦ Strings and the cstring.h library
◦ String output formatting
2
 C++ is a statically-typed, compiled, general
purpose, case-sensitive, multi-paradigm,
intermediate-level programming language.”
 In simple terms, C++ is a sophisticated, efficient,
and general-purpose programming language
based on C. It was developed by Bjarne
Stroustrup in 1979.
 Many of today’s operating systems, system drivers,
browsers, and games use C++ as their core
language. This makes C++ one of the most
popular languages today.
 In any language there are some fundamentals you need to know before you can
write even the most elementary programs. In this section, we will discuss and
review some of C++ basics.
◦ Basic program constructions
◦ Variables
◦ Data types
◦ Input/output
◦ Operators
◦ Data conversion and
◦ library functions
3
4
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Let’s look at a very simple C++ program. this program is called hello_world, so
its source file is hello_world.cpp. It simply prints a sentence on the screen.
5
 A First Program – hello_world.cpp
// Program: Display greetings
// This is Comment.
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!" << endl;
return 0;
}
Preprocessor
directives
Insertion
statement
Ends executions
of main() which ends
program
Comments
Function
named
main()
indicates
start of
program
Provides simple access
6
Fig. shows how C++ program is executed
7
 In programming, a variable is a container (storage area) to hold data.
 To indicates the storage area, each variable should be given a unique name
(identifier).
Rules for naming a variable (identifiers)
 It is a name given to any program element.
 The elements might be variables, functions, arrays, structures, or classes.
 The general rules for naming variables are:
◦ A variable name can only have alphabets, numbers, and the underscore.
◦ A variable name cannot begin with a number.
◦ Names are case sensitive (myVar and myvar are different variables)
8
◦ Names cannot contain whitespaces or special characters like !, #, %, etc.
◦ A variable name cannot be a keyword. Reserved words (like C++ keywords,
such as int) cannot be used as names.
◦ Note: We should try to give meaningful names to variables. For example,
first_name is a better variable name than fn.
 The value of a variable can be changed, hence the name variable.
int age =17;//age is 17
age=14;// age is 14
9
 C++ Constants
 In C++, we can create variables whose value cannot be changed. For that,
we use the const keyword. Here's an example:
const int age =17;//age is 17
age=14;// Error !age is a const
A constant can also be created using the #define preprocessor directive.
#define pi 3.14 //this tells the compiler the value of pi is equal to 3.14 and the
value will not be changed after declared in this way.
10
 In C++, data types are declarations for variables. This determines the type
and size of data associated with variables. The fundamental data types of
C++ are :
Data Type Meaning Size (in Bytes)
int Integer 4
float Floating-point 4
double
Double Floating-
point
8
char Character 1
bool Boolean 1
void Empty 0
11
 We can further modify some of the fundamental data types by using type
modifiers.
 There are 4 type modifiers in C++. They are:
◦ signed
◦ unsigned
◦ short
◦ long
 We can modify the fundamental data types with the above modifiers:
 Short int, long int, unsigned short int, unsigned long int etc.
 We can calculate the size of the data types using the keyword of “sizeof”
◦ Cout<<sizeof(int);//it provides size of int data types.
12
 In C++ cout sends formatted output to standard output devices,
such as the screen. We use the cout object along with the <<
operator for displaying output.
#include<iostream>
using namespace std;
int main()
{
cout<<"hello world!";
return 0;
}
 In C++, cin takes formatted input from standard input devices such
as the keyboard. We use the cin the >> operator for taking input.
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num; // Taking input
cout << "The number is: " << num;
return 0;
}
13
 C++ allows us to convert data of one type to that of another.
 The process of converting a value from one data type to
another during arithmetic operation is called casting or type of
casting.
 There are two types of type conversion in C++.
◦ Implicit Conversion
◦ Explicit Conversion (also known as Type Casting)
14
15
// An example of implicit conversion
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}
16
// C++ program to demonstrate
// explicit type casting
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}
17
Operators in C++:
Types of operators symbols
Assignment operators =
Arithmetic operators +,-,*,/,%
Relational operators ==,!=,>,<,>=,<=
Logical operators !,&&,||
Bitwise operators ~,&,|
Compound operators +=,-=,*=,/=,%=
Increment and decrement operators ++,--
Conditional operators ?:
18
 Here’s an example that shows both the prefix and postfix versions of the
increment operator:
19
20
 Syntax:
Test condition?expression1:expression2
If the test condition is true, expression 1 is
implemented otherwise expression 2 is
evaluated. It is the same as if-else statements.
21
#include <iostream>
using namespace std;
int main () { // Local variable declaration:
int x, y = 10;
x = (y < 10) ? 30 : 40;
cout << "value of x: " << x << endl;
return 0; }
value of x: 40
 Many activities in C++ are carried out by library functions. These functions
perform file access, mathematical computations, and data conversion, among other
things.
22
 The next example, SQRT, uses the library function sqrt() to calculate the
square root of a number entered by the user.
23
24
 An array is a collection of data that holds a fixed number of values
of the same type.
 In programming, sometimes a simple variable is not enough to hold
all the data.
 For example, let’s say we want to store the marks of 100 students,
having 100 different variables for this task is not feasible, we can
define an array with size 100 that can hold the marks of all students.
25
 datatype array_Name[array_Size];
 datatype [array_Size] array_Name;
◦ For example, float mark[100];
◦ float [100] mark;
 Here, we declared an array, mark, of floating-
point type and size 100. Meaning, it can hold 100
floating-point values.
 The size and type of arrays cannot be changed
after its declaration.
26
 How to initialize a one-dimensional array?
 There are three ways to initialize an array.
 arra
0 1 2 3 4
10 20 30 40 50
27
 What will happen if the size and number of elements of
an array is different?
28
 Array index starts with 0, which means the first array
element is at index 0, the second is at index 1, and so
on. We can use this information to display the array
elements. See the code below:
29
 Although this code worked fine, displaying all the elements of the array like this is
not recommended. When you want to access a particular array element then this is
fine but if you want to display all the elements then you should use a loop like this:
#include <iostream>
using namespace std;
int main()
{
int array[100], position, c, n, value;
cout<<"Enter number of elements
in arrayn"<<endl;
cin>>n;
cout<<"Enter elementsn"<<endl;
for (c = 0; c < n; c++)
{
cin>>array[c];
}
cout<<"Enter the location where
you wish to insert an
elementn"<<endl;
cin>>position;
cout<<"Enter the value to
insertn"<<endl;
cin>>value;
for (c = n - 1; c >= position - 1;
c--)
{
array[c+1] = array[c];
}
array[position-1] = value;
cout<<"Resultant array
isn"<<endl;
for (c = 0; c <= n; c++)
{
cout<<array[c];
}
return 0;
}
30
 Can you copy array using a syntax like this?
double myList []={1.9,2.3,1.8,4.5};
list = myList;//wrong, this is not allowed.
 In C++ You have to copy individual elements from one array to the other as
follows:
for (int i = 0; i < ARRAY_SIZE; i++)
{
list[i] = myList[i];
}
31
C++ program to store and calculate the sum of 5 numbers
entered by the user using arrays.
#include <iostream>
using namespace std;
int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";
// Storing 5 number entered by user in an array
// Finding the sum of numbers entered
for (int i = 0; i < 5; ++i)
{
32
cin >> numbers[i];
sum += numbers[i];
}
cout << "Sum = " << sum << endl;
return 0;
}
Output
Enter 5 numbers: 3
4
5
4
2
Sum=18
33
 Multidimensional arrays are also known
as array of arrays.
 The data in multidimensional array is stored
in a tabular form as shown in the diagram
below.
34
35
36
37
Example 1: Two Dimensional Array
C++ Program to display all elements of an initialised two dimensional array.
#include <iostream>
using namespace std;
int main()
{
int test[3][2] = { {2, -5}, {4, 0},{9, 1}};
// Accessing two dimensional array using
// nested for loops
for(int i = 0; i < 3; ++i)
{
for(int J = 0; J < 2; ++J)
{
38
cout<< "test[" << i << "][" << J<< "] = " << test[i][J] << endl;
}
}
return 0;
}
39
Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1
 Arrays can be passed to a function as an
argument. Consider this example to pass one-
dimensional array to a function:
 C++ Program to display marks of 5 students
by passing one-dimensional array to a
function.
#include <iostream>
using namespace std;
void display(int marks[5]);
int main()
{
40
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
void display(int m[5])
{
cout << "Displaying marks: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "Student "<< i + 1 <<": "<< m[i] << endl;
}
}
41
 When an array is passed as an argument to
a function, only the name of an array is
used as argument.
display(marks);
 Also notice the difference while passing array as an
argument rather than a variable.
void display(int m[5]);
42
 Multidimensional array can be passed in similar way as one-
dimensional array. Consider this example to pass two
dimensional array to a function:
 C++ Program to display the elements of two dimensional
array by passing it to a function.
#include <iostream>
using namespace std;
void display(int n[3][2]);
int main(){
int num[3][2] = {{3, 4},{9, 5},{7, 1}};
display(num);
return 0;}
43
void display(int n[3][2])
{
cout << "Displaying Values: " << endl;
for(int i = 0; i < 3; ++i)
{
for(int J = 0; J < 2; ++J)
{
cout << n[i][J] << " ";
}
}
}
44
 A function that calls itself is known as a recursive
function. And, this technique is known as recursion.
45
46
47
 Strings are words that are made up of
characters, hence they are known as
sequence of characters.
 In C++ we have two ways to create and use
strings:
1. By creating char arrays and treat them as
string
2. By creating string object
1) Array of Characters – Also known as C Strings
 C-strings are arrays of type char terminated
with null character, that is, 0 (ASCII
value of null character is 0).
48
char str[] = "C++";
In the above code, str is a string and it holds 4
characters.
Although, "C++" has 3 character, the null
character 0 is added to the end of the string
automatically
Alternative ways of defining a string
char str[4] = "C++";
char str[] = {'C','+','+','0'};
char str[4] = {'C','+','+','0'};
49
C + + 0
str
A simple example where we have initialized the
char array during declaration.
50
#include <iostream>
using namespace std;
int main()
{
char book[50] = "A Song of Ice and Fire";
cout<<book;
return 0;}
Output:
A Song of Ice and Fire
51
This can be considered as inefficient method of reading user input, why?
Because when we read the user input string using cin then only the first word of
the string is stored in char array and rest get ignored. The cin function considers
the space in the string as delimiter and ignore the part after it.
#include <iostream>
using namespace std;
int main()
{
char book[50];
cout<<"Enter your favorite book name:"; //reading user input
cin>>book;
cout<<"You entered: "<<book;
return 0;}
Output:
Enter your favorite book name:The Murder of Roger Ackroyd
You entered: The
 You can see that “The” got captured in the book and remaining part after
space got ignored.
 How to deal with this then? Well, for this we can use cin.get function,
which reads the complete line entered by user.
 Example 3: Correct way of capturing user input string using cin.get
52
#include <iostream>
using namespace std;
int main()
{
char book[50];
cout<<"Enter your favorite book name:"; //reading user input
cin.get(book, 50);
cout<<"You entered: "<<book;
return 0;}
Output:
Enter your favorite book name:The Murder of Roger Ackroyd
You entered: The Murder of Roger Ackroyd
 Size of the char array is fixed, which means the size of the string created
through it is fixed in size, more memory cannot be allocated to it during
runtime. For example, lets say you have created an array of character with
the size 10 and user enters the string of size 15 then the last five characters
would be truncated from the string.
On the other hand if you create a larger array to accommodate user input
then the memory is wasted if the user input is small and array is much
larger then what is needed.
 What is the solution of these problems? We can create string using
string object
53
54
 In C++, you can also create a string object for
holding strings.
 Unlike using char arrays, string objects has no
fixed length, and can be extended as per your
requirement.
Example 4: C++ string using string data
type
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str; // Declaring a string object
cout << "Enter a string: ";
getline(cin, str);
cout << "You entered: " << str << endl;
return 0; }
Output
Enter a string: Programming
is fun.
You entered: Programming is
fun.
55
Function Use
strlen calculates the length of string
strcat Appends one string at the end of another
strncat
Appends first n characters of a string at the
end of another
strcpy Copies a string into another
strncpy
Copies first n characters of one string into
another
strcmp Compares two strings
strncmp Compares first n characters of two strings
strchr
Finds first occurrence of a given character in
a string
strrchr
Finds last occurrence of a given character in a
string
strstr
Finds first occurrence of a given string in
another string
 We can perform different kinds of string functions like joining of 2 strings,
comparing one string with another or finding the length of the string. Let's have a
look at the list of such functions.
 These predefined functions are part of the cstring library.
Therefore, we need to include this library in our code by
writing.
56
#include <cstring>
• strlen, strcpy, strcat and strcmp as these are the most commonly used.
• strlen(s1) calculates the length of string s1.White space is also calculated in the
length of the string.
• strcpy(s1, s2) copies the second string s2 to the first string s1.
• strcat(s1, s2) concatenates(joins) the second string s2 to the first string s1.
• strcmp(s1, s2) compares two strings and finds out whether they are same or
different. It compares the two strings character by character till there is a mismatch.
If the two strings are identical, it returns a 0. If not, then it returns the difference
between the ASCII values of the first non-matching pairs of characters.
57
#include <iostream>
using namespace std;
int main()
{
string str = "C++ Programming";
// you can also use str.length()
cout << "String Length = " << str.size();
return 0;
}
Output
String Length = 15
58
To get the length of a C-string string, strlen() function is used.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[] = "C++ Programming is awesome";
// you can also use str.length()
cout << "String Length = " << strlen(str);
return 0;
}
Output
String Length = 26
59
#include <iostream>
using namespace std;
int main()
{
string s1, s2, result;
cout << "Enter string s1: ";
getline (cin, s1);
cout << "Enter string s2: ";
getline (cin, s2);
result = s1 + s2;
cout << "Resultant String = "<< result;
return 0;}
Output
Enter string s1: C++ Programming
Enter string s2: is awesome.
Resultant String = C++ Programming is awesome.
60
#include <iostream>
#include <cstring>
using namespace std;
int main()
{ char s1[50],s2[50], result[100];
cout << "Enter string s1: ";
cin.getline(s1, 50);
cout << "Enter string s2: ";
cin.getline(s2, 50);
strcat(s1, s2);
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2;
return 0;}
Output
Enter string s1:I love
Enter string s2: C++ programming
s1 = I love C++ programming
s2 = C++ programming
61
#include <iostream>
using namespace std;
int main()
{
string s1, s2;
cout << "Enter string s1: ";
getline (cin, s1);
s2 = s1;
cout << "s1 = "<< s1 << endl;
cout << "s2 = "<< s2;
return 0;
}
Output
Enter string s1: C++ Strings
s1 = C++ Strings
s2 = C++ Strings
To copy c-strings in C++, strcpy() function is used.
62
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[100], s2[100];
cout << "Enter string s1: ";
cin.getline(s1, 100);
strcpy(s2, s1);
cout << "s1 = "<< s1 << endl;
cout << "s2 = "<< s2;
return 0;
}
Output
Enter string s1: C-Strings
s1 = C-Strings
s2 = C-Strings
63
In this program, a string str is declared. Then the
string is asked from the user.
Instead of using cin>> or cin.get() function, you
can get the entered line of text using getline().
getline() function takes the input stream as the first
parameter which is cin and str as the location of
the line to be stored.
The advantage of using this method is that you need not to
declare the size of the string, the size is determined at run
time, so this is better memory management method. The
memory is allocated dynamically at runtime so no memory is
wasted.
 This is the same as we do with other arrays. The only difference is that this is an
array of characters. That's it!
 Let's see an example.
64
Enter a word
cpp
cpp
65
Thank you !!!

Más contenido relacionado

Similar a Chapter1.pptx

C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
Mohamed Ahmed
 
introductory concepts
introductory conceptsintroductory concepts
introductory concepts
Walepak Ubi
 

Similar a Chapter1.pptx (20)

Pengaturcaraan asas
Pengaturcaraan asasPengaturcaraan asas
Pengaturcaraan asas
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
C programming language
C programming languageC programming language
C programming language
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2
 
CP 04.pptx
CP 04.pptxCP 04.pptx
CP 04.pptx
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
introductory concepts
introductory conceptsintroductory concepts
introductory concepts
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Hello world! Intro to C++
Hello world! Intro to C++Hello world! Intro to C++
Hello world! Intro to C++
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 

Último

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 

Último (20)

ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 

Chapter1.pptx

  • 1. University of Gondar Institute of Technology Department of Computer Engineering Course name: intermediate computer programming Course code: CoEng2111 Course instructor: Wondimu B. Email: wondimubantihun2005@gmail.com
  • 2. 1  Review of C++ Basics  Arrays and Strings ◦ Introduction to Array ◦ Implementing array ◦ Multidimensional array ◦ Using arrays with functions ◦ Recursion functions ◦ Strings and the cstring.h library ◦ String output formatting
  • 3. 2  C++ is a statically-typed, compiled, general purpose, case-sensitive, multi-paradigm, intermediate-level programming language.”  In simple terms, C++ is a sophisticated, efficient, and general-purpose programming language based on C. It was developed by Bjarne Stroustrup in 1979.  Many of today’s operating systems, system drivers, browsers, and games use C++ as their core language. This makes C++ one of the most popular languages today.
  • 4.  In any language there are some fundamentals you need to know before you can write even the most elementary programs. In this section, we will discuss and review some of C++ basics. ◦ Basic program constructions ◦ Variables ◦ Data types ◦ Input/output ◦ Operators ◦ Data conversion and ◦ library functions 3
  • 5. 4 #include <iostream> using namespace std; // main() is where program execution begins. int main() { cout << "Hello World"; // prints Hello World return 0; } Let’s look at a very simple C++ program. this program is called hello_world, so its source file is hello_world.cpp. It simply prints a sentence on the screen.
  • 6. 5  A First Program – hello_world.cpp // Program: Display greetings // This is Comment. #include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; } Preprocessor directives Insertion statement Ends executions of main() which ends program Comments Function named main() indicates start of program Provides simple access
  • 7. 6 Fig. shows how C++ program is executed
  • 8. 7  In programming, a variable is a container (storage area) to hold data.  To indicates the storage area, each variable should be given a unique name (identifier). Rules for naming a variable (identifiers)  It is a name given to any program element.  The elements might be variables, functions, arrays, structures, or classes.  The general rules for naming variables are: ◦ A variable name can only have alphabets, numbers, and the underscore. ◦ A variable name cannot begin with a number. ◦ Names are case sensitive (myVar and myvar are different variables)
  • 9. 8 ◦ Names cannot contain whitespaces or special characters like !, #, %, etc. ◦ A variable name cannot be a keyword. Reserved words (like C++ keywords, such as int) cannot be used as names. ◦ Note: We should try to give meaningful names to variables. For example, first_name is a better variable name than fn.  The value of a variable can be changed, hence the name variable. int age =17;//age is 17 age=14;// age is 14
  • 10. 9  C++ Constants  In C++, we can create variables whose value cannot be changed. For that, we use the const keyword. Here's an example: const int age =17;//age is 17 age=14;// Error !age is a const A constant can also be created using the #define preprocessor directive. #define pi 3.14 //this tells the compiler the value of pi is equal to 3.14 and the value will not be changed after declared in this way.
  • 11. 10  In C++, data types are declarations for variables. This determines the type and size of data associated with variables. The fundamental data types of C++ are : Data Type Meaning Size (in Bytes) int Integer 4 float Floating-point 4 double Double Floating- point 8 char Character 1 bool Boolean 1 void Empty 0
  • 12. 11  We can further modify some of the fundamental data types by using type modifiers.  There are 4 type modifiers in C++. They are: ◦ signed ◦ unsigned ◦ short ◦ long  We can modify the fundamental data types with the above modifiers:  Short int, long int, unsigned short int, unsigned long int etc.  We can calculate the size of the data types using the keyword of “sizeof” ◦ Cout<<sizeof(int);//it provides size of int data types.
  • 13. 12  In C++ cout sends formatted output to standard output devices, such as the screen. We use the cout object along with the << operator for displaying output. #include<iostream> using namespace std; int main() { cout<<"hello world!"; return 0; }
  • 14.  In C++, cin takes formatted input from standard input devices such as the keyboard. We use the cin the >> operator for taking input. #include <iostream> using namespace std; int main() { int num; cout << "Enter an integer: "; cin >> num; // Taking input cout << "The number is: " << num; return 0; } 13
  • 15.  C++ allows us to convert data of one type to that of another.  The process of converting a value from one data type to another during arithmetic operation is called casting or type of casting.  There are two types of type conversion in C++. ◦ Implicit Conversion ◦ Explicit Conversion (also known as Type Casting) 14
  • 16. 15 // An example of implicit conversion #include <iostream> using namespace std; int main() { int x = 10; // integer x char y = 'a'; // character c // y implicitly converted to int. ASCII // value of 'a' is 97 x = x + y; // x is implicitly converted to float float z = x + 1.0; cout << "x = " << x << endl << "y = " << y << endl << "z = " << z << endl; return 0; }
  • 17. 16 // C++ program to demonstrate // explicit type casting #include <iostream> using namespace std; int main() { double x = 1.2; // Explicit conversion from double to int int sum = (int)x + 1; cout << "Sum = " << sum; return 0; }
  • 18. 17 Operators in C++: Types of operators symbols Assignment operators = Arithmetic operators +,-,*,/,% Relational operators ==,!=,>,<,>=,<= Logical operators !,&&,|| Bitwise operators ~,&,| Compound operators +=,-=,*=,/=,%= Increment and decrement operators ++,-- Conditional operators ?:
  • 19. 18
  • 20.  Here’s an example that shows both the prefix and postfix versions of the increment operator: 19
  • 21. 20
  • 22.  Syntax: Test condition?expression1:expression2 If the test condition is true, expression 1 is implemented otherwise expression 2 is evaluated. It is the same as if-else statements. 21 #include <iostream> using namespace std; int main () { // Local variable declaration: int x, y = 10; x = (y < 10) ? 30 : 40; cout << "value of x: " << x << endl; return 0; } value of x: 40
  • 23.  Many activities in C++ are carried out by library functions. These functions perform file access, mathematical computations, and data conversion, among other things. 22
  • 24.  The next example, SQRT, uses the library function sqrt() to calculate the square root of a number entered by the user. 23
  • 25. 24  An array is a collection of data that holds a fixed number of values of the same type.  In programming, sometimes a simple variable is not enough to hold all the data.  For example, let’s say we want to store the marks of 100 students, having 100 different variables for this task is not feasible, we can define an array with size 100 that can hold the marks of all students.
  • 26. 25  datatype array_Name[array_Size];  datatype [array_Size] array_Name; ◦ For example, float mark[100]; ◦ float [100] mark;  Here, we declared an array, mark, of floating- point type and size 100. Meaning, it can hold 100 floating-point values.  The size and type of arrays cannot be changed after its declaration.
  • 27. 26  How to initialize a one-dimensional array?  There are three ways to initialize an array.  arra 0 1 2 3 4 10 20 30 40 50
  • 28. 27  What will happen if the size and number of elements of an array is different?
  • 29. 28  Array index starts with 0, which means the first array element is at index 0, the second is at index 1, and so on. We can use this information to display the array elements. See the code below:
  • 30. 29  Although this code worked fine, displaying all the elements of the array like this is not recommended. When you want to access a particular array element then this is fine but if you want to display all the elements then you should use a loop like this:
  • 31. #include <iostream> using namespace std; int main() { int array[100], position, c, n, value; cout<<"Enter number of elements in arrayn"<<endl; cin>>n; cout<<"Enter elementsn"<<endl; for (c = 0; c < n; c++) { cin>>array[c]; } cout<<"Enter the location where you wish to insert an elementn"<<endl; cin>>position; cout<<"Enter the value to insertn"<<endl; cin>>value; for (c = n - 1; c >= position - 1; c--) { array[c+1] = array[c]; } array[position-1] = value; cout<<"Resultant array isn"<<endl; for (c = 0; c <= n; c++) { cout<<array[c]; } return 0; } 30
  • 32.  Can you copy array using a syntax like this? double myList []={1.9,2.3,1.8,4.5}; list = myList;//wrong, this is not allowed.  In C++ You have to copy individual elements from one array to the other as follows: for (int i = 0; i < ARRAY_SIZE; i++) { list[i] = myList[i]; } 31
  • 33. C++ program to store and calculate the sum of 5 numbers entered by the user using arrays. #include <iostream> using namespace std; int main() { int numbers[5], sum = 0; cout << "Enter 5 numbers: "; // Storing 5 number entered by user in an array // Finding the sum of numbers entered for (int i = 0; i < 5; ++i) { 32
  • 34. cin >> numbers[i]; sum += numbers[i]; } cout << "Sum = " << sum << endl; return 0; } Output Enter 5 numbers: 3 4 5 4 2 Sum=18 33
  • 35.  Multidimensional arrays are also known as array of arrays.  The data in multidimensional array is stored in a tabular form as shown in the diagram below. 34
  • 36. 35
  • 37. 36
  • 38. 37
  • 39. Example 1: Two Dimensional Array C++ Program to display all elements of an initialised two dimensional array. #include <iostream> using namespace std; int main() { int test[3][2] = { {2, -5}, {4, 0},{9, 1}}; // Accessing two dimensional array using // nested for loops for(int i = 0; i < 3; ++i) { for(int J = 0; J < 2; ++J) { 38
  • 40. cout<< "test[" << i << "][" << J<< "] = " << test[i][J] << endl; } } return 0; } 39 Output test[0][0] = 2 test[0][1] = -5 test[1][0] = 4 test[1][1] = 0 test[2][0] = 9 test[2][1] = 1
  • 41.  Arrays can be passed to a function as an argument. Consider this example to pass one- dimensional array to a function:  C++ Program to display marks of 5 students by passing one-dimensional array to a function. #include <iostream> using namespace std; void display(int marks[5]); int main() { 40
  • 42. int marks[5] = {88, 76, 90, 61, 69}; display(marks); return 0; } void display(int m[5]) { cout << "Displaying marks: "<< endl; for (int i = 0; i < 5; ++i) { cout << "Student "<< i + 1 <<": "<< m[i] << endl; } } 41
  • 43.  When an array is passed as an argument to a function, only the name of an array is used as argument. display(marks);  Also notice the difference while passing array as an argument rather than a variable. void display(int m[5]); 42
  • 44.  Multidimensional array can be passed in similar way as one- dimensional array. Consider this example to pass two dimensional array to a function:  C++ Program to display the elements of two dimensional array by passing it to a function. #include <iostream> using namespace std; void display(int n[3][2]); int main(){ int num[3][2] = {{3, 4},{9, 5},{7, 1}}; display(num); return 0;} 43
  • 45. void display(int n[3][2]) { cout << "Displaying Values: " << endl; for(int i = 0; i < 3; ++i) { for(int J = 0; J < 2; ++J) { cout << n[i][J] << " "; } } } 44
  • 46.  A function that calls itself is known as a recursive function. And, this technique is known as recursion. 45
  • 47. 46
  • 48. 47
  • 49.  Strings are words that are made up of characters, hence they are known as sequence of characters.  In C++ we have two ways to create and use strings: 1. By creating char arrays and treat them as string 2. By creating string object 1) Array of Characters – Also known as C Strings  C-strings are arrays of type char terminated with null character, that is, 0 (ASCII value of null character is 0). 48
  • 50. char str[] = "C++"; In the above code, str is a string and it holds 4 characters. Although, "C++" has 3 character, the null character 0 is added to the end of the string automatically Alternative ways of defining a string char str[4] = "C++"; char str[] = {'C','+','+','0'}; char str[4] = {'C','+','+','0'}; 49 C + + 0 str
  • 51. A simple example where we have initialized the char array during declaration. 50 #include <iostream> using namespace std; int main() { char book[50] = "A Song of Ice and Fire"; cout<<book; return 0;} Output: A Song of Ice and Fire
  • 52. 51 This can be considered as inefficient method of reading user input, why? Because when we read the user input string using cin then only the first word of the string is stored in char array and rest get ignored. The cin function considers the space in the string as delimiter and ignore the part after it. #include <iostream> using namespace std; int main() { char book[50]; cout<<"Enter your favorite book name:"; //reading user input cin>>book; cout<<"You entered: "<<book; return 0;} Output: Enter your favorite book name:The Murder of Roger Ackroyd You entered: The
  • 53.  You can see that “The” got captured in the book and remaining part after space got ignored.  How to deal with this then? Well, for this we can use cin.get function, which reads the complete line entered by user.  Example 3: Correct way of capturing user input string using cin.get 52 #include <iostream> using namespace std; int main() { char book[50]; cout<<"Enter your favorite book name:"; //reading user input cin.get(book, 50); cout<<"You entered: "<<book; return 0;} Output: Enter your favorite book name:The Murder of Roger Ackroyd You entered: The Murder of Roger Ackroyd
  • 54.  Size of the char array is fixed, which means the size of the string created through it is fixed in size, more memory cannot be allocated to it during runtime. For example, lets say you have created an array of character with the size 10 and user enters the string of size 15 then the last five characters would be truncated from the string. On the other hand if you create a larger array to accommodate user input then the memory is wasted if the user input is small and array is much larger then what is needed.  What is the solution of these problems? We can create string using string object 53
  • 55. 54  In C++, you can also create a string object for holding strings.  Unlike using char arrays, string objects has no fixed length, and can be extended as per your requirement. Example 4: C++ string using string data type #include <iostream> #include <cstring> using namespace std; int main() { string str; // Declaring a string object cout << "Enter a string: "; getline(cin, str); cout << "You entered: " << str << endl; return 0; } Output Enter a string: Programming is fun. You entered: Programming is fun.
  • 56. 55 Function Use strlen calculates the length of string strcat Appends one string at the end of another strncat Appends first n characters of a string at the end of another strcpy Copies a string into another strncpy Copies first n characters of one string into another strcmp Compares two strings strncmp Compares first n characters of two strings strchr Finds first occurrence of a given character in a string strrchr Finds last occurrence of a given character in a string strstr Finds first occurrence of a given string in another string  We can perform different kinds of string functions like joining of 2 strings, comparing one string with another or finding the length of the string. Let's have a look at the list of such functions.
  • 57.  These predefined functions are part of the cstring library. Therefore, we need to include this library in our code by writing. 56 #include <cstring> • strlen, strcpy, strcat and strcmp as these are the most commonly used. • strlen(s1) calculates the length of string s1.White space is also calculated in the length of the string. • strcpy(s1, s2) copies the second string s2 to the first string s1. • strcat(s1, s2) concatenates(joins) the second string s2 to the first string s1. • strcmp(s1, s2) compares two strings and finds out whether they are same or different. It compares the two strings character by character till there is a mismatch. If the two strings are identical, it returns a 0. If not, then it returns the difference between the ASCII values of the first non-matching pairs of characters.
  • 58. 57 #include <iostream> using namespace std; int main() { string str = "C++ Programming"; // you can also use str.length() cout << "String Length = " << str.size(); return 0; } Output String Length = 15
  • 59. 58 To get the length of a C-string string, strlen() function is used. #include <iostream> #include <cstring> using namespace std; int main() { char str[] = "C++ Programming is awesome"; // you can also use str.length() cout << "String Length = " << strlen(str); return 0; } Output String Length = 26
  • 60. 59 #include <iostream> using namespace std; int main() { string s1, s2, result; cout << "Enter string s1: "; getline (cin, s1); cout << "Enter string s2: "; getline (cin, s2); result = s1 + s2; cout << "Resultant String = "<< result; return 0;} Output Enter string s1: C++ Programming Enter string s2: is awesome. Resultant String = C++ Programming is awesome.
  • 61. 60 #include <iostream> #include <cstring> using namespace std; int main() { char s1[50],s2[50], result[100]; cout << "Enter string s1: "; cin.getline(s1, 50); cout << "Enter string s2: "; cin.getline(s2, 50); strcat(s1, s2); cout << "s1 = " << s1 << endl; cout << "s2 = " << s2; return 0;} Output Enter string s1:I love Enter string s2: C++ programming s1 = I love C++ programming s2 = C++ programming
  • 62. 61 #include <iostream> using namespace std; int main() { string s1, s2; cout << "Enter string s1: "; getline (cin, s1); s2 = s1; cout << "s1 = "<< s1 << endl; cout << "s2 = "<< s2; return 0; } Output Enter string s1: C++ Strings s1 = C++ Strings s2 = C++ Strings To copy c-strings in C++, strcpy() function is used.
  • 63. 62 #include <iostream> #include <cstring> using namespace std; int main() { char s1[100], s2[100]; cout << "Enter string s1: "; cin.getline(s1, 100); strcpy(s2, s1); cout << "s1 = "<< s1 << endl; cout << "s2 = "<< s2; return 0; } Output Enter string s1: C-Strings s1 = C-Strings s2 = C-Strings
  • 64. 63 In this program, a string str is declared. Then the string is asked from the user. Instead of using cin>> or cin.get() function, you can get the entered line of text using getline(). getline() function takes the input stream as the first parameter which is cin and str as the location of the line to be stored. The advantage of using this method is that you need not to declare the size of the string, the size is determined at run time, so this is better memory management method. The memory is allocated dynamically at runtime so no memory is wasted.
  • 65.  This is the same as we do with other arrays. The only difference is that this is an array of characters. That's it!  Let's see an example. 64 Enter a word cpp cpp