Thứ Tư, 2 tháng 12, 2015

03 Example Programs(Các chương trình ví dụ)

Program to convert A to B:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
    float A;
    float B;
    cout<<"Enter A = ";
    cin>> A;
    B = A * 3.14;
    cout<<"Result B = "<< B;
    return 0;
}
-
Program to add two numbers:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <iostream>
using namespace std;

int main()
{
    int a, b, c;
    cout<<endl<<"Enter a and b: ";
    cin>> a>> b;
    c = a + b; // -, * , / with type float
    cout<<"Result c = "<< c;
    return 0;
}
-
Program to swap two numbers:
Cách 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int i, j, g;
    i = 4;
    j = 7;
    cout<<"values before swapping: "<<i<<" "<<j<<endl;
    g = i;
    i = j;
    j = g;
    cout<<"values after swapping: "<<i<<" "<<j;
    return 0;
}
-
Cách 2:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int i, j, g;
    i = 4;
    j = 7;
    cout<<"values before swapping: "<<i<<" "<<j<<endl;
    g = i * j;
    i = g / i;
    j = g / i;
    cout<<"values after swapping: "<<i<<" "<<j;
    return 0;
}
-
Cách 3:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int i, j, g;
    i = 4;
    j = 7;
    cout<<"values before swapping: "<<i<<" "<<j<<endl;
    i = i * j; // 4*7
    j = i / j; // 4*7 / 7 = 4
    i = i / j; // 4*7 / 4 = 7
    cout<<"values after swapping: "<<i<<" "<<j;
    return 0;
}
-
Cách 4:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int i, j, g;
    i = 4;
    j = 7;
    cout<<"values before swapping: "<<i<<" "<<j<<endl;
    g = i + j;
    i = g - i;
    j = g - i;
    cout<<"values after swapping: "<<i<<" "<<j;
    return 0;
}
-
Cách 5:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int i, j, g;
    i = 4;
    j = 7;
    cout<<"values before swapping: "<<i<<" "<<j<<endl;
    i = i + j; //4+7 = 11
    j = i - j; // 11 - 7 = 4
    i = i - j;
    cout<<"values after swapping: "<<i<<" "<<j;
    return 0;
}
-
Program printing the name and age:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
using namespace std;

int main()
{
    char name[10];
    int age;
    cout<<"Enter the name: ";
    cin>>name;
    cout<<"Enter the age: ";
    cin>>age;
    cout<<"The name of the person is "<<name<<" and the age is "<<age;
    return 0;
}
- 004