Home


Lesson 0

Standard input / output, methods, namespaces

Task 0

Write a program, that displays first and last name in first row and student number in second.
You can use cpp.sh or jdoodle and examples below.
Writing to standard output
#include <iostream>
int main() {
    std::cout << "hello world!";
}

hello world!

Writing in two rows
#include <iostream>
int main() {
    std::cout << "Hello there,";
    std::cout << "General Kenobi!";
}
źle

Hello there,General Kenobi!

#include <iostream>
int main() {
    std::cout << "Hello there,";
    std::cout << "\n";
    std::cout << "General Kenobi!";
}
we can do better

Hello there,

General Kenobi!

#include <iostream>
int main() {
    std::cout << "Hello there,";
    // endl = end of line
    std::cout << std::endl;
    std::cout << "General Kenobi!";
}
ok

Hello there,

General Kenobi!

Using std as namespace
#include <iostream>
using std::cout;
using std::endl;

int main() {
    cout << "Hello there,";
    cout << endl;
    cout << "General Kenobi!";
}

Hello there,

General Kenobi!

Merging output streams
#include <iostream>
using std::cout;
using std::endl;

int main() {
    cout << "Hello there," << endl << "General Kenobi!";
}

Hello there,

General Kenobi!

Task 1

Create a new method with body from main.
Call created method in main function.
Put the method into new namespace and call it inside main.
Method writing
#include <iostream>
using std::cout;
using std::endl;

void hello() {
    cout << "Hello there," << endl
         << "General Kenobi!";
}

int main() {
    hello();
}

Hello there,

General Kenobi!

Own namespace
#include <iostream>
using std::cout;
using std::endl;

namespace helpers {
    void hello() {
        cout << "Hello there," << endl
                << "General Kenobi!";
    }
}

int main() {
    helpers::hello();
}

Hello there,

General Kenobi!


What could go wrong if we swap namespace and main?

Task 2

Write a program, that takes params for equation: ax2+bx+c=0,
and displays real solution(s).
Use as much C++ elements from current lesson as you can.
Reading data from standard input
#include <iostream>
using std::cout;
using std::cin;

int main() {
    int number;
    cout << "Type a number: ";
    cin >> number;
    cout << "Your number is: " << number;
}

Type a number: 42

Your number is: 42

Params and returning
#include <iostream>
using std::cout;
using std::cin;

namespace my_math {
    int sum(int a, int b) {
        return a + b;
    }
}

int main() {
    int x, y;
    cin >> x >> y;
    int sum = my_math::sum(x, y);
    if (sum > 100) {
        cout << "sum is greater than 100";
    }
}

50 140

sum is greater than 100

Task 3

Create a BMI calculator.