Solutions to Assignment 1

 

// p1
#include 

// use namespace std;

int 
main() {
    int N;			/* Size of the input */
    int S = 0;			/* Temporary sum */
    int x;			/* Current number */

    cout << "Enter the input size: ";
    cin >> N;
    for (int i = 0; i < N; i++) {
        cout << "Input number " << i+1 << ": ";
        cin >> x;
        S += x;
    }

    cout << "Sum is:" << S << endl;
    cout << "Average is: " << static_cast(S) / N << endl;

}

// p2
#include 
//use namespace std;

int 
main() {
    int a;
    int b;

    cout << "Enter the two numbers: ";
    cin >> a >> b;
    cout << "Numbers (before): " << a << ", " << b << endl; 
    int c = a;
    a = b;
    b = c;
    cout << "Numbers (after): " << a << ", " << b << endl;
}

// p3
#include 
//use namespace std;

int 
main() {
    int a;
    int b;

    cout << "Enter the two numbers: ";
    cin >> a >> b;
    cout << "Numbers (before): " << a << ", " << b << endl; 
    a += b;                                                                    
    b = a - b;                                                                 
    a -= b;  
    cout << "Numbers (after): " << a << ", " << b << endl;
}

// p4
#include 
//use namespace std;

int
main() {
    int a, b;

    cout << "Enter numbers: ";
    cin >> a >> b;
    while (a > 0) {
        if (a < b) {
            a += b;    
            b = a - b;
            a -= b;  
        }
        a -= b;
        
    }
    cout << "Greatest common divisor is: " << b << endl;

}

// p5
#include 
//use namespace std;

int 
main() {
    float B, S, BP, D, C;

    cout << "Enter B, S, BP, D: ";
    cin >> B >> S >> BP >> D;
    if (B < 125.1) {
        C = 0.0;
    } else if (B < 135.0) {
        C = 0.5208 - 0.0012*(B-125.0);
    } else if (B < 145.0) {
        C = 0.5088 - 0.0011*(B-135.0);
    } else if (B < 155.0) {                                                     
        C = 0.4978 - 0.0010*(B-145.0);                                          
    } else if (B < 165.0) {                                                     
        C = 0.4878 - 0.0009*(B-155.0);                                          
    } else {
        C = 0.0;
    }
    cout << C*(S + BP + D) << endl;
    return 1;
}

// p6
#include 
#include 
// using namespace std;

#define FACTOR 50

int 
main() {
    float x, y;

    for (x = 0.0; x < 2.0 + 0.1 / 2; x += .1) {
        y = x / (1 + x * x) * FACTOR;
        cout << setfill(' ') << setw(3) << x << " ";
        cout << setfill('*') << setw(static_cast(y)) << "" << endl;
     }

    return 0;
 }