CSE 201 - Tutorial 2

Exercise 1: Palindrome testing (Code refactoring)

Write a new version of the program that determines if the word that the user inputs is a palindrome or not (cf.Tutorial 1). Organize your code using "functions".

Exercise 2: Palindrome testing (Code refactoring/2)

Now, write another version that uses a recursive function.

Exercise 3: Second word

Write a program that writes the second word (and its length) in an array of characters. Words are separated by spaces, punctuation and tabs. Test your code on the sentence “Actually, couldn’t you come with me?” The correct answer should be: couldn’t (8).

Exercise 4: Pointers

Guess the output of the following program, then code it and check if you were right.

#include <iostream>
using namespace std;
int main(){
  int val1 = 2015, val2 = 442;
  int *p1 , *p2;
  p1 = &val1; 
  p2 = &val2; 
  *p1 = 2016;
  *p2 = *p1; 
  p1 = p2; 
  *p1 = val2;
  cout << "val1 = " << val1 << endl; 
  cout << "val2 = " << val2 << endl; 
  return 0;
}

Exercise 5: Swap function (1)

This "swap" function does not swap "a" and "b".

#include <iostream>
 
void swap(int a, int b)
{
  int s=a;
  a=b;
  b=s;
}
 
int main(int argc, char **argv)
{
  int a = 0;
  int b = 0;
 
  std::cin >> a;
  std::cin >> b;
 
  swap(a,b);
 
  std::cout << a << " " << b << std::endl;
  return 0;
}

Fix it passing arguments by reference.

Exercise 6: Swap function (2)

Now fix it using pointers in the swap function.

Exercise 7: Transpose of a matrix

The following program should get size and values of a matrix from the user and then it should show its transpose.

#include <iostream>
 
int main(int argc, char** argv)
{
  // get the size of the matric
 
  int n = 0;
  int m = 0;
 
  std::cin >> n;
  std::cin >> m;
 
  // create the matrix
 
  int** matrice = 0;
 
  // To do: 
  // 1. Allocate memory and get values from the user
  // 2. Show the transpose
 
  return 0;
}

Complete it, then download inputTransposition1.txt. and test your code with the command

./your_program < inputTransposition1.txt 

You should get:

17 8 75
17 4 90

Exercise 8: Matrix multiplication

Modify your previous program and create one that gets two matrices and outputs their product.

Download inputMultiplication.txt.

Test your program with the command
./your_program < inputMultiplication.txt 

You should get:

10 10 10
10 10 10
10 10 10
10 10 10