In: Computer Science
Loops
Write a simple C/C++ console application that will calculate the equivalent series or parallel resistance. Upon execution the program will request ether 1 Series or 2 Parallel then the number of resisters. The program will then request each resistor value. Upon entering the last resistor the program will print out the equivalent resistance. The program will ask if another run is requested otherwise it will exit.
The language used is C++.
Code:
#include<iostream>
using namespace std;
//This function calculates the equivalent series
resistance
double seriesEquivalent(double resistors[], int numberOfResistors)
{
double sum = 0;
//Equivalent series resistance is simply the sum of
resistances.
for(int i=0;i<numberOfResistors;i++)
sum += resistors[i];
return sum;
}
//This function calculates the equivalent parallel
resistance.
double parallelEquivalent(double resistors[], int
numberOfResistors) {
double sum = 0;
for(int i=0;i<numberOfResistors;i++)
sum += 1/resistors[i];
//Equivalent resistance is the reciprocal of sum.
return (1/sum);
}
int main() {
while(true) {
//Get the required inputs from the user.
int input;
int numberOfResistors;
cout<<"Press 1 for Series and 2 for Parallel\n";
cin>>input;
if(input != 1 && input != 2){
cout<<"Wrong input. Try again";
continue;
}
cout<<"Enter the number of resistors:\n";
cin>>numberOfResistors;
double resistors[numberOfResistors];
cout<<"Enter the values of
"<<numberOfResistors<<" resistors:\n";
for(int i=0;i<numberOfResistors;i++)
cin>>resistors[i];
if(input == 1) {
cout<<"\nEquivalent series resistance:
"<<seriesEquivalent(resistors,
numberOfResistors)<<endl;
}else if(input == 2) {
cout<<"\nEquivalent parallel resistance:
"<<parallelEquivalent(resistors,
numberOfResistors)<<endl;
}
char repeat;
cout<<"Press y to repeat and other key to exit: ";
cin>>repeat;
if(repeat != 'y' && repeat != 'Y')
break;
}
return 0;
}
Code Snippets:
Sample Output: