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

4. Strings, Arrays and Function (2)

The document provides an overview of strings, arrays, and functions in C++. It explains string operations such as comparison, concatenation, and access, as well as array declaration, initialization, and manipulation. Additionally, it covers the basics of functions, including their declaration, calling, and the use of pre-defined functions.

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)
4 views

4. Strings, Arrays and Function (2)

The document provides an overview of strings, arrays, and functions in C++. It explains string operations such as comparison, concatenation, and access, as well as array declaration, initialization, and manipulation. Additionally, it covers the basics of functions, including their declaration, calling, and the use of pre-defined functions.

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/ 49

INDIAN INSTITUTE OF TECHNOLOGY ROORKEE

CEC-101: Computer Programming


Strings, Arrays and Functions

Prof. Anjaneya Dixit


[email protected]
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

2
String in C++

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


• Escape sequence:

3
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

4
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” ?

5
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
}

6
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

7
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;

8
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;

9
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

10
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]; //

11
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;

12
Arrays

13
Arrays

Value [] is an array of
type int with 1000
‘elements’

14
Arrays

• Arrays are used to store multiple values in a single variable,


instead of declaring separate variables for each value.
int value[1000];
string cars[4];
string cars[4] = {“Maruti
Suzuki", “Honda", "Ford", “Kia"};
int myNum[3] = {10, 20, 30};

• A collection of a fixed number of components wherein all of


the components have the same data type

15
Arrays

• Its elements are stored in a contiguous memory


location
• The size of the array should be mentioned while
declaring it
• Array elements are always counted from zero (0)
onward
• Array elements can be accessed using the position of
the element in the array
• The array can have one or more dimensions.

16
Arrays

17
Arrays

• Access the elements of an array by referring to index


number.
• Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
cout << cars[2];//  Ford

• An element of an array can be changed by referring to the


index of that element.

string cars[4] = {“Maruti


Suzuki", “Honda", "Ford", “Kia"};
cars[0] = “Toyota";
cout << cars[0]; //  Toyota

18
Arrays

Let us try to create an array, which has size of 10, and elements are sum of previous two
elements. Initial two elements are 0 and 1.

int list[10];
list[0] = 0;
list[1] = 1;

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


list[i] = list[i-2] + list[i-
1];
cout << list[i] << "\n";
}

TODO: write a program to determine the maximum element from an integer array.

19
Copying an Array

int firstArr[50];
int secondArr[50];

To copy, can we simply use the assignment operator?

firstArr = secondArr;

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


firstArr [i] = secondArr[i];
}

Similarly, there is no aggregate input/ output for arrays, aggregate arithmetic, etc.

20
Arrays

• Array Index out of bound  if someone attempts to access


the element at a position which does not exist or is higher
than the size of the array – 1.

• Arrays can be initialized during declaration; size is not


required.
string cars[] = {“Maruti
Suzuki", “Honda", "Ford", “Kia"};

21
Arrays: Two dimensional

• Also known as matrix string sales[10][5];

22
Arrays: Two dimensional

int rows = 2;
int cols = 2;
int mat[rows][cols];

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


for (int j = 0; j < cols; j++) {
mat[i][j] = i * j;
cout << mat[i][j] ;
}
cout<< endl;
}

23
Arrays: Two dimensional

Array initialization
int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

int x[3][4] = {
{0, 1 ,2 ,3},
{4, 5 , 6 , 7}, 0 1 2 3
{8 , 9 , 10 , 11} 4 5 6 7
}
8 9 10 11

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


for (int j = 0; j < 4; j++)
{
cout << x[i][j] << ‘ ’;
}
cout<< endl;
}

24
Arrays: User input

int rows = 2;
int cols = 2;
int mat[rows][cols];

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


for (int j = 0; j < cols; j++) {
cout <<"Enter the value for” << i <<"th row and "<< j <<"th
column!";
cin >> mat[i][j];
}
}

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


for (int j = 0; j < cols; j++) {
cout << mat[i][j] ;
}
cout<< endl;
}

25
Arrays: Three dimensional

26
Arrays: Three dimensional

int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};

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


for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
cout << x[i][j][k] << ‘ ’;
}
cout<< endl;
}
cout << endl;
}

27
Array declaration
#include <iostream>
using namespace std;

int main() {
int size;
int size, int size,
cin>>size; OR a[size]; OR a[ ];
int a[size];
cin>>size; cin>>size;
cout<<"Taking input\n";
for (int i=0; i<size; i++)
cin>>a[i];

cout<<"Giving output\n";
for (int i=0; i<size; i++)
cout<<a[i]<<endl;

return 0;
}

28
Arrays elements as variables

angle[2] = 9.6; Assign it a value.


cin >> angle[2]; Read a value into it.
cout << angle[2]; Write its contents.
y = sqrt ( angle[2] ); Pass it as an argument.
x = 6.8 * angle[2] + 7.5; Use it in an arithmetic
expression

29
Code to find highest and offset scores
#include <iostream> max = score[0];
using namespace std; for (int i = 0; i < num; i++)
{if (score[i] > max)
int main() { max = score[i];
int num, max ; }

cout<<"Enter class size cout << “Highest score: " << max;
";
cin>>num; cout << “\n Offset from highest:\
int score[num]; n";
for (int i = 0; i < num; i++)
cout<<"\n Enter scores\ cout << "Score "<< i << " off by
n"; "
for (int i=0; i<num; i++) << (max-score[i]) << endl;

cin>>score[i]; return 0;
}
cout<<"Scores entered\
n:";
for (int i=0; i<num; i++)
30
Arrays-Examples

Bubble Sorting

31
Arrays-Examples

Bubble Sorting

if (a[j]>a[j+1])
{
int temp = a[j];
a[j] =
a[j+1];
a[j+1] = temp;
}
32
Arrays-Examples

Selection Sorting

33
Arrays-Examples

Palindromes

Segregation (odd/even; vowels/consonants)

Record keeping

Matrix operations

34
Functions

35
Functions

• A function is a block of code which runs only when it is called.

• You can pass data, known as parameters, into a function.

• Functions are used to perform certain action(s).

• Functions are useful when a block of code is to be used again


and again.

• main() is one of the pre-defined function.

36
Functions: Basics

Take the instance of


f(x) = 2x + 5
1, 2, 3 are arguments (or
Then, f(1) = 7, parameters) sent to the function
f(2) = 9, and
f(3) = 11 7, 9, 11 are returned values

Some pre-defined mathematical functions in C++

pow (x,y);
sqrt (x);
floor (x); ceil (x);

37
Functions: Pre-defined functions

floor(x): Returns the largest integer smaller than or equal to x


Examples of ceil:
Input : 2.5 Output : 2
Input : -2.1 Output : -3
Input : 2.9 Output : 2

ceil(x): Returns the smallest integer greater than or equal to x


Examples of ceil:
Input : 2.5 Output : 3
Input : -2.1 Output : -2
Input : 2.9 Output : 3

38
Functions: Syntax

void MyFunction()
{
//Function body
}

• “MyFunction” is the name of the function


• “void” signifies the function shall not return any value
• “Function body” defines the content/operation of the function
• “()” signifies that no data was passed to the function

39
Functions: Declaration and Calling
• Functions are declared before main()
• Declaration is done by defining the ‘type’ and the ‘name’ of the function
followed by a pair of parenthesis ()
• Function declaration explains how to call it

void fun() {
cout << “This is a trial function\
n”;
} What happens if you
declare fun() after main()?
int main () {
fun(); //Calling the function
fun(); //Calling multiple times
fun(); //Calling multiple times
return 0;
}

40
Functions: Declaration and Calling
• Functions are declared before main(), but can be defined after main()
• Helps in better organization of the code
• Functions are called inside the main function
• Calling is done by following the syntax of function declaration
Compilation sequence Run sequence
// Function declaration
1 void fun(); 2
// main function
2 int main() {
fun(); // calling function 1
return 0;
}

// Function definition
3 void fun() {
cout << “My first function.\n”;
3
}
41
Functions: Declaration and Calling

•Functions are declared before main(), but can be defined after main()
•Helps in better organization of the code
•Function declaration explains how to call it

// Function declaration // Function declaration


void fun(); void fun();
void fun(int x);
void fun(int x, int y);
// main function void fun(int x, float y, string s);
int main() {
fun(); // calling function
return 0; // Function declaration
} int fun();
int fun(int x, int y);
// Function definition
void fun() { bool fun(int x, int y)
cout << “My first function.\n”;
}

42
Functions: Parameters and passing
arguments
• Functions communicate with one another through parameters
• Parameter details (numbers and types) are given during function declaration
void myFun(parameter1, parameter2, parameter
3) {
// code to be executed
}
#include <iostream>
using namespace std;

void myfunc(string fname, string


country="India"){
cout << fname << " is from " << country <<
endl;
}

int main(){
myfunc("Anjaneya");
myfunc("Dixit", "USA");
return 0; 43
Functions: Variables as Parameters
• Functions communicate with one another through parameters
• Parameter details (numbers and types) are given during function declaration
• Variables can be passed as parameters

#include <iostream>
using namespace std;

void myfunc(string fname, string country="India"){


cout << fname << " is from " << country << endl;
}

int main(){
string s; cin>>s;
myfunc(s);
myfunc(s, "USA");
return 0;
}

44
Functions: Variables as Parameters
• Functions communicate with one another through parameters
• Parameter details (numbers and types) are given during function declaration
• Parameter mismatch (type or number) will result in compilation error

#include <iostream>
using namespace std;

void myfunc(string fname, string country){


cout << fname << " is from " << country << endl;
}

int main(){
string s; cin>>s;
myfunc(s); //Invalid due to Parameter
mismatch
myfunc(s, "USA"); //Valid
return 0;
}
45
Functions: Returning a value
• Functions communicate with one another through parameters
• Parameter details (numbers and types) are given during function declaration
• For a two-way communication, functions can return values to talk back
#include <iostream>
using namespace std;
//Function declaration and receiving the argument sent from main()
int FACT(int x) //Function type set to return value type
{
int fact=1;
for (int i=1; i<=x; i++)
fact*=i; //Calculating the factorial
return fact; //Returning the factorial
}

int main(){
int x; cin>>x; //Taking input
int y = FACT(x); //Calling function and passing the
argument
cout << y; //Displaying the output
return 0;
} 46
Functions: A small program inside the program
• Instead of input using cin, arguments are received as formal parameters
• The output may be the conventional type (cout) or return of a value
• Variables are declared independently in main() and user-defined function()
#include <iostream>
using namespace std;
//Function declaration and receiving the argument sent from main()
int FACT(int x) //Function type set to return value type
{
int fact=1;
for (int i=1; i<=x; i++)
fact*=i; //Calculating the factorial
return fact; //Returning the factorial
}

int main(){
int x; cin>>x; //Taking input
int y = FACT(x); //Calling function and passing the
argument
cout << y; //Displaying the output
return 0;
} 47
Functions: Overloading
• Overloading is declaring multiple functions with same name
• Made distinct by changing the number and/or type of the arguments
• Compiler identifies relevant function by checking the argument number and type
• Only changing the return type will not allow function overloading

int FACT(int x) //Type-1


int FACT(int x, int y) //Type-2
int FACT(int x, float z) //Type-3

void FACT (int x) vs int FACT(int


x) //Is this function
overloading?

48
Functions: Overloading

#include <iostream>
using namespace std;

int FACT(int x){ //Type-1


//Function body
}
int FACT(int x, int y){ //Type-2
//Function body
}
int FACT(int x, float z){ //Type-3
//Function body
}

int main(){
int p,q; float r; cin>>p>>q>>r;
int a = FACT(p); //Calling function
Type-1
int b = FACT(p,q); //Calling function
Type-2
int c = FACT(p,r); //Calling function
Type-3
cout << a << b << c;
return 0; 49

You might also like