Friday, July 31, 2009

C++ Programming Question?

I'm having a little trouble figuring a successful program for this problem... any help would be appreciated!!





Write a C++ program that first asks the user how many numbers will be entered - let's call this positive integer n. Then the program reads n integers (not ordered) and outputs how many even values and how many odd values have been entered. The input should be restricted to only integers between 0 and 100.

C++ Programming Question?
I won't give you the code, but I will give you some pseudocode that should help alot :





- intialize a counter for evens, and one for odds


- get the # of numbers to be entered by user


- start loop based on the number entered


- for each pass of the loop, get a number from user


- use the modulus operator (%) with the number 2 to determine if the number is even (e.g. 16 % 2 = 0, 15 % 2 = 1) so if the answer is 0, number is even


- increment appropriate counter





FYI - if your instructor hasn't already told you, I will : always do some pseudocode first, especially if you are having trouble. That way, you don't worry about the syntax, and can focus on the logic. Once the logic is right, the syntax is a piece of cake. Good luck : )
Reply:First get their input and store it to variable "n"


Then use a for loop to get that many numbers


As each number is entered, do number modulus 2


Use If to detect if it is even or odd (0=even 1=odd)





#include %26lt;iostream%26gt;





int main ()


{


int n;


int i;


int x;


int odd;


int even;





cout %26lt;%26lt; "Please enter a value: ";


cin %26gt;%26gt; i;


for(i=0,i%26lt;n,i++){


cout %26lt;%26lt; "Please enter a value: ";


cin %26gt;%26gt; x;


x = x%2;


If x{


odd += 1;


Else


even += 1;


}


}


cout %26lt;%26lt; even;


cout %26lt;%26lt; " are even";


cout %26lt;%26lt; odd;


cout %26lt;%26lt; " are odd";

clear weed

No comments:

Post a Comment