0% found this document useful (0 votes)
17 views99 pages

01 Cec101

The document is a course outline for Computer Programming (CEC-101) at the Indian Institute of Technology Roorkee, focusing on C++ programming. It covers fundamental concepts such as definitions of computers, programming, algorithms, and the structure of C++ programs, including syntax, data types, and operators. The course aims to teach students how to write programs and understand the importance of programming in fields like Civil Engineering.

Uploaded by

villanerror767
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)
17 views99 pages

01 Cec101

The document is a course outline for Computer Programming (CEC-101) at the Indian Institute of Technology Roorkee, focusing on C++ programming. It covers fundamental concepts such as definitions of computers, programming, algorithms, and the structure of C++ programs, including syntax, data types, and operators. The course aims to teach students how to write programs and understand the importance of programming in fields like Civil Engineering.

Uploaded by

villanerror767
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/ 99

INDIAN INSTITUTE OF TECHNOLOGY ROORKEE

Computer Programming (CEC-101)

Prof. Amit Agarwal and Prof. Anjaneya Dixit


[email protected] [email protected];
[email protected]
What do you think of
programming (one word)?

ⓘ Start presenting to display the poll results on this slide.

2
Introduction

• Computer: (Definition by Oxford Dictionary)

“an electronic device for storing and processing data,


…, according to instructions given to it in a
variable program.”

• Complex system consisting of hardware and software


– Hardware: physical parts (e.g., input media, motherboard, etc.)
– Software: a set of programs used by a computer

• Programming is a process of writing instructions (a set of


commands) to solve a specific problem.

• Algorithm is a step-by-step problem-solving process. 3


Basics components

Main memory consists of a long


list of numbered locations called
memory locations (a few
thousands to millions);
Secondary memory (or storage)
The contents of these locations
is the memory that is used for
can change and contain the same
keeping a permanent record of
number of 0s and 1s  binary
information after (and before) the
digit or a bit  most computers
computer is used. Also referred as
contains 8 bits (i.e., byte)  The
auxiliary memory, auxiliary
number that identifies a byte is
storage, external memory, and
called its address.
external storage
4
Programs

Input to the program


Set of instructions

• Algorithm
• A set of explicit and unambiguous finite steps, which, when carried out for
a given set of initial conditions to produce the corresponding output and
terminate in finite time.
• Basically, they are a set of steps to be performed, which can be used to
perform a task/solve a problem.
• Program
• An implementation of an algorithm in a programming language that computer
can understand.
5
Programs

Algorithm Program (in C++)

#include <iostream>
using namespace std;

Input A, B, C int main() {


int A, B, C, Sum;
Sum = A + B + C
cin>>A>>B>>C;
Print Sum Sum = A + B + C;
cout<<Sum;
return 0;
}

6
High and low level languages

High-level Low-level
• Resemble human languages • It is difficult to write and debug
• Are designed to be easy to read and code in Low-Level Languages.
write • Assembly
• Use more complicated instructions ADD X Y Z
than the CPU can follow • Machine language
• Must be translated to zeros and – CPU can follow machine language
ones for the CPU to execute a – Assembly must be converted to
program machine language
• C, C++, Java, Visual Basic, etc.
0110 1001 1010 1011
•  Source Code
 Object Code

7
High and low-level languages

8
Programmers?

9
In this course

• How to write programs?

• Program  a set of instructions  special notation or syntax


(i.e., programming language)

• C++
– Derived from C
– C++ designer: Bjarne Stroustrup (1979)
– Powerful and complex

• We will cover only a part of C++….

10
C++ basics

• Syntax: language-specific statements (instructions/


notations/ rules) which are legal

• Comments:
– used to explain the code or increase the readability
– Comments are ignored by compiler
– Single/ multi-lined
// looping over the array
/* looping over
the array*/

• Every instruction/ command is terminated by semi-colon “;”

11
Processing a C++ program

• Editor  simply writing the set of instructions as per the


syntax (many text editors support syntax/ color highlighting)

• Preprocessor  these are directives which give instructions


to the compiler to pre-process the information
– Starts with # (only whitespace is allowed before this)
– these are filenames in the Standard C++ Library.

#include <iostream>  this is a C++ standard library header


for input-output stream
#define PI 3.14

12
Processing a C++ program

• Compiler 
– checks the program for syntax errors (set of rules which are
language specific)
– Compiler accepts almost any pattern of line breaks and indentation
– Translate into machine language (low-level language);
– Binary of “Hello World.”
01001000 01100101 01101100 01101100 01101111
00100000 01010111 01101111 01110010 01101100
01100100
• Execution
– from top to bottom
– from left to right

• Output
13
Program errors

• Syntax errors
– Violation of the grammar rules (syntax) of the language
– Discovered by the compiler
• Error messages may not always show the correct location of
errors

• Run-time errors
– Error conditions detected by the computer at run-time

• Logic errors
– Errors in the program’s algorithm
– Most difficult to diagnose
– Computer does not recognize an error

14
Hello World!

#include <iostream>

int main( ) {

// hello world program


std::cout << “Hello world”;
return 0;

15
Where to run the program?
• Offline:
– Dev-C++
– Visual Studio
– …
• Online:
– https://www.programiz.com/cpp-programming/online-compiler/
– https://www.tutorialspoint.com/compile_cpp_online.php
– https://www.w3schools.com/cpp/cpp_compiler.asp

– …
[[let’s run the first program]]

Try to write a few programs, which prints your name/ enrolment number/ branch/
institute, etc.

16
Where to run the program?

17
Why C++ (or programming) in Civil Engineering?

• AutoCAD  C++
• SUMO (open-source): https://sumo.dlr.de/  C++
• 12 D solutions  C++
• FreeFEM: https://freefem.org/  C++
• …
• Others (general)  C++
– Amazon
– Google web search engine
– Apple OS X (a few important parts)
– Adobe systems
– Bloomberg
– Sun: Open Office
– …
• Many other languages…
18
Special symbols

• + • ?
• - • ,
• * • <=
• / • !=
• . • ==
• ; • >=

19
Reserved keywords

• int • catch
• float • enum
• double • public
All small-case
• char • false
• const • true
• void • break
• return • continue
• switch • namespace
• while • throw
• do • static
• for • private
• this • …

20
C++ basic input, output

• cout  sends the output from main memory to standard


devices (e.g., console screen)

• cin  takes the input from standard devices (e.g., keyboard,


mouse) to the main memory

• header (required): #include <iostream>

• For cout, insertion (<<) operators are used, whereas for cin
extraction (>>) operators are used

• Let’s look on the Hello World example TODO: try clog and cerr

21
cout
header (remember Name of the function;
directives)!! return type;
every program must have
#include <iostream> exactly one main()
function
int main( ) {
Check cout, insertion
// write the comment here… operator, semi colon
std::cout << “Hello world”;
return 0;
What is this? Can we
} get rid of it?

Return statement; optional


but some compilers expect it
to be included as the last line
of the main() function

22
cout
This means, all functions under std namespace
#include <iostream> are available in the scope of this program
using namespace std; without explicitly prefixing “std::”

int main( ) {

// write the comment here…


cout << “Hello world”;
return 0;

Let’s look on another example

23
cout

#include <iostream>
using namespace std;
What will be the output of this?

int main( ) {

cout << “Hel” << “lo” <<“Wo” << “rld”;


return 0;

Let’s look on another example

24
cin

#include <iostream>
using namespace std;

int main( ) {

int num ;
cout << “Enter an Integer”;
cin >> num; // taking input
cout << “Square of the number is “ << num*num;
return 0;

25
C++ Program

26
Data types

• Primitive data types


• Derived data types
• User defined data types

27
Data types

28
Primitive Data types: char

• “hello” is a string literal


• char is stored in the computers as an integer
• enclosed in single quotes
• American Standard Code for Information Interchange
(ASCII)
• Visit:
– https://www.ascii-code.com/
– https://en.cppreference.com/w/cpp/language/ascii
• Newline character ‘\n’ is one of the non-printing characters
(e.g., \n, \t).
• Size 1 byte
• Range: -128 to 127 or 0 to 255 (on most compilers)

29
Primitive Data types
Data type Meaning Size (in bytes) Other details
int Integer 4 Range: -2147483648 to
2147483647; usually of 4
int age = 24; bytes

float Floating point 4 Precision = 7 places


float speed = 60.5; (decimals)
double Double floating 8 Higher precision than
double dist = 4.45; point float (14)

char Character 1 Inside single quotes; an integer


value is stored rather than the
character itself (see
char te = ‘t’; https://en.cppreference.com/w/c
pp/language/ascii
std::cout << int(te) ; Do you really need 1 and
byte for bool? https://www.ascii-code.com/ )
Range: -127 to 127 or 0 to
255
bool Boolean 1 Two possible values: true,
false
bool val = false;
30
Data types modifiers

• signed: int, char, long-prefix


• unsigned: int, char, long-prefix
• short: int
• long: int, double
• Execute the following and try to understand the results
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of signed int : " << sizeof(signed int) << endl;
cout << "Size of unsigned int : " << sizeof(unsigned int) << endl;
cout << "Size of unsigned long int : " << sizeof(unsigned long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of long double : " << sizeof(long double) << endl;
cout << "Size of signed char : " << sizeof(signed char) << endl;
cout << "Size of unsigned char : " << sizeof(unsigned char) << endl;
31
Data types modifiers

1 2 4 8

32
Other Data types

• Derived data types: array, pointers, functions, etc.


• User defined: Class, Structure, Union, Enum, etc.

33
Variable names in C++

• Unique names (called as identifiers)


• This is basically, a name given to the memory location
• Variables must be declared before use.
• It could be short as (i,j,k or long as volume, speed)
• It may contain letters, digits, underscores (_)
• It must begin with a letter or underscore (i.e., it cannot begin with a
number)
• Names are case sensitive
• Names cannot contain white spaces or special characters
• Reserved words cannot be used.
• Examples:
age _age A_ge a_g_e
age23 a23ge a ageOfPerson

What will happen if you write wrong names? Try it.

34
Variable names in C++

• Syntax
datatype variable_name;
• Though, it is a matter of personal preference, descriptive
names are recommended for better readability of the code
• Unlike reserved words, predefined identifiers (e.g., cout,
cin) can be redefined, but don’t do that.

• Cases:
– Camel ageOfPerson
– Pascle AgeOfPerson
– Snake age_of_person

Different style for local, instance, static, variables may be adopted for clarity.

35
Variable names in C++

int age = 24;

data_type variable_name value (initialize)

int time, speed;

What will be output of the following?

float number = 1/10;


std::cout << number <<std::endl;
What will be output of the following?

float number = 1.0/10.0;


std::cout << number <<std::endl;
What will be output of the following?

int number = 1.0/10.0;


std::cout << number <<std::endl;
36
Variable names in C++

#include <iostream>
using namespace std;

int main( ) {

int num ; // declaration


num = 23; // initialization or assignment
return 0;

A variable must be initialized before it is used (not necessarily during declaration).

A variable can be initialized by assignment and by taking from inputs.

37
Variable names in C++

#include <iostream>
using namespace std;

int main( ) {

int num1;
int num2;
num1=34;
num2=90;
cout << num1 << endl;
cout << num2;
return 0;
}

38
Variable names in C++

#include <iostream>
using namespace std;

int main( ) {

int num1 =34, num2=90; // declaration and initialization


cout << num1 << endl;
cout << num2;
return 0;
}

39
Variable names in C++

#include <iostream>
using namespace std;

int main( ) {

int num1 =34, num2=90;


cout << num1 << endl;
cout << num2 <<endl;
int num3 = num1 +num2; /* expression (on the right) is
evaluated first and then assigned to num3 */
cout << num3;
return 0;
}

40
Variable names in C++

#include <iostream>
using namespace std;

int main( ) {

int hours, minutes, seconds;


cin>> hours >> minutes >> seconds; // order is important
cout<< hours << ":" << minutes << ":" << seconds;
return 0;
}

Three variables can be entered separated by space or one number in each line
(newline separator).

41
Operators

1. Arithmetic
2. Assignment
3. Relational
4. Logical
5. Other

42
Arithmetic Operators

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

Modulo Operation (Remainder


%
after division)

43
Arithmetic Operators
int main( ) {
int a =34, b=90;
cout << "a+b=" << (a+b) << endl;
cout << "a-b=" << (a-b) << endl;
cout << "a*b=" << (a*b) << endl;
cout << "a/b=" << (a/b) << endl;
cout << "a%b=" << (a%b) << endl;
return 0;
}

int main( ) {
int a =3;
Unary operators
int x = a++;
• Pre-increment ++x (also --x)
cout << x << endl;
• Post-increment x++ (also x-- )
cout << a << endl;
x = ++a;
cout << x << endl;
cout << a << endl;
return 0;
}
44
Assignment Operators

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;

45
Assignment Operators

#include <iostream>
using namespace std;

int main( ) {

int a =3, b=9;


cout << “Old value of a:" << a << endl;
a += b
cout << “New value of a:" << a << endl;
return 0;

46
Order of Precedence
• All operations inside of () are evaluated first

• *, /, and % are at the same level of precedence and are evaluated next

• + and – have the same level of precedence and are evaluated last

• When operators are on the same level


• Performed from left to right (associativity)

47
Mixed expression
• Integral expression 2+3*6

• Floating expression 2.5 + 3.1 * 3.2

• Mixed expression evaluation: 2 + 3.5 / 2


• If operator has same types of operands
• Evaluated according to the type of the operands

• If operator has both types of operands


• Integer is changed to floating-point
• Operator is evaluated
• Result is floating-point

• Entire expression is evaluated according to precedence rules

48
Relational Operators

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


>= 3 >= 5 give us false
To

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

49
Logical Operators

Operator Example Meaning

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

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

Logical NOT.
! !expression True only if the
operand is false.

50
Logical Operators

#include <iostream>
using namespace std;

int main( ) {

bool out = (3 != 5) && (3 < 5); // 1 (true)

bool out2 = !(5 == 2); // 1 (true)

bool out3 = !(5 == 5); //0 (false)


return 0;

51
other Operators

Operator Description Example

sizeof returns the size of data type sizeof(int); // 4

string result = (5 > 0) ?


?: returns value based on the condition "even" : "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;

52
Mathematical Functions

• Large number of mathematical functions are available in


standard C++

• To use them, include:


#include<cmath>

#include<math.h>

• Examples:
– sin, cos, tan …
– asin, acos, atan …
– sqrt, abs, pow, floor, ceil …
– log, exp, …
– See https://www.cplusplus.com/reference/cmath/

53
Mathematical Functions

#include <iostream>
#include<cmath>
using namespace std;

int main( ) {

int num = -10;


cout << abs(num) << endl;

int a = 25;
cout << sqrt(a) << endl;

int b = 5;
int c = 3;
cout << pow(5,3);
return 0;
}

54
Conditional Statements

• Remember Relational and logical operators

• Use if to execute a block of code, if a condition is met (i.e., true)

• Use else to execute a block of code, if the same condition is false

• Use else if to test a new condition, if the first condition is false

• Use switch to execute many alternative blocks based on different criteria of a


variable

if (condition) {
// block of code to be executed if the condition is
true
}
if (35 >= 20) {
cout << “35 is greater than or equal to 20";
}

55
Conditional Statements
Truth Tables

56
Conditional Statements

57
Conditional Statements

int speed = 30;


if (speed < 40) {
cout << “Good going…";
} else {
cout << “Too fast, slow down…";
}

int speed = 30;


if (speed < 40) {
cout << “Good going…";
} else if (speed < 50) {
cout << “Just right …";
} else {
cout << “Too fast, slow down…";
}

58
Conditional Statements

59
Conditional Statements

int speed = 30;


if (speed < 40) {
cout << “Good going…";
} else {
cout << “Too fast, slow down…";
}

int speed;
cin >> speed;
if (speed < 40) {
cout << “Good going…";
} else if (speed < 50) {
cout << “Just right …";
} else {
cout << “Too fast, slow down…";
}

60
Conditional Statements

61
Conditional Statements

int speed = 30;


string message = (speed < 40) ? "Good going…" : “Too fast, slow
down…";
cout << message;

62
Conditional Statements: nested

int speed = 30;


int vehicle = 1; // 1 car, 2 MTW
if (speed < 40) {
if (vehicle == 1) {
cout << “Good going…";
} else {
cout << “Be careful, out there.";
}
} else {
if (vehicle == 1) {
cout << “Too fast, slow down …";
} else {
cout << “Dangerous speed…";
}
}

63
Conditional Statements: Ternary operator

Syntax

(speed < 40) ? "Good going…" : “Too fast, slow


down…";

Assignment using ?:

int speed = 30;


string message = (speed < 40) ? "Good going…" : “Too fast, slow
down…";
cout << message;

64
Conditional Statements: Ternary operator

Comparison with if-else

65
Conditional Statements: switch

• Used when a set of menus is clearly defined


• Allows to create discrete blocks for each case
• Compiler will switch between different cases
• Upon operating a case successfully, the compilation
will break and move out of the switch block
• If no case matches the set menu, default menu shall
execute

break and default optional. The switch block will be


executed even if there are no breaks for each case or a
default case is not provided

66
Conditional Statements: switch
int day = 4; It breaks out of the switch
switch (day) {
case 1: block, i.e., no more case
cout << "Monday"; testing inside the switch
break; block.
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday"; When none of the
break; outlined cases match the
default: input argument
cout << “Enjoying the Weekend";
}

67
Conditional Statements: switch
Leaving an empty case in the switch block

• Suppose A, B, C, D, and F are


the only valid grades.
• You want to display the same
message for grades is D or F

Leave case D empty, so


the compiler can jump
directly to case F.

68
Conditional Statements: switch
Pitfall of forgetting a break in the switch block

69
Conditional Statements: switch for menu

Declaring the respective functions


to do the assigned task. This is
done outside main function

Calling the respective functions


to do the assigned task.
This is done inside main function

70
Loops
• Repetition
• To execute a block of code as long as a specific condition is met
• Loops are handy, saves time, and are more readable

The while loop loops through


while (condition) { a block of code as long as a
// code block to be executed specified condition is true.
}
This loop will execute the code block
once, before checking if the condition
do { is true, then it will repeat the loop as
// code block to be executed long as the condition is true.
}
while (condition);
If it is known that a block of
for (initialization; condition; update) { code is to be executed ‘n’
// code block to be executed times, use the for loop
} instead of a while loop:

71
Loops: Types
for (int i = 0; i < max; i++)
{
cout << i << "\n";
‘for’ loop
}

int i = 0; max;
cin >> max;
while (i < max)
{ ‘while’ loop
cout << i << "\n";
i++;
}

int i = 0;
int max;
cin >> max;
do
{
‘do-while’ loop
cout << i << "\n";
i++;
} while (i < max);

72
‘for’ LOOP: Syntax

for (Initialization; Condition;


Updation) {
Code body
}
Occurs only once Runs every time Done only if the
at the start of loop loop is repeated condition is met

int i = 0; max;
cin >> max;
while (i < max)
{
cout << i << "\n";
i++;
for (int i = 0; i < max; i++) }
{
cout << i << "\n"; int i = 0;
} int max;
cin >> max;
do
{
cout << i << "\n";
i++;
} while (i < max);

73
‘while’ LOOP: Syntax

while (Condition)
Runs every time
{
loop is repeated
Code body
}
Updation: Part of Initialization: Occurs
loop code before start of loop

int i = 0; max;
cin >> max;
while (i < max) for (int i = 0; i < max; i+
+)
{ {
cout << i << "\n"; cout << i << "\n";
}
i++; int i = 0;
} int max;
cin >> max;
do
{
cout << i << "\n";
i++;
} while (i < max);

74
‘do-while’ LOOP: Syntax

Updation: Part of Initialization: Occurs


do loop code before start of loop
{ Do-while
Code body loop will run
} while (Condition); Checked after the at least once,
loop has run even if the
condition is
false

int i = 0;
int max;
cin >> max; for (int i = 0; i < max; i+
+)
do {
{ cout << i << "\n";
}
cout << i << "\n";
i++; int i = 0; max;
cin >> max;
} while (i < max); while (i < max)
{
cout << i << "\n";
i++;
}

75
Loops: Pitfalls in for loop

76
Loops: Multiple variables in for

Printing the sum of first 100 integers

77
Loops

• Infinite loop

78
Loops

• Compute the average of numbers as long as a user enters the numbers

79
Loops: nested

for (int i = 0; i < max; i++) {


for (int j = 0; j < max; j++) {
cout << i << "\n";
}
}

How can we get the following?


*
**
***
****
*****
How can we get the following?
*****
****
***
**
*

80
Jumps statements: break, continue, goto

• break:
• Exits from a switch or loop immediately.
• Jumps to the first statement that follows the switch or loop.

• continue:
• Has the opposite effect to break; the next loop begins immediately.
• In while or do-while loop, the program jumps to the test expression, whereas a for
loop is reinitialized.

• goto:
• C++ also offers a goto statement and labels.
• Allows to jump to any given point marked by a label within a function.
• For example, exiting a deeply embedded loop construction immediately.
• A label is a name followed by a colon.

81
break

for (int i = 0; i < 10; i++) {


if (i == 4) {
break;
}
}
cout << i << "\n";

int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

82
break

83
continue

for (int i = 0; i < 10; i++) {


if (i == 4) {
continue;
}
}
cout << i << "\n";

int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}

84
goto

85
goto

86
Control structure in C++

87
String in C++

• String is a variable, which is a collection of characters


– Surrounded by double quotes (“my string”)
– Example
string age
= “34"; Note that: sizeof only
age.size(); Try to use sizeof(age) and
• Size of string see the output. Does it
reports the memory
occupied by the
age.length( make sense? variable
);
• Each character has relative position in string
– Position of first character is 0

• Length of a string is no. of characters in it

88
String in C++

• endl  causes insertion point to move to beginning of next line


• Escape sequence:

89
String Comparison in C++

• Relational operators can be applied to strings


• Strings are compared character by character, starting
with the first character
• Comparison continues until either a mismatch is found,
or all characters are found equal
• If two strings of different lengths are compared and the
comparison is equal to the last character of the shorter
string
– The shorter string is less than the larger string

90
String Comparison in C++

1. s1 < s2 : A string s1 is smaller than s2 string, if either, length of s1


is shorter than s2 or first mismatched character is smaller.
2. s1 > s2 :A string s1 is greater than s2 string, if either, length of s1
is longer than s2 or first mismatched character is larger.
3. <= and>= have almost same implementation with additional
feature of being equal as well.
4. If after comparing lexicographically, both strings are found same,
then they are said to be equal.
5. If any of the points from 1 to 3 follows up then, strings are said to
be unequal.

“Hello” > “Hi” ?

91
String Comparison in C++

#include <iostream>

using namespace std;


int main()
{
e = 101 and i = 105
string str1 = "Hi";
in ASCII (decimal system)
string str2 = "Hello";

bool out = str1>str2;

cout << out;


return 0; TRUE
}

92
String Comparison in C++

string str1 = "Hello";


string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str5 = "Big";

What will be the output of…


str1 < str2; True
str1 > “Hen”; false bool out = 'H' < 'h';
str3 < “An”; true cout << boolalpha<< out << endl;
str1 ==“hello”; false
str3 <= str4; true
str2 > str4; true
str4 >= “Billy”; false
str5 <= “Bigger”; true

You may need https://en.cppreference.com/w/cpp/language/ascii

93
String Concatenation

• The + operator can be used between two strings to make a new


string
• White space can also be concatenated.
string firstName = "Anjaneya ";
string lastName = "Dixit";
string fullName = firstName + lastName;
cout << fullName;

• Since string is an object, append() can also be used to


concatenate strings.
string firstName = "Anjaneya ";
string lastName = "Dixit ";
string fullName = firstName.append(lastName);
cout << fullName;

94
String Concatenation

• Partial concatenation: Append allows part of a string to concatenate

string s1 = "Computer ";


string s2 = "Programming" ;
Computer Program
string s3 = s1.append(s2, 0,
7);
cout << s3;

What will be the output of…

int x = 10;
int y = 20;
int z = x + y; 1020
string x = "10" ;
string y = "20" ;
string z = x + y;

95
String inserting and erasing
string s1("Miss Summer");
s1.insert(5, "Ashley "); // Insert at position: 5

string s(“The summer-time");


s.erase(4,7); // position: 4, quantity 7

96
String Access

• String index starts at 0 (i.e., first character)


• The characters in the string can be accessed using index numbers
inside [ ]
• It can also replace the existing character

What will be the output of…


What will be the output
of… string myString = "Hello" ;
myString[0] = 'J';
string myString = "Hello" cout << myString;
;
cout << myString[1]; //

97
String Access
• Taking a string as input with whitespace in it.

What will be the output of…

string name;
cin >> name; // Enter “Anjaneya Dixit”
cout << name;

• cin considers a space (whitespace, tabs, etc.) as a terminating character,


which means that it can only display a single word

What will be the output of…

string name;
cout << "Enter your name" <<endl;
getline (cin, name);
cout << name;

98
Thanks …
[email protected]

99

You might also like