Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 A Loop program
Index -> Programming, Java -> Java Help
Goto page 1, 2  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
grasshopper




PostPosted: Mon Mar 29, 2004 4:38 pm   Post subject: A Loop program

i need help writing a program.. i`m just testing loops.. and i`m not sure how to print this but i just want to try.. anyone know the code?

I need to write a program which produces sets of triangles like these:
****
***
**
*
*
**
***
****

- ->I need to allow the user to deteremine how many sets of triangles will be produced.. I know I need this using TextIO...

I started programming this using a `for loop`. and then got stuck....

any suggestions? thanksss
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: Mon Mar 29, 2004 5:08 pm   Post subject: (No subject)

well first you'll need a function to compile your line of astrics, similar to turing's repeat

code:

string repeat(int size)
{
  String word = new String;
  word = "";
  for (int i=0;i<size;i++)
  {
    word = word + "*);
  }
  return word
}


now break your patten into decending and addending loops

code:

for (int i=size;i>=1;i--)
{
  System.out.println(repeat(i));
}

for (int i2=1;i2<=size;i2++)
{
  System.out.println(repeat(i2));
}
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
wtd




PostPosted: Mon Mar 29, 2004 6:03 pm   Post subject: (No subject)

Good suggestion, tony, but instead of using String and + all over the place, use StringBuffer.

code:
String repeat(int size)
{
  StringBuffer word = new StringBuffer("");
  for (int i=0;i<size;i++)
  {
    word.append("*");
  }
  return word.toString();
}


It minimizes the number of temporary String objects created and increases memory efficiency.
grasshopper




PostPosted: Tue Mar 30, 2004 8:37 pm   Post subject: (No subject)

umm.. i`m not worrying about adding the *`s for now because i don`t know where exactly to put that in my code.. i`ll try figuring that out later... but i have another question...

okay this program it`s suppose allow the user to determine how many sets... not how long the set is..
Arrow because in the following code...

code:


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

 
        int triangles;

 
        System.out.print("Please determine how many sets of triangles you want to have produced: ");
        triangles = TextIO.getlnInt();

       
       
        for (int i=triangles;i>=1;i--)
        {
            System.out.println(i); 
        }

       for (int i2=1;i2<=triangles;i2++)
        {
            System.out.println(i2);
        }

   
    }       //end of main

}          //end of class


the following gets printed out..

Arrow if user determines the number of sets to be 5 the following will print out..

5
4
3
2
1
1
2
3
4
5

Arrow if they chose 4..
4
3
2
1
1
2
3
4

and so on

but want i need it to print is..
Arrow if they chose five..
****
***
**
*
*
**
***
****

****
***
**
*
*
**
***
****

****
***
**
*
*
**
***
****

****
***
**
*
*
**
***
****

****
***
**
*
*
**
***
****


like print that whole set five times if they chose 5...

if anyone can help that would be great.. Very Happy i hope it`s not a lot to ask for.. i`m a beginner at programming loops.. so there is still a lot i need to learn..but i`m sure will all these col programmers i`ll be fine.. wow this is starting to sound g.ay.. i`ll stop..
thanks
Tony




PostPosted: Tue Mar 30, 2004 10:29 pm   Post subject: (No subject)

Confused eh
code:

for (int i=0;i<triangles;i++)
{

     for (int i1=4;i>=1;i--)
        {
            System.out.println(i1);
        }

       for (int i2=1;i2<=4;i2++)
        {
            System.out.println(i2);
        }

}


Wink
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
grasshopper




PostPosted: Thu Apr 01, 2004 9:37 am   Post subject: thanks...

heey.. thanks for the help guys.. but i finally figured it out!!


code:
import java.io.*;
         
public class test
{
  public static void main (String[] args)
   {
        //Variable Declaration
                             
        int triangles;               
       System.out.print("Please determine how many sets of triangles you want to have produced: ");     //prompt for input
        triangles = TextIO.getlnInt();                       //read from keyboard
     
      for (int count=1; count<=triangles; count=count+1)       
       {
        for (int i=4;i>=1;i--)
        {
            for(int j= 1; j<=i; j=j+1)
                     
            System.out.print("*");
            System.out.println ("");
        } //first half of triangle
               
        // begin second half of triangle
        for (int i=1;i<=4;i++)
        {
            for(int j= 1; j<=i; j=j+1)
                     
            System.out.print("*");
            System.out.println ("");
           
        } //second half of triangle
System.out.print("\n");
       }//end of first for statement


    }       //end of main
}          //end of class



Laughing
wtd




PostPosted: Thu Apr 01, 2004 3:54 pm   Post subject: (No subject)

Now put all of the loops and such in a separate method. Putting everything in main is bad, bad bad! Smile
grasshopper




PostPosted: Fri Apr 02, 2004 1:16 am   Post subject: (No subject)

lol is it?.. meh my teacher formatted it like that...
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Fri Apr 02, 2004 3:09 pm   Post subject: (No subject)

Yes. Teachers aren't always right. Wink

code:
class Exercise {
   public static void printStuff() {
     // code here
   }

   public static void main(String[] args) {
      printStuff();
   }
}
grasshopper




PostPosted: Sat Apr 03, 2004 2:08 pm   Post subject: (No subject)

oo i c..
umm okay would you be able to help me with something else..as i`m still a beg. at programming..
i want to try this.. like see the code and see if it can help with something else i need to figure out..but not wanting the code for that..
hmm lets see...
alright.. how about a program that asks the user to enter 10 marks for a student.. umm then print out the student`s average, the maximum mark and the minumum mark..using a loop.. using only one variable to read all marks

can you help
Very Happy
Dan




PostPosted: Sat Apr 03, 2004 3:08 pm   Post subject: (No subject)

well to start you will need 3 varibales.

an int for the max var

an int for the min var

an int for the sum of all the marks


now you will input the 1st mark and sotre it in all 3 vars (max, min, and sum)

next you will make a loop that runs for number of marks to be inputed -1 (becuse you all ready got the 1st mark).

then in the loop you input the number in a temp var. add it to sum and check to see if it is bigger then max or smaller then min. if it is you will set it as the one it is biger or smaller then.

then end the loop and output the max, the min and the sum div the num of marks to get the avg.
Computer Science Canada Help with programming in C, C++, Java, PHP, Ruby, Turing, VB and more!
wtd




PostPosted: Sat Apr 03, 2004 7:54 pm   Post subject: (No subject)

You'd want something like the following untested program.

code:
import java.lang.*;
import java.io.*;

class Exercise {
   public static BufferedReader keyboard =
      new BufferedReader(new InputStreamReader(
         System.in));

   private class StudentGradeset {
      private double grades[10];
      private int gradesInput;
     
      public StudentGradeSet(double initialGrade = 0.0) {
         grades = new double[10];
         gradesInput = 0;
         int len = grades.length;
         for (int i = 0; i < len; i++)
            grades[i] = initialGrade;
      }

      public double sumOfGrades() {
         double total = 0.0;
         int len = grades.length;
         for (int i = 0; i < len; i++)
            total += grades[i];
         return total;
      }

      public double minGrade() {
         double min = 0;
         int len = grades.length;
         for (int i = 0; i < len; i++)
            if (grades[i] < min)
               min = grades[i];
         return min;
      }

      public double maxGrade() {
         double max = 0;
         int len = grades.length;
         for (int i = 0; i < len; i++)
            if (grades[i] > max)
               max = grades[i];
         return max;
      }

      public double averageGrade() {
         return sumOfGrades() / grades.length;
      }

      private void inputGrade(BufferedReader input) {
         grades[gradesInput++] = Double.parseDouble(input.readLine());
      }

      public void inputGrades(PrintStream output, BufferedReader input) {
         while (gradesInput < grades.length) {
            output.print("Please input a grade: ");
            inputGrade(input);
         }
      }

      public void outputResults(PrintStream output) {
         output.println("Max grade: " + maxGrade());
         output.println("Min grade: " + minGrade());
         output.println("Avg Grade: " + averageGrade());
      }

      public static void main(String[] args) {
         StudentGradeSet grades = new StudentGradeSet();
         grades.inputGrades(System.out, keyboard);
         grades.outputResults(System.out);
      }
}


And just in case seeing the problem solved in other languages can be of help, I've attached some other samples.



sample.rb.txt
 Description:
Sample Ruby program.

Download
 Filename:  sample.rb.txt
 Filesize:  978 Bytes
 Downloaded:  176 Time(s)


sample.py.txt
 Description:
Sample Python program.

Download
 Filename:  sample.py.txt
 Filesize:  1.01 KB
 Downloaded:  166 Time(s)


sample.cpp
 Description:
Sample C++ program.

Download
 Filename:  sample.cpp
 Filesize:  1.52 KB
 Downloaded:  191 Time(s)


student_grade_set.e.txt
 Description:
The guts of the sample Eiffel program.

Download
 Filename:  student_grade_set.e.txt
 Filesize:  2.28 KB
 Downloaded:  166 Time(s)


main.e.txt
 Description:
"main" for the sample Eiffel program

Download
 Filename:  main.e.txt
 Filesize:  231 Bytes
 Downloaded:  173 Time(s)

grasshopper




PostPosted: Sun Apr 04, 2004 3:47 pm   Post subject: (No subject)

uuuhhh.. what?
i don`t think it was suppose to get that confusing..

Sad
grasshopper




PostPosted: Sun Apr 04, 2004 9:14 pm   Post subject: (No subject)

okaay umm how about i forget that program.. i confused myself..
how about..
A program that asks the user to enter a mark. The program then prints out one line. The word and the mark will be separated by enough dots so that the total line length is 30:
Enter your name: Super
Enter your mark: 95
Super's mark is"¦"¦"¦..95

- ->to print the dots, use System.out.print(".") inside a loop body
- ->might need the following code

code:
String inputString;
Int times;

....

Times= inputstring.length() //times will hold the number of characters in inputString


i don`t know how i`d program that and if i`d use a while or for loop

this is my strcutre so far. (without the public static void main...etc.. etc..)

code:
//Variable Declaration

      String usersName;              //the user's name
      String inputString;
      int times;            //will hold the number of characters in inputString
      int mark;
     
      //Variable Initialization and Input

      System.out.print("Please enter your name: ");     //prompt for input
      usersName = TextIO.getln();                       //read from keyboard
     
      System.out.println("Please enter a mark: ");
      mark = TextIO.getlnInt();

      //Program Processing and Output
      // the process and output i don`t get


Crying or Very sad Crying or Very sad help?
Dan




PostPosted: Mon Apr 05, 2004 4:28 pm   Post subject: (No subject)

TextIO eh? i dont think that is a standered I/O method, u using the Robot java text book by any chance?

any way that dose not matter. This is what i think u need:

code:

                int length = usersName.length() + 11;
               
                if(mark >= 10)
                {
                        length = usersName.length() + 12;
                }
                else if(mark == 100)
                {
                        length = usersName.length() + 13;
                }
               
               
                System.out.print(usersName + "'s mark is");
               
                for     (int i = 0; i < 30-length; i++)
                {
                        System.out.print(".");
                }
               
                System.out.print(mark + "\n");


in this part:

code:

int length = usersName.length() + 11;
               
                if(mark >= 10)
                {
                        length = usersName.length() + 12;
                }
                else if(mark == 100)
                {
                        length = usersName.length() + 13;
                }


length is a var to rep how many chars are in the line minus the "."s. u have to add in 10 for the "'s mark is" part and 1, 2 or 3 for the length of the mark.

the for loop part runs for 30 - the length of the line with out "."s and thous will put in the right number of "."s. some error checking should probly be added to this in case there is - dots or 0 dots needed.


by the way what corse u talking and where? that TextIO is alot like one of the methods in a book i was using for my course.
Computer Science Canada Help with programming in C, C++, Java, PHP, Ruby, Turing, VB and more!
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 2  [ 20 Posts ]
Goto page 1, 2  Next
Jump to:   


Style:  
Search: