Click here to Skip to main content
15,896,348 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
I am having trouble with this language and being specific in your answers (ie. exactly where things go and for what reason please)will help me a great deal I cant seem to understand when and where these if while and for statements are to be placed in order for them to work and where the cin should be placed in order for it to be in the correct order.
thanks to all who help I really need explanations on this reading the material is getting me confused.


write a program that asks the user to enter how many numbers
they would like to enter.

Read in that many numbers from the user and calculate the
total, average, highest, and lowest numbers,
and the number of even and odd numbers.

Your program should then display all of that information back
out to the user. Your program should also use a for loop to
control the number of numbers entered by the user.



C++
#include <iostream>

using namespace std;

int main() {

	int total = 0;
	int grade = 0;

	for (int curGrade = 5; curGrade > 0; curGrade--) {
		cout << "Enter a grade: ";
		cin >> grade;
		total += grade;
	}

	cout << "Average = " << total / 5;

	return 0;
}
Posted
Updated 14-Oct-10 20:19pm
v3

First I will give you the code, then I wil explain.

/*
Collect numbers from user, then perform basic operations on them.
*/
#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
//first step: declare our variables
    int i=0; //holds the index for our loop.
    int input=0; //holds the numbers a user would like to collect.
    int lowest = 0; //holds the lowest number.
    int highest = 0; //holds the highest number.
    int total = 0;
    cout << "How many numbers do you want to input?";
    cin >> input;
//Now we use an if statement to make sure input isn't less than one, or more than 100.
    if ((input < 1) || (input > 100)) {
        cout << "You must use a number between 1 and 100." << endl;
        return 1;
    }

//now we create an array.
    int *numbers = new int[input];
//now we iterate through the array and accept numbers.
    for (i=0; i < input; i++) {
        cout << "Please enter entry " << i+1 << "." << endl;
        cin >> numbers[i];
    }

//now we iterate through again and pick out the numbers.
//first, we set lowest to numbers[0], otherwise it won't get set
    lowest = numbers[0];
    for (i=0; i < input; i++) {
//add the entry to the total.
        total += numbers[i];
//check for the highest number.
        if (numbers[i] > highest) {
            highest=numbers[i];
        }
        if (numbers [i] < lowest) {
            lowest=numbers[i];
        }
    }

//now we show the stetistics:
    cout << "Average: " << total/input << "." << endl;
    cout << "lowest: " << lowest << " highest: " << highest << "." << endl;
    delete []numbers;
    return 0;
}
</iostream>


Now: here is my explaination:
//first step: declare our variables
    int i=0; //holds the index for our loop.
    int input=0; //holds the numbers a user would like to collect.
    int lowest = 0; //holds the lowest number.
    int highest = 0; //holds the highest number.
    int total = 0;

As the code says, this just declares the variables. It is good to have your declarations at the top, because they are easier to track down.
    cout << "How many numbers do you want to input?";
    cin >> input;
//Now we use an if statement to make sure input isn't less than one, or more than 100.
    if ((input < 1) || (input > 100)) {
        cout << "You must use a number between 1 and 100." << endl;
        return 1;
    }

So, we get the input from the user, then do some error checking. This is something you'll want to get in the habbit of doing; when getting input from the user, check on some bounds. If not, you'll get some clever hacker that says, "I wonder what happens if I supply -1!
//now we create an array.
    int *numbers = new int[input];

I know you haven't covered this, but this is one of the better ways to do it. Another way would be to add everything up, then do your calculations as your getting input; Iwill provide the code for this, as well.
Basically, an array is just a set of variables, which you will get to eventually, but it's a way to hold multiple variables of the same type, so you could do something like:
int tttBoard [3][3];

One thing you'll have to get used to that we use is starting at a 0 index, rather than one.
//now we iterate through the array and accept numbers.
    for (i=0; i < input; i++) {
        cout << "Please enter entry " << i+1 << "." << endl;
        cin >> numbers[i];
    }

This is one of the loops you were asking about, so let me explain:
A for loop will do something in order until the condition is met, so lets split it apart.
for (i=0...

This basically sets your counter (i) to 0.
i < input

The loop will keep going while this condition is true. In otherwords, while i is less than input. When I is equal to input, the loop will finish.
i++

Fore each time the loop is ran, (otherwise known as an iteration), I is incremented.
So, to sum up: The loop starts I at zero, the n runs until I is less than input (which is the max amount of numbers the user requested). So, this works because as we stated earlier, arrays run off of a zero index.
//now we iterate through again and pick out the numbers.
//first, we set lowest to numbers[0], otherwise it won't get set
    lowest = numbers[0];
    for (i=0; i < input; i++) {
//add the entry to the total.
        total += numbers[i];
//check for the highest number.
        if (numbers[i] &gt; highest) {
            highest=numbers[i];
        }
        if (numbers [i] < lowest) {
            lowest=numbers[i];
        }
    }

Again, we just run the loop over, with an if statement.
An if statement looks something like this:
if (condition)
{
do something
}

So, if the condition is met, for example:
if (numbers[i] < lowest)

which basically checks to see if the number is lower than numbers[i], and if so evaluates to true, we execute the code within the braces.
The rest of the code just deletes the array from the heap, prints the results, and returns 0.
I hope this helped. These are concepts that are not easily explained over a forum, but rather with a good book. I personally recommend thinking in C++, by Bruce eckel. It's a free download, just google the title. Skip chapter one (which just basically talks about OOP and will confuse you until later), and dig in.
 
Share this answer
 
v2
C++
#include <iostream.h>
#include <conio.h>
int main()
{
    clrscr();
    top:
    int size = 0;
    int sum,avearge,odd,even;
    cout<<"How many nos. do you want to enter";
    cin>>size;
    int *array = new int[size];
    count<<"Enter the numbers";
    for (int i = 0; i<size; i++)
    {
       cin>>array[i];
    }
    cout<<"Press 1 for sum\n"
        <<"Press 2 for average\n"
        <<"Press 3 for finding out highest and lowest\n"
        <<"Press 4 for finding out odd and even numbers\n";
   int opt;
   cin>>opt;
   switch(opt)
   {
      case 1:
      {
         for (int j=0 ; j<size; j++)         
         {
            sum+=array[j]; 
         }
         cout>>"The sum of the nos:\t"<<sum;
         break;
      }

      case 2:
      {
          cout>>"The average of the nos:\t"<<sum/size;
          break;
      }
      case 3:
      {
         for (int k=0; k<size;k++)         
         {
           if(array[k]%2==0)
           {
               odd++;
           }
           else
           {
               even++;
           }
         }
         cout>>"The total no. of odd nos:\t">>odd;
         cout>>"The total no. of even nos:\t">>even;
         break;
      }
      default:
      {
         cout>>"Sorry! No options available\n";
      }
   }
   delete[] array;
   cout>>"Do you want to continue(Y/N)?";
   char ans[1];
   cin<<ans;
   if(ans=="Y" || ans=="y")
   {
       goto top;
   }
   getch();
   return 0;
}
 
Share this answer
 
v3
Comments
Bikash Shrestha From Nepal 13-Oct-10 2:01am    
Good example Jipin Boka
CPallini 13-Oct-10 3:15am    
I believe 'case 2' not working whenever 'case 1' hasn't previously selected.
EDITH GINGRAS 13-Oct-10 7:21am    
You are a bit ahead of me here I am not understanding the while for and if do statements I am not ready for the array yet thanks for the idea thought need to get this down first thanks
Dalek Dave 15-Oct-10 4:03am    
Good Answer
I think there is no need for a switch over there. Total do you mean the sum of all the numbers read? if it is, my code would be like this
I repeat part of the code inside the for loop because it needs to compare it inside it too. I'll try to explain a bit.
"if" you use when you need to compare something or try a condition, like in "if i get grade greater than 60, i pass".
"else" is used in case when the "if" is not correct and you want another comparison(using another if after it) or an alternative,for ie if 1 get a grade greater tha 60 i pass, else i fail).
"for" you use when you need to repeat something for a known number of times. Sorry if i couldn't explain it better.
hope i helped a bit.

#include <iostream>;
#include <conio.h>//is not recommended to use it because is not considered standard
using namespace std;
int main()
{
  int qtyNumbers,odd=0,even=0,number,highest=0,lowest=0,total=0,i;
  float average=0;

  cout << "Please Informe the quantity of numbers you wish to enter: ";
  cin >> qtyNumbers;
  cout << "Enter a number: ";
  cin >> number;
  if(number % 2 ==0) //if the rest of number divide by 2 is zero
  {
    even++; //adds 1 to even
  }
  else odd++; //else the number is odd
  highest = number; // i placed this one outside the for because you will compare the other values against this one and the lowest one below, and also because the first value read will be both the lowest and the highest ones.
  lowest = number;
  total=total + number;
  for(i=1;i<qtyNumbers;i++) /*Like i explained above, for is used to repeat something for a known number of times, so, here you will repeat it for about the same number as the person asked inputs, if she inputs 7 numbers in the first question, then it will repeat here 6 times because you are already reading one number before the "for" loop. You use it whenever you need to repeat the same thing several times(but a limited number)*/
  {
     clearscr();
     cout << "Enter a number: ";
     cin >> number;
     total=total+number;
     if(number % 2 ==0) //if the rest of number divide by 2 is zero//this if goes here because every time a number is read, you need to compare if it is even or odd, that's when you use "if"
     {
       even++; //adds 1 to even
     }
     else odd++; //"else" is always used(when needed) after an "if"

     if(number > highest)//this is another condition you're trying,if the number is lower than the first number read.
     {
       highest = number; //if the above condition is true, than it will enter here and modify the highest number.
     }
     else
     if(number < lowest)
     {
       lowest = number; //else if the number is lower than the lowest one before, it will modify it. a good thing to explain is that it "enters" the scope only if the condition is true in here, if both cases are not true, > highest or < lowest, nothing will happen to those values(lowest and highest).
     }
  }
  average = (float)total/qtyNumbers; //need to cast(force it to be float) it to get division correcly
  cout << "the total is: "<<total <<endl;
  cout << "the average value is: " <<average <<endl;
  cout << "the highest number is: " <<highest <<endl;
  cout << "the lowest number is: " <<lowest <<endl;
  cout << "The total of odd numbers is: "<<odd<<endl;
  cout << "The total of even numbers is: "<<even<<endl;

}
 
Share this answer
 
v3
Comments
EDITH GINGRAS 13-Oct-10 7:26am    
yes thanks but I still do not understand why its placed where it is and how can I tell where it goes? I am feeling overwhelmed because I cant get this in my head your answer is good but I want to understand how this is figured out step by step if you dont mind with explanations along the way
If you are new to programming, it is always better to write an algorithm / psuedocode in plain text before writing the actual code.

So, by seeing the above problem, I would write my algorithm as follows. I hope you will follow this for rest of your programs.

1. Ask the user how many numbers they want to enter.
2. Allow the user to enter a number and store it in a variable.
3. Say user enters the number n.
4. Ask the user to enter n numbers. Take an array of fixed length and fill them upto n numbers.
5. Allow the user to enter n numbers (repetitively)
6. Calculate total
7. Calculate average
8. Calculate highest.
9. Calculate lowest
10.Calculate even and odd numbers.
11. Display all the above calculations one by one.

I assume that you know how to declare variables and arrays. Because this is a starter program, let us consider the maximum array count to be 100. If you think arrays are not simple, first take out that impression from your mind. Arrays are just group of some variables. It actually makes life simple.

Upto step 4 it is plain simple code. I would use cout and cin. I would take an array and fill numbers.

In Step5. I would take a for loop. Array index starts from 0 and I would allow the user to enter total of n numbers.

Step6 to Step10 are sub tasks. I would actually write seperate functions to perform subtasks. They increase readability and those functions can be used again and again (reusability). for a starter, better write this without functions. Once you are done writing succesful code without functions, you can move the code to functions.

It is better to write algorithms for subtasks again.

For Total:
1. iterate through all values of array upto n.
2. sum up all numbers.

For average:
1. take the total and divide it by n.

For highest:
1. I need to use if statement because I need to check a condition.
2. take a variable called nHighestVal and initialize it with zero.
3. Iterate through all variables in the array upto n.
4. for each iteration, check if the current value in array is greater than nHighestVal. (if statement)
5. if the value is greater, assign it to nHighestVal.

Like wise, write algorithms for rest of subtasks.

By the way, how old are you? I am just curious.
Is this your homework? If you are seriously learning, People here are very intersted to help. If you are asking us to complete your homework, we really have lot of work to do. Hope you understand.

Improved answer on 18/Oct/2010.

If you have not gotten upto arrays, then this problem is not best suited for writing a program with simple variables. The problem clearly states 'Read in many numbers'. So, an array is required to accomodate those many numbers.

Here is why. Suppose say I have 100 students in a class and I need to enter and sum up all their grades. Let us see how we can do. If we need to store all grades without arrays, we need to take 100 variables.
int grade1, grade2, ... gradeN;

and if I need to add these,
sum = grade1 + grade2 + gradeN;

You can see that it is very difficult to store, access and maintain all these without arrays.

int grade[100]; // 100 students.
sum = grade[0] + grade[1] + ..... grade[99];

Even the above is pain taking. This can be easily done with a for loop. But before that you can see that I am accessing my first variable with index 0 which is grade[0]. Like this you can access any variable in an array.

Using a for loop for array,
for(int i = 0; i < 100; i++) // which means: for i starting from 0, execute the following code block upto 99, increment i for each iteration.
{
cout << "Grade:" << grade[i] << endl; // get i'th grade and print
}

If you are not feeling comfortable, start with simple variables and take only 5 students. But for this, you don't have to take a for loop.
 
Share this answer
 
v3
Comments
EDITH GINGRAS 17-Oct-10 18:22pm    
oh I am sorry but I AM 50 YRS SO THANKS THAT IS WHY I ASKED FOR SPECIFIC ANSWERERS SO THAT I WOULD UNDERSTAND HOW IT ALL WORKS
EDITH GINGRAS 17-Oct-10 18:24pm    
I HAVE NOT GOTTEN TO UNDERSTAND ARRAYS YET AMS STILL ON THE WHILE DO FOR IF ELSE ELSE IF STAGE LOL
mk14882 17-Oct-10 22:31pm    
LOL, I first thought you are college kid and answered like a big brother. Please do not consider my words on homework then. When I was learning programming languages in an institute during my college days, I sat beside a grandpa, aged 60. I was amazed to see his interest. Anyway, I must tell you, for any starter it may take some 3 months to get basics. So have patience :)

Please see my reply above in the solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900