Starting from:

$30

EC327-Homework 3 Solved

Total: 100 points 
 

Q1. Loops, functions. 
 

Implement a function to calculate the greatest common divisor (gcd) of two positive integers. The function will need to have the following prototype: 

 

int gcd(int x, int y);

 

Given two positive integers, it must return their gcd. Implement your lcm function in a file named Q1.cpp. Include the gcd function only in this file (plus any #includes that the function might need, the appropriate namespace declaration etc.). The gcd function should not check for invalid values (e.g., negative numbers as input). Instead, we provide two files (Q1.h and Q1main.cpp) to test your code, but you are not supposed to submit those for grading. Submit only Q1.cpp.  

 


Q2. Strings. 
 

Implement a function replace with the following prototype:

 

void replace(string &s, char c1, char c2);

 

The function parses the string passed as an argument and substitutes any occurrence of character c1 with character c2. For example, replace(“hello”,’l’,’X’) will modify the string to be “heXXo”. Implement the function in a file named Q2.cpp. We provide two files (Q2.h and Q2main.cpp) to test your code, but you are not supposed to submit those for grading. Submit only Q2.cpp.

 

Q3. File I/O. 
 

You are given a file grades.txt in the format <student ID, class, grade> as follows:

 

123456 EC327 91

493218 EC330 67

904531 EC327 82

 

Implement a function calculateAverage with the following prototype:

 

float calculateAverage(string class, string filename);

 

The function reads the file passed in the filename parameter and calculates the average grade for the class passed in the class parameter. For example, by calling calculateAverage(“EC327”,”grades.txt”) the function would parse the file above and return 86.5 (as a float). Implement the function in a file named Q3.cpp. We provide two files (Q3.h and Q3main.cpp) to test your code, but you are not supposed to submit those for grading. Submit only Q3.cpp.

 

Q4 Recursion. 
 

Write a recursive function to calculate triangular numbers. The function must follow this prototype: 

 

int triangular(int num);

 

Given a positive number “num”, it must return the correct triangular number (as an integer). For example, triangular(6) will return 21, according to the following scheme:

 
 

Implement your triangular function in a file named Q4.cpp. Include only the triangular function in this file (plus any #includes that the function might need, the appropriate namespace declaration etc.). We provide two files (Q4.h and Q4main.cpp) to test your code, but you are not supposed to submit those for grading (i.e., we will use our own main implementation). Submit only Q4.cpp.  

More products