Monday, July 27, 2009

What would the code look like if this problem was designed using C++ programming?

Write a C++ Program to count the total number of occurrences of the number '2' in a series of 10 numbers input by the user.





Two codes must be submitted, one which implements the above task using a WHILE loop, and the other which implements the above task using a FOR loop.

What would the code look like if this problem was designed using C++ programming?
Why not write one program with 2 functions, one using while loop and the other using for loop?


Try this:





#include%26lt;iostream.h%26gt;


using namespace std; //don't use it if u r using an old compiler





class counter{


int input,cnt;


int inputs[10];


public:


counter();


void get_input(int ); //so that you can search other numbers also, not only 2


void cal_for();


void cal_while();


};





counter::counter()


{


cnt=0;


for(int i=0;i%26lt;10;i++)


inputs[i]=0;


}





void counter::get_input(int m)


{


input=m;


}





void counter::cal_for()


{


cout%26lt;%26lt;"Input 10 numbers:\n";


for(int i=0;i%26lt;10;i++)


{


cin%26gt;%26gt;inputs[i];


if(inputs[i]==input)


cnt++;


}


cout%26lt;%26lt;"The number of occurence of the number"%26lt;%26lt;input%26lt;%26lt;"in this series of inputs is:"%26lt;%26lt;cnt%26lt;%26lt;"\n";


}





void counter::cal_while()


{


cout%26lt;%26lt;"Input 10 numbers:\n";


int i=0;


while(i%26lt;10)


{


cin%26gt;%26gt;inputs[i];


if(inputs[i]==input)


cnt++;


i++;


}


cout%26lt;%26lt;"The number of occurence of the number"%26lt;%26lt;input%26lt;%26lt;"in this series of inputs is:"%26lt;%26lt;cnt%26lt;%26lt;"\n";


}





int main()


{


counter C;


int a;


cout%26lt;%26lt;"What is the number you are looking for?\n";


cin%26gt;%26gt; a;


C.get_input(a);


cout%26lt;%26lt;"\n";


C.cal_for();


C.cal_while();


return 0;


}





One more thing. I don't have a c++ compiler here. So I couldn't check and debug it before sending. Hope you will be able to fix syntax errors if there is any.:)
Reply:let me just write out a possible for and while in a pseudo-code that you could use.





for(counter=initial value; exit condition(s); [change counter's value])


body of the loop;





counter=initial value;


while([not] exit condition)


body of the loop with some way to change counter's value;





work out the rest. Homework assignment? Perhaps ask in homework section.


No comments:

Post a Comment