Professional Documents
Culture Documents
#include <iostream>
using namespace std;
void display(int marks[5]);
int main()
{
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69
Passing Multidimensional Array 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;
}
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);
cout << "You entered: " << str << endl;
return 0;
}
objects of string class
string Object
#include <iostream>
using namespace std;
int main()
{
string str;
cout << "Enter a string: ";
getline(cin, str);
cout << "You entered: " << str << endl;
return 0;
}
Reading multiple lines
#include <iostream>
using namespace std;
Const int MAX=2000;
Char str[MAX];
int main()
{
Cout<<“Enter a string”;
Cin.get(str, MAX, ’$’);
Cout<<“You entered”<<str;
return 0;
}
output
• Enter a string
Aaaaaaaaaa
Bbbbbbbbbb
Cccccccccccc
$
You entered
Aaaaaaaaaa
Bbbbbbbbbb
Cccccccccccc
Copy String Object
#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
Copy C-Strings
#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
Arrays of strings
#include <iostream>
using namespace std;
int main()
{
char colour[4][10] = { "Blue", "Red", "Orange", "Yellow" };
for (int i = 0; i < 4; i++)
cout << colour[i] << "\n";
return 0;
}
Output
Output:
Blue
Red
Orange
Yellow
Drawbacks:
• Both the number of Strings and Size of String are fixed.
• A 2D array is allocated, whose second dimension is equal to
maximum sized string which causes wastage of space.
Instead of previous --- to save space since the
size is fixed
int main()
{
string colour[4] = { "Blue", "Red",
"Orange", "Yellow" };
for (int i = 0; i < 4; i++)
cout << colour[i] << "\n";
}