Share This

Comp116 Lab Exercise Series : Lab 1

We've started to share the lab exercises of Object Oriented Programming course of this running semester. While we will share fully working code, we expect you to grab the idea from codes and try writing the code on your own. This way, it will help you learn the language.

To access the lab exercises, you can visit the official webpage by clicking here. In this episode, we will post the lab 1's solutions.
Question #1
Write a C++ program that reads three coefficients a, b and c for quadratic equation and finds whether the solutions are in real or imaginary. (ax2 + bx + c = 0 if b2-4ac >=0 then the solutions are real.)

/*
*Compiled using g++
*g++ -o 1_1 1_1.cpp
*/
#include <iostream>

using namespace std;

int main()
{
 int a, b, c, m;
 cout << "Enter the values of a, b and c: ";
 cin >> a >> b >> c;
 m = (b * b) - (4 * a * c);
 if (m >= 0)
 {
  cout << "Roots are real" << endl;
 }
 else
 {
  cout << "Roots are imaginary" << endl;
 }
 return 0;
}

Question #2
Write a C++ program that reads three coefficients a, b and c for quadratic equation and finds whether the solutions are in real or imaginary. (ax2 + bx + c = 0 if b2-4ac >=0 then the solutions are real.)
/*
*Compiled using g++
*g++ -o 1_2 1_2.cpp
*/
#include <iostream>

using namespace std;

//returns largest number in array arr[] of size n
int get_largest(int arr[], int n)
{
 int largest = arr[0]; //assume first element is largest, now we perform 'less than' test with it
 for (int i = 1; i <= n; i++)
 {
  if (largest < arr[i])
  {
   largest = arr[i];
  }
 }
 return largest;
}

int main()
{
 int a[10], largest;
 for (int i = 0; i < 10; i++)
 {
  //do while loop for asking positive number when -ve value is given
  do
  {
   cout << "Enter the " << i+1 << "th number: ";
   cin >> a[i];
  } while (a[i] < 0);
 }
 largest = get_largest(a, 10);
 cout << "The largest number is " << largest << endl;
 return 0;
}

Please report us if there's any bug in the codes though we've tested them thoroughly.

0 comments:

Post a Comment

Followers