For loop

G

geletine

I have been asked to design and create a program that reads in a
sequence of student grades and computes the average grade, the number
of students who pass (a grade of at least 60) and the number who fail.
The program will print the total number of students, average grades,
number of students who pass and number of students who fail.

I may be looking at the problem in the completely wrong way but here is
my first attempt of the code

import java.io.*;
public class grades
{
public static void main (String args [])throws IOException

{

int totalstudents, averagegrade, numberofgrade, numberofstudents,
total;

String information ;

BufferedReader stgin = new BufferedReader ( new InputStreamReader (
System.in ) );
total = 0;
numberofstudents = 0;
totalstudents = 0;
averagegrade = 0;

System.out.println ("Enter the number of students");
information = stgin.readLine();
numberofstudents = Integer.parseInt (information) ;

System.out.println ("Enter grade of a student");
information = stgin.readLine();
numberofgrade = Integer.parseInt( information );

for ( numberofgrade = 1; numberofgrade >= 60; )
{
numberofstudents = numberofstudents + totalstudents;
total = total + numberofgrade ;
averagegrade = total / numberofgrade;
}

System.out.println ( " Total amount of students entered" +
totalstudents );
System.out.println ( " The average student grade is " + averagegrade);
System.out.println ( " Total amount of students that passed is " +
information );

for ( numberofgrade = 1; numberofgrade <60; )
{
numberofstudents = numberofstudents + totalstudents;
total = total + numberofgrade;
averagegrade = total / numberofgrade;
}
System.out.println ( " Total amount of students entered" +
totalstudents );
System.out.println ( " The average student grade is " + averagegrade);
System.out.println ( " Total amount of students that passed is " +
information);
}
}
 
I

Ian Mills

geletine said:
I have been asked to design and create a program that reads in a
sequence of student grades and computes the average grade, the number
of students who pass (a grade of at least 60) and the number who fail.
The program will print the total number of students, average grades,
number of students who pass and number of students who fail.

I may be looking at the problem in the completely wrong way but here is
my first attempt of the code

import java.io.*;
public class grades
{
public static void main (String args [])throws IOException

{

int totalstudents, averagegrade, numberofgrade, numberofstudents,
total;

String information ;

BufferedReader stgin = new BufferedReader ( new InputStreamReader (
System.in ) );
total = 0;
numberofstudents = 0;
totalstudents = 0;
averagegrade = 0;

System.out.println ("Enter the number of students");
information = stgin.readLine();
numberofstudents = Integer.parseInt (information) ;

System.out.println ("Enter grade of a student");
information = stgin.readLine();
numberofgrade = Integer.parseInt( information );

for ( numberofgrade = 1; numberofgrade >= 60; )
{
numberofstudents = numberofstudents + totalstudents;
total = total + numberofgrade ;
averagegrade = total / numberofgrade;
}

System.out.println ( " Total amount of students entered" +
totalstudents );
System.out.println ( " The average student grade is " + averagegrade);
System.out.println ( " Total amount of students that passed is " +
information );

for ( numberofgrade = 1; numberofgrade <60; )
{
numberofstudents = numberofstudents + totalstudents;
total = total + numberofgrade;
averagegrade = total / numberofgrade;
}
System.out.println ( " Total amount of students entered" +
totalstudents );
System.out.println ( " The average student grade is " + averagegrade);
System.out.println ( " Total amount of students that passed is " +
information);
}
}

I don't want to be too critical but it looks rather as if you have just
sat down and written some code without really thinking about what you
are trying to achieve. The code above will only ever accept one score
and I think you need to look again at the use of for loops as neither
yours will work. I would strongly suggest sitting down and working out
the flow of your application first (using something like a flow diagram
or whatever method you prefer) before you start coding.
 
G

geletine

I thought the line
for ( numberofgrade = 1; numberofgrade >= 60; )
meant if the numberofgrade entered is 60 or more to do what is in that
first for loop if not goto the 2nd for loop for ( numberofgrade = 1;
numberofgrade <60; )
and carry out what is in this loop, what the program is actually doing
is just outputing to the screen the number i entered on the first
question and the other questions are asked but nothing is stored to any
variables. Its the first time i have coded for loops in any programming
language , any tips i would appreactiate.

thank you
 
P

P.Hill

geletine said:
I thought the line
for ( numberofgrade = 1; numberofgrade >= 60; )
meant if the numberofgrade entered is 60 or more to do what is in that
first for loop if not goto the 2nd for loop for ( numberofgrade = 1;
numberofgrade <60; )

for ( numberofgrade = 1; numberofgrade >= 60; move the index somehow )
A for can be rewritten as

numberofgrade = 1;
while ( numberofgrade >= 60 ) {

move the index somehow;
}

I think you have the idea wrong.

-Paul
 
R

Roedy Green

System.out.println ("Enter the number of students");
information = stgin.readLine();
numberofstudents = Integer.parseInt (information) ;

System.out.println ("Enter grade of a student");
information = stgin.readLine();
numberofgrade = Integer.parseInt( information );

for ( numberofgrade = 1; numberofgrade >= 60; )
{
numberofstudents = numberofstudents + totalstudents;
total = total + numberofgrade ;
averagegrade = total / numberofgrade;
}

This is a very 60s way of doing things, to make life easy for the
computer. The person entering does not know in advance how many
students he will enter. So instead you ask him to keep entering until
he is done, letting you know when he is done by entering some special
marker e.g. 0, 99999, or by triggering an EOF (hitting Ctrl-Z on the
console).

Think about which things you do just once and which things you do for
each student. The thing for each student go INSIDE the loop.
Ditto for calculation. Which things do you do as you go, and which do
you do when you have collected all the students?

Try running your program printing out all your variables as you go.
Your loop confusion should become obvious.
 
G

geletine

Unfortunately i could not view your webpage , the plugin would not
install

When you say "Think about which things you do just once and which
things you do for
each student. The thing for each student go INSIDE the loop.
Ditto for calculation. Which things do you do as you go, and which do
you do when you have collected all the students?"

do you mean i only need one for loop?
 
B

Big Jim

geletine said:
I thought the line
for ( numberofgrade = 1; numberofgrade >= 60; )
meant if the numberofgrade entered is 60 or more to do what is in that
first for loop if not goto the 2nd for loop for ( numberofgrade = 1;
numberofgrade <60; )
and carry out what is in this loop, what the program is actually doing
is just outputing to the screen the number i entered on the first
question and the other questions are asked but nothing is stored to any
variables. Its the first time i have coded for loops in any programming
language , any tips i would appreactiate.

thank you
I think you're mixing up "for" and "if" (conditional) statements
 
B

blmblm

[ snip excellent advice ]
or by triggering an EOF (hitting Ctrl-Z on the
console).

Not-entirely-on-topic nitpick:

How to signal EOF is system-dependent -- it's Ctrl-Z for MS-DOS
(and its emulation under Windows, if that's the way to describe the
DOS-prompt thingie), all right, but Ctrl-D for all the Unix/Linux
shells I know. (Anyone know of other systems for which it's
different? though this is probably a question for another newsgroup,
since I strongly suspect we're mostly Windows and Unix/Linux here,
with maybe a smattering of Mac OS?)

[ snip ]

| B. L. Massingill
| ObDisclaimer: I don't speak for my employers; they return the favor.
 
G

geletine

This is a perhaps a very late reply, as i have been busy , I feel i am
getting closer to the solution, but i am not quite there , here is the
improved code

import java.io.*;
public class grades
{
public static void main (String args [])throws IOException

{

int averagegrade, grade, numberofstudents, totalgrades,storage;

String information ;

BufferedReader stgin = new BufferedReader ( new
InputStreamReader ( System.in ) );
storage = 0;
totalgrades = 0;
grade = 0;
averagegrade = 0;
System.out.println ("Enter the number of students");
information = stgin.readLine();
numberofstudents = Integer.parseInt (information) ;


for ( numberofstudents = 1; numberofstudents >= storage ;
numberofstudents ++ )
{
System.out.println ("Enter grade of a student");
information = stgin.readLine();
grade = Integer.parseInt( information );
totalgrades = totalgrades + grade;
}
averagegrade = totalgrades / numberofstudents;

if ( grade >= 60)
{
System.out.println ( " Total amount of students entered " +
numberofstudents );
System.out.println ( " The average student grade is " +
averagegrade);
System.out.println ( " Total amount of students that passed is
" + grade );
}
else
{
System.out.println ( " Total amount of students entered " +
numberofstudents );
System.out.println ( " The average student grade is " +
averagegrade);
System.out.println ( " Total amount of students that failed is
" + grade );
}
}
}
 
T

Tom Leylan

geletine said:
This is a perhaps a very late reply, as i have been busy , I feel i am
getting closer to the solution, but i am not quite there , here is the
improved code

Personally I would characterize it as "different" but would hesitate to call
it "closer". It was mentioned before that your decision to prompt for the
"number of students" as in "how much data are you going to enter" is
less-than-optimal. The user has no way out when they find out there aren't
25 students as first thought but only 24. You are forcing them to enter a
bogus 25th grade and then they have to enter all 25 again.

What does Java documentation say is the syntax for a FOR loop? In
particular what does it call the second parameter? It is referred to as the
"exit condition" so your loop will exit when numberofstudents is greater or
equal to storage and storage is equal to zero isn't it? It sounds like the
exist condition is met immediately. So the question becomes when you say
it's almost working does that mean it exits the loop without prompting to
enter the grade of a student? In that case it is almost a 1st person,
hi-res video game also... except it doesn't display any graphics and you
can't move around in a 3D world. :)

Remind yourself what the curly braces are used for in Java? So do you have
the correct code placed inside the curly braces of your FOR loop? Why
(having exited the loop) would you refer to the grade variable? It has a
value of zero or (with some modification) the value of the last grade
entered. If you didn't enter any grades it prints the number of failed
students (since the value is zero) and proclaims that zero students failed.
If you managed to enter 20 grades and the last grade was 10 it would report
that 10 students failed. That can't be what you intended.

I'm curious why you still haven't bothered to pseudocode the solution first
as it gives you a target to aim for. In my book I have a section on
pseudocoding where I point out the following:

<begin quote>
Pseudocoding has two main benefits. First, it gives us an opportunity to
identify coding problems or roadblocks. From the following examples of
pseudocode, we learn that we need a Random() function and discover that we
must either personally write a file transfer routine with Z-Modem protocol
or that we had better start looking for one:

/* get random number */

/* set com port to 9600 baud */
/* transfer "file" using zmodem */

The second advantage of using pseudocode may seem a bit brutal. The reality
of the situation is that if you cannot write an English-like version of the
application, you will almost certainly be unable to complete it in Clipper
or any other computer language.

Writing in pseudocode doesn't burden us with scoping rules, memory
limitations, the order of arguments to the TbrowseNew() function, or any of
the myriad of obstacles that computer languages present. Pseudocode has no
tangible bugs, only logical ones.

<end quote>

If you have the time try to post commented pseudocode rather than Java.
You'll finish the program far faster by "translating" to Java rather than
"architecting" with Java.

Hope this helps,
Tom

import java.io.*;
public class grades
{
public static void main (String args [])throws IOException

{

int averagegrade, grade, numberofstudents, totalgrades,storage;

String information ;

BufferedReader stgin = new BufferedReader ( new
InputStreamReader ( System.in ) );
storage = 0;
totalgrades = 0;
grade = 0;
averagegrade = 0;
System.out.println ("Enter the number of students");
information = stgin.readLine();
numberofstudents = Integer.parseInt (information) ;


for ( numberofstudents = 1; numberofstudents >= storage ;
numberofstudents ++ )
{
System.out.println ("Enter grade of a student");
information = stgin.readLine();
grade = Integer.parseInt( information );
totalgrades = totalgrades + grade;
}
averagegrade = totalgrades / numberofstudents;

if ( grade >= 60)
{
System.out.println ( " Total amount of students entered " +
numberofstudents );
System.out.println ( " The average student grade is " +
averagegrade);
System.out.println ( " Total amount of students that passed is
" + grade );
}
else
{
System.out.println ( " Total amount of students entered " +
numberofstudents );
System.out.println ( " The average student grade is " +
averagegrade);
System.out.println ( " Total amount of students that failed is
" + grade );
}
}
}
 
G

geletine

Hello,
regarding your first point, i have no say in what the final application
should do, i just have to write it.
the programs i am to build are just learning steps , there is no real
value in any of them, netherless i have to complete them.

I fully understand the value of pseudocode, and i believe that is where
this program is failing, after all computer languages are only tools.
If i were to speak grammatically correct english, but the sentence made
no sense, the exercise would get me no where. The same is true with
programming, adapting the program to work by applying the correct
syntax and ignoring the actual algorithm or implementing a poorly
thought out one would be a complete defeat.

I am inserting the new pseudocode, which should explain where i am
needing improvement.

Read the number of students
Start for loop
Read a number for the first student
Student total grades = Student total grades + student grade
End loop
Calculate average grade for the students
If the student grade is greater than 60
Print to the screen total amount of students
Print to the screen the average grade
Print to the screen the student has passed

Else
Print to the screen total amount of students
Print to the screen the average grade
Print to the screen the student has failed
 
T

Tom Leylan

geletine said:
regarding your first point, i have no say in what the final application
should do, i just have to write it.

That's right but remember you are interpreting the specs, nobody supplied
the pseudocode. So did the spec say that you have to prompt for the number
of students or did you figure that would be the best solution? The answer
doesn't matter but I'm asking so you don't take it for granted if nothing in
the exercise actually said that.
the programs i am to build are just learning steps , there is no real
value in any of them, netherless i have to complete them.

That is their value.
If i were to speak grammatically correct english, but the sentence made
no sense, the exercise would get me no where. The same is true with
programming...

If you wrote down what you were planning to say and read it back you would
be aware that it made no sense. At that point you would reword it. In any
case we aren't targetting poorly written explanations... you'll know you
have a good one when you see it.
Read the number of students
Start for loop
Read a number for the first student
Student total grades = Student total grades + student grade
End loop
Calculate average grade for the students
If the student grade is greater than 60
Print to the screen total amount of students
Print to the screen the average grade
Print to the screen the student has passed

Else
Print to the screen total amount of students
Print to the screen the average grade
Print to the screen the student has failed

You can almost see (and I have to guess) that that couldn't be the
assignment. Your loop is keeping track of multiple student grades and after
you exit the loop you refer to a particular student grade and print whether
a single student has passed or failed. But clearly you are outside the loop
so the concept of "the student just entered" has no meaning. If you want to
print whether each student passed or failed it has to be inside the loop.
If on the other hand you want to print the total number of students who
passed or failed you aren't capturing enough information inside the loop.

Do you see the problem? "If the student grade is greater than 60" which
student? "Print to the screen the student has failed" which student?

It is also the "total number of students" and the "sum of the grades" not
really the "total amount of students". Not that this is the problem but
when things get confusing, simplify them. You can get lost (when you're
almost lost) by simply making bad variable name choices. Not that you did
it but people name things X, Y and Z and then wonder why they can't remember
what Z was used for.

So... don't write any code yet instead, refine your pseudocode. Decide
which student you are saying has passed or failed. Maybe those lines aren't
in the right spot.

Not to belabor the point but consider simplifying the pseudocode as well.
It's "input number of students" and "output total number of students"
whether they are "read" or printed to the screen isn't significant at this
point. I'm not trying to cause you grief but I can see you're getting stuck
on details that don't matter and ignoring the real meat which is "who is
that student" you keep referring to outside of the loop?

Hope this helps,
Tom
 
G

geletine

Hello
So did the spec say that you have to prompt for the number
of students or did you figure that would be the best solution?

It would make sense to ask for a users grade and then ask if they want
another and then when they don;t to exit the loop, but unfortunately i
have to determine the amount of grades to be entered first.
If on the other hand you want to print the total number of students who
passed or failed you aren't capturing enough information inside the loop.

that is what i am been assigned to do.

I have hopefully arranged the pseudocode slightly better now..

Read the number of students
Start loop
Read a number for the first student
Student total grades = Student total grades + student grade
End loop
Calculate average grade for the students
If the student grade is greater than 60
calculate how many students got grades 60 and above ??
Else
calculate how many students got grades 59 and below??

Print to the screen total amount of students
Print to the screen the average grade
Print to the screen the amount of students that have passed
print to the screen the amount of students that have failed


i believe with some thought that i am on the right side of road..
 
T

Tom Leylan

geletine said:
It would make sense to ask for a users grade and then ask if they want
another and then when they don;t to exit the loop, but unfortunately i
have to determine the amount of grades to be entered first.

Good enough reason, I just wanted to make sure :)
Read the number of students
Start loop
Read a number for the first student
Student total grades = Student total grades + student grade
End loop
Calculate average grade for the students
If the student grade is greater than 60
calculate how many students got grades 60 and above ??
Else
calculate how many students got grades 59 and below??

Print to the screen total amount of students
Print to the screen the average grade
Print to the screen the amount of students that have passed
print to the screen the amount of students that have failed
i believe with some thought that i am on the right side of road..

I think you are definitely closer. This line: "If the student grade is
greater than 60" is still suspect. Again if you mean the last student
entered it would work but that is a very odd spec for a school project.
Seriously you could post the assignment and we can figure out the
pseudocode. Notice you are actually "ahead" in the process. At first you
were trying to write a Java app without knowing the goal. At least now you
can reword the thing repeatedly without bothering with Java syntax. Resist
the temptation to start coding before you have a defined target. Is 60 the
passing grade? Is the assignment to use a for loop or can you use any type
of loop?

Look the following over. Note that I try to avoid things like "to the
screen", "calculate average" and even "if student grade is greater than 60"
because your first pass needn't include that kind of detail. I will output
the studentAverage so it infers I will need to calculate it. I don't need
to calculate it anywhere in particular however perhaps I can do it inline
when I output it. I don't exactly know what constitutes passed or failed
either. It will be 60 but for me to outline routine doesn't require that
information. Something will determine it but what I need to do is keep
track of the total.

// get studentCount
// while counter < studentCount
// get grade
// total passedCount
// total failedCount
// total gradeTotal
// end

// output studentCount
// output studentAverage
// output passedCount
// output failedCount

Is this what you want it to do? If so do you want to try the next step?
Create a Java app and place the pseudocode in a method. Notice I made them
comments so you can imbed them in your routine. I probably wouldn't put
place it directly in main or all you get is an app which can compute this
one thing. Yes I know that is the assignment but why not create a framework
that the next assignment can use also? Have your main method can call
getGrades() or something like that.

In any case define and initialize the count variables you need (not the loop
ones yet). Add the output lines (in Java) and have them output the proper
variables. Now compile and run and lo and behold it should produce your
output. The numbers will all be zero but hey you're part way there. If
there are no errors you proceed to step two. Add the code to input the
studentCount. Compile and run it again. Still working, great go on to step
3. Add a line to input a grade... you still don't need the loop. Compile
and run. Notice how if at any time it stops working you can look over what
you just did. There won't be 50 lines of Java to hunt through there will be
the 4 or 5 you just added.

So now add the loop. If the output worked in step 1 and the input worked in
steps 2 and 3 then I'm going to guess there are no surprises and the entire
thing works as expected.

Let us see the final results and gosh I hope it is prettier than the first
one :) Don't forget to make the pass/fail value a constant (static final).
You don't want magic numbers like 60 appearing in the middle of your code.

Hope this helps,
Tom
 
G

geletine

I have really appreciated all your help :) its been a great experience
learning from my mistakes
I have finally got the program working...

pseudocode

Read the number of students
Start loop
Read a number for the first student
Student total grades = Student total grades + student grade
If the student grade is 60 or greater
store the amount of times the number reaches this statement by 1
Else
store the amount of times the number reaches this statement by 1
End loop
Calculate average grade for the students
Print to the screen total amount of students
Print to the screen the average grade
Print to the screen the amount of students that have passed
print to the screen the amount of students that have failed

and here is the java code

import java.io.*;
public class grades
{
public static void main (String args [])throws IOException

{

int averagegrade, grade, numberofstudents,
totalgrades,storage,sumpassed,sumfailed;
String information ;

BufferedReader stgin = new BufferedReader ( new InputStreamReader (
System.in ) );
sumpassed = 0;
sumfailed = 0;
numberofstudents = 0;
totalgrades = 0;
grade = 0;
averagegrade = 0;
System.out.println ("Enter the number of students");
information = stgin.readLine();
numberofstudents = Integer.parseInt (information) ;

for ( storage = 0 ; storage < numberofstudents ; storage ++ )
{
System.out.println ("Enter grade of a student");
information = stgin.readLine();
grade = Integer.parseInt( information );
totalgrades = totalgrades + grade;
if (grade >= 60)
{
sumpassed = sumpassed + 1 ;
}
else
{
sumfailed = sumfailed + 1 ;
}
totalgrades = totalgrades + grade;
}
averagegrade = totalgrades / numberofstudents;
System.out.println ( " Total amount of students entered " +
numberofstudents );
System.out.println ( " The average student grade is " + averagegrade);
System.out.println ( " Total amount of students that passed is " +
sumpassed);
System.out.println ( " Total amount of students that failed is " +
sumfailed );
}
}
 
G

geletine

by mistake i added twice, which doubles the average, i relised that
after
totalgrades = totalgrades + grade;
 
T

Tom Leylan

geletine said:
I have really appreciated all your help :) its been a great experience
learning from my mistakes

I truly believe that's the best way. Just a quick few notes. Obviously the
posting may not have retained your formatting but pretty counts. Lack of
readability impacts understanding and makes it much harder for somebody else
(and even the author weeks later) from understanding what the code does.
I'd take a moment to indent and align your code before you turn it in. The
exact format is up to you but be consistent. You might also consider using
the other math operators. Instead of the first example consider the second
one.

1) totalgrades = totalgrades + grade
2) totalgrades += grade

And you imbedded a "magic number" (60) in the middle of your program with no
explanation. Yes we can figure it out but it is much better to define it at
the top of the program. It gives it a name and all references (if you had
more) would use the same reference value.

Congratulations and pseudocode first, Java code second.

import java.io.*;
public class grades
{
public static void main (String args [])throws IOException

{

int averagegrade, grade, numberofstudents,
totalgrades,storage,sumpassed,sumfailed;
String information ;

BufferedReader stgin = new BufferedReader ( new InputStreamReader (
System.in ) );
sumpassed = 0;
sumfailed = 0;
numberofstudents = 0;
totalgrades = 0;
grade = 0;
averagegrade = 0;
System.out.println ("Enter the number of students");
information = stgin.readLine();
numberofstudents = Integer.parseInt (information) ;

for ( storage = 0 ; storage < numberofstudents ; storage ++ )
{
System.out.println ("Enter grade of a student");
information = stgin.readLine();
grade = Integer.parseInt( information );
totalgrades = totalgrades + grade;
if (grade >= 60)
{
sumpassed = sumpassed + 1 ;
}
else
{
sumfailed = sumfailed + 1 ;
}
totalgrades = totalgrades + grade;
}
averagegrade = totalgrades / numberofstudents;
System.out.println ( " Total amount of students entered " +
numberofstudents );
System.out.println ( " The average student grade is " + averagegrade);
System.out.println ( " Total amount of students that passed is " +
sumpassed);
System.out.println ( " Total amount of students that failed is " +
sumfailed );
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,277
Latest member
VytoKetoReview

Latest Threads

Top