Students in Computer Science would like to understand the concept of Ohm’s law. You are required to write an application that will allow them to calculate the relation between Voltage, Current and Resistance using the formulas below.
V = IR, Current (I) = V/R, Resistance= V/I, (where I is the current, V - Voltage and R is the resistance). The program must do the following:
Prompt the user for the calculation he/she would like to see or N/n to exit .
Based on the option selected by the user (I/I, V/v, R/r),
If an invalid option is selected an appropriate error message must be displayed.
NB: Use a switch for the selection If there are no calculations to performed, display a summary that consist of the number of calculations performed. This number must exclude the invalid options,
SOLUTION TO THE ABOVE QUESTION
SOLUTION CODE
#include <iostream>
using namespace std;
//lets define fiunctioms to perform our operations
//A function to calculate Voltage(V)=IR
void voltage()
{
cout<<"\n\tEnter the value of Current(I): ";
double I;
cin>>I;
cout<<"\n\tEnter the value of Resistance(R): ";
double R;
cin>>R;
//calculate the volatge
double V = I*R;
cout<<"\tThe Voltage(V) = "<<V<<" Volts"<<endl;
}
//A function to calculate Resistance (R)= V/I
void resistance()
{
cout<<"\n\tEnter the value of Voltage(V): ";
double V;
cin>>V;
cout<<"\n\tEnter the value of Current(I): ";
double I;
cin>>I;
//calculate the resistance
double R = V/I;
cout<<"\tThe Resistance(R) = "<<R<<" ohms"<<endl;
}
//A function to calculate Current(I)=V/R
void current()
{
cout<<"\n\tEnter the value of Voltage(V): ";
double V;
cin>>V;
cout<<"\n\tEnter the value of Resistance(R): ";
double R;
cin>>R;
//calculate the current
double I = V/R;
cout<<"\tThe Current(I) = "<<I<<" amperes"<<endl;
}
int main()
{
//Now lets code the menu
cout<<"\n\tEnter the operation to perform: "<<endl;
cout<<"\tV/v.Calculate Voltage"<<endl;
cout<<"\tR/r.Calculate Resistance"<<endl;
cout<<"\tI/i.Calculate Current"<<endl;
cout<<"\tN/n.Exit the program"<<endl;
cout<<"\n\tEnter your option: ";
char option;
cin>>option;
switch(option)
{
case 'V':
//call voltage function
voltage();
break;
case 'v':
//call voltage function
voltage();
break;
case 'R':
//call resistance function
resistance();
break;
case 'r':
//call resistance function
resistance();
break;
case 'I':
//call current function
current();
break;
case 'i':
//call current function
current();
break;
case 'N':
cout<<"\n\tProgram successfully exited"<<endl;
break;
case 'n':
cout<<"\n\tProgram successfully exited"<<endl;
break;
default:
cout<<"\nYou have entered an Invalid option, please try again"<<endl;
}
}
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment