Lab 2. Solutions

Task 1. Maximum value

/*
  Author: Alexey Nikolaev
  Description: Lab 2. Task 1. Maximum value
    Usage: 
      ./a.out < file
    
    Reads a stream of positive integers from the file 
    redirected to the standard input, keeping track of 
    the largest integer so far.
    When the end of file is reached, the program outputs 
    the largest integer it found.
*/

#include <iostream>

using namespace std;

int main () {
  int largest = 0;
  int n;
  while (cin >> n) {
    if (n > largest) {
      largest = n;
    }
  }
  cout << largest << endl;
}

Task 2. Maximum difference

/*
  Author: Alexey Nikolaev
  Description: Lab 2. Task 2. Maximum difference
    Usage: 
      ./a.out < file

    Reads a stream of positive integers from the file 
    redirected to the standard input. Outputs the largest 
    absolute value of the difference betweeen any two 
    consecutive numbers that were read.

    The program expects that the file contains at least 2 integers.
*/

#include <cstdlib>
#include <iostream>

using namespace std;

int main () {
  int largest = 0;
  int a;
  int b;

  cin >> a;
  while (cin >> b) {
    int diff = abs(b - a);
    if (diff > largest) {
      largest = diff;
    }
    a = b;
  }
  cout << largest << endl;
}

Task 3. Printing a bar chart

/*
  Author: Alexey Nikolaev
  Description: Lab 2. Task 3. Bar chart
    Usage: 
      ./a.out < file

    Reads a stream of positive integers from the file 
    redirected to the standard input.
    
    Outputs the numbers as a bar chart printed using 
    the vertical bar "|" character.
*/

#include <iostream>

using namespace std;

int main () {

  int n;
  while (cin >> n) {
    for (int i = 0; i < n; i++) {
      cout << '|';
    }
    cout << endl;
  }

}