Basics of C/C++ Programming: Difference between revisions

From ICO wiki
Jump to navigationJump to search
Jtominga (talk | contribs)
Jtominga (talk | contribs)
Line 279: Line 279:
* Has a member function to retrieve stored value;
* Has a member function to retrieve stored value;
You may assume the templated type is not a pointer and has operator+= defined.
You may assume the templated type is not a pointer and has operator+= defined.


5. (optional, self-research) Create a class Distance, that can be used with the Accumulator:
5. (optional, self-research) Create a class Distance, that can be used with the Accumulator:

Revision as of 02:56, 18 October 2016

Introduction

Lecturers

Rait Liiv: rait.liiv@itcollege.ee

Janno Tomingas: janno.tomingas@itcollege.ee

C

Lectures

Practices

Practice 1

Console input/output


1. Write a program, that outputs "Hello, World!"

2. Write a program, that asks the user for a number and then writes the number back to the user

3. Write a simple calculator, that supports addition, subtraction, multiplication and division. The program should ask the user for two numbers and the operation to perform and output the result to the console.

Practice 2

Functions, pointers, out variables, function return values as success/error codes


1. Write a function that adds two integers, outputs the result via an out variable and returns 0 to indicate a successful operation.

Hint:

 int add(int a, int b, int* out)
 {
 }


2. Write a function that swaps two integers and returns 0 to indicate a successful operation.

Hint:

 int swap(int* a, int* b)
 {
 }


3. Write a function that reverses a string and returns 0 to indicate a successful operation.

Hint:

 int reverse(char* string, size_t length)
 {
 }


4. Write a function that sorts an array of ints and returns 0 to indicate a successful operation.

Hint:

 int sort(int* string, size_t length)
 {
 }


Practice 3

File input/output, dynamic memory allocation


1. Write a program that outputs the contents of a text file into the console.

Hint:

Always close the file stream after you are done using it.

Make sure to check for error codes.


2. Write a program that reads the contents of a text file into a dynamically sized array and outputs the information into a new file.

Hint:

Use "fseek", "ftell" and "rewind" to find out how large the buffer should be.

Make sure you have enough room for a null terminator.

Remember to free the allocated memory after calling malloc or calloc.

Make sure to check for error codes.


Practice 4

Dynamic memory allocation continued, structs, .h/.c files


1. Create an implementation of a stack data structure (Stack (abstract data type)) that uses a dynamically allocated array for storage.

  • Required functions:
    • init - Initializes stack's variables and allocates required dynamic memory with an initial(default) size,
    • destroy - Frees all allocated memory and optionally resets other stored information for a stack,
    • push - Adds an element to the top of the stack,
    • peek - Gets the top element of the stack,
    • pop - Gets and removes the top element of the stack;


  • Describe the stack struct and functions in a separate .h file,
  • Implement the functions in a corresponding .c file,
  • Test your stack with some operations. Remember to check for edge cases;
Hints:
  • How do you know which element to access?
  • How do you know if an array is full?
  • How should the functions behave when a stack is empty?
  • How should the functions behave when a stack is full?
  • What will happen if any of the functions are called unexpectedly many times?

Assignment

Write a program that reads values from a file and outputs the result to stdout.

Input

Input file's name is "input.txt".

The file contains index-value pairs of integers on a single line. Integers in a pair are separated with a comma (,) and pairs are separated with a semicolon (;).

All indices between 0 and (count_of_pairs - 1) are guaranteed to be present.

The indices are guaranteed to be unique.

The indices are not guaranteed to appear in an ascending order.

Sample input: 1,4;0,2;2,8

Output

The program should output the differences between consecutive values as the index increases.

Output should be printed as a comma separated list of values on a single line to stdout.

For input:

0,1;2,4;1,2

Calculates:

0,1 to 1,2 -> 2 - 1 = 1
1,2 to 2,4 -> 4 - 2 = 2

And outputs:

1,2
Examples
->
0,2 -> 0
1,2;0,1 -> 1
1,4;0,2;2,8 -> 2,4
1,4;0,2;2,-2 -> 2,-6

C++

Lectures

Practices

Practice 1

Console input/output, strings, references, arrays, new/delete


1. Write a simple calculator, that takes a simple binary operation (+,-,*,/) as an input and outputs the result to the console on a new line.

Example:

 1 + 2 -> 3
 3 * 8 -> 24
2. Write a program that asks the user for several strings and outputs the total numbers of characters entered.
  • Ask for the number of strings the user will enter,
  • Store all input strings in in an appropriately sized array,
  • Use a function to count the total number of characters entered;

Example:

Input:

3
one
two
three

Output:

11
Practice 2

Classes, constructors/destructors, member functions, intro to templates, vector


1. Create a class Rectangle, that:

  • Stores the width and height as private member variables,
  • Uses a constructor to set width and height,
  • Has public member functions to calculate and return the area and circumference of the rectangle;


2. Create a program that uses std::vector to store several Rectangles and computes the total area of all stored rectangles.


3. Convert the stack (Practice 4 of C) from C to C++:

  • Replace the struct with a class,
  • Add member functions,
  • Make use of constructors and destructors,
  • Adjust member functions to return values on success (and, for the bold, throw on failure),
  • Use a class template to describe the datatype stored in the struct;
Practice 3

Inheritance, dynamic polymorphism, unique_ptr


1. Create classes Rectangle and Circle, that:

  • Store necessary data as private member variables,
  • Have a public member function to calculate and return their area;


2. Create a program, that:

  • Creates and stores some Rectangles and Circles,
  • Calculates the total area of the shapes;


3. Create a base class for previously created objects, called Shape:

  • Create a public virtual member function area,
  • Create a protected member variable to store the number of a Shape's corners in,
  • Modify both Rectangle and Circle to inherit Shape and override the virtual function,
  • Modify your program to store Shapes in a vector of unique pointers to Shape;


4. Add a class Triangle, that inherits from Shape:

  • Store the necessary data,
  • Create the necessary functions,
  • Use all the Shapes in your program;


5. Add a function to calculate the Shapes' circumference.


6. (optional) Similarly to the Shapes, create a hierarchy of Animals, that:

  • Know their name,
  • Can write out the sound they make;

Use your Animals in a simple program.

Practice 4

Overloading, template functions, template classes


1. Create a new header file:

  • Create a function add - int add (int a, int b),
  • Create separate implementations of the add function for floats, doubles, and strings,
  • Try out the functions;


2. Template the add function.


3. Create a simple templated Queue (Queue (abstract data type)), that:

  • Uses a container to store the items in,
  • Has a member function to add items to the queue (enqueue),
  • Has a member function to get items from the queue (dequeue);


4. Create a template class Accumulator, that:

  • Stores an instance of the templated type as a member variable,
  • Sets the initial value of the variable via the constructor,
  • Has a member function to add to the stored value,
  • Has a member function to retrieve stored value;

You may assume the templated type is not a pointer and has operator+= defined.


5. (optional, self-research) Create a class Distance, that can be used with the Accumulator:

  • Store the value in a member variable,
  • Overload operator+= to support addition between two instances of the Distance class,

Additional information on operators and operator overloading can be found at operator overloading.