Professional Documents
Culture Documents
Opt1
Assignment topic : CPP Functions, Passing FRESHER
variable to functions ACADEMY
Assignment duration : 180 minutes
Bài 1. Below example tries to swap value of evenNumber and oddNumber but it does not works.
Please correct it by trying passing reference of pointer to swap function.
cout << "evenNumber: " << evenNumber << " ,oddNumber : " << oddNumber << endl;
swap(evenNumber, oddNumber);
cout << "evenNumber: " << evenNumber << " ,oddNumber : " << oddNumber<< endl;
return 0;
}
Result:
evenNumber: 2 ,oddNumber : 3
evenNumber: 2 ,oddNumber : 3
#include <iostream>
using namespace std;
cout << "evenNumber: " << evenNumber << " ,oddNumber : " << oddNumber << endl;
swap(evenNumber, oddNumber);
cout << "evenNumber: " << evenNumber << " ,oddNumber : " << oddNumber<< endl;
return 0;
}
Bài 2. Write a C++ program that compare length of 2 input strings and return the string that has longer
length.
User will input 2 strings step by step, then program will output the string that is longer.
For example: string1 = “abc”, string2 = “qwer”. Output should be string2 = “qwer”.
#include <iostream>
#include <string>
using namespace std;
main()
{ int x;
string string1,string2;
cout<<"nhap vao do dai xau 1 va 2 "<<endl;
getline( cin,string1);
fflush(stdin);
getline(cin,string2);
if (string1.size()==string2.size())
{
cout<<"2 chuoi bang nhau";
}
else if (string1.size()<string2.size())
{
cout<<string2;
}
else cout<<string1;
}
Bài 3. What is the output when trying to print the value of v.
#include <iostream>
using namespace std;
void incr1(int& x)
{ // increase 1
x++;
}
int incr2(int x)
{ // increase 1
return x++;
}
main()
{
int v = 2;
incr1(v);
v = incr2(v);
cout<<v;
}
Vì 3 phần ABC đúng còn phần D theo cá nhân mỗi người nên có thể sai.