CS101 Students for CS101 Students

Possible CS101 Exam Questions & Programs

Last Update
December 15, 2015 - 3:29 pm

Note: I asked a number of students prepare possible midterm/final questions and their answers.

By possible midterm/exam question what I mean is questions that are difficult and easy enough for our exams (definition of easy and difficult is according to the judgment of the submitter it does not reflect my judgment about difficulty level of the questions). I also include recommendations by your peers/classmates.

I publish them with no editing. So if you study them please be critical since they may have some typos/bugs.

I will update this document irregularly as the suggestions come and add the newest one to the top.

F. Can
Bilkent - CS101 Sec. 4 & 5

 

December 15, 2015 - 3:29 pm
Rummy Garden & Playing Cards

by Alihan Hüyük

Problem Description: The Rummy Garden: Helping your father!

/**
 * The Rummy Garden - Line Class
 * Alihan Hüyük
 * Please refer to the question description "The Rummy Garden"
 */

public class Line
{
  //I chose to define a line with a slope value and a point
  private double m;
  private Point p;
 
  public Line(Point p1, Point p2)
  {
    p = new Point(p1);
    //I do not want p to change values if I edit p1 in elsewhere so I copy p1.
   
    m = (p2.getY() - p1.getY()) / (p2.getX() - p1.getX());
    //m will end up being infinite if the line is perfectly vertical
  }
 
  public Boolean onTop(Point p)
  {
    if(!Double.isFinite(m)) return null;
    //question does not make sense
   
    return p.getY() < this.p.getY() + m * (p.getX() - this.p.getX());
    //it is just some algebra you can easily verify it
    //used smaller signed as garden's y-axis is inverted
  }
 
  public Boolean onLeft(Point p)
  {
    if(m == 0) return null;
    //question does not make sense
   
    if(!Double.isFinite(m)) return p.getX() < this.p.getX();
    //the case where the line is perfectly vertical
   
    return p.getX() < this.p.getX() + (1/m) * (p.getY() - this.p.getY());
    //yet again some basic algebra
  }
}
//==========================================================================
/**
 * The Rummy Garden - Point Class
 * Alihan Hüyük
 * Please refer to the question description "The Rummy Garden"
 */

public class Point
{
  private double x;
  private double y;
 
  public double getX() { return x; }
  public double getY() { return y; }
 
  public Point(double x, double y)
  {
    this.x = x;
    this.y = y;
  }
 
  public Point()
  {
    //calls the first constructor
    this(0, 0);
  }
 
  public Point(Point p)
  {
    this(p.x, p.y);
  }
}
//==========================================================================
import java.util.Scanner;

/**
 * The Rummy Garden - Main Class
 * Alihan Hüyük
 * Please refer to the question description "The Rummy Garden"
 */

public class RummyMain
{
  public static void main(String[] args)
  {
    Scanner scanner = new Scanner(System.in);
    Line left, right, top, bottom;
   
    System.out.println("Enter the left most vertical line:");
    left = scanLine(scanner);
    System.out.println();
   
    System.out.println("Enter the right most vertical line:");
    right = scanLine(scanner);
    System.out.println();
   
    System.out.println("Enter the top most vertical line:");
    top = scanLine(scanner);
    System.out.println();
   
    System.out.println("Enter the bottom most vertical line:");
    bottom = scanLine(scanner);
    System.out.println();
   
    while(true)
    {
      double x, y;
   
      System.out.print("x: ");
      x = scanner.nextDouble();
      if(x < 0) break;
     
      System.out.print("y: ");
      y = scanner.nextDouble();
      if(y < 0) break;
     
      Point p = new Point(x, y);
     
      int xCoordinate = 2;
      if(right.onLeft(p))
      {
        xCoordinate = 1;
        if(left.onLeft(p)) xCoordinate = 0;
      }
     
      int yCoordinate = 2;
      if(bottom.onTop(p))
      {
        yCoordinate = 1;
        if(top.onTop(p)) yCoordinate = 0;
      }
     
      int region = yCoordinate * 3 + xCoordinate + 1;
     
      System.out.println("This point is in the region number " + region + ".");
      System.out.println();
    } 
  }
 
  public static Line scanLine(Scanner scanner)
  {
    double x, y;
    Point p1, p2;
   
    System.out.print("\tx1: ");
    x = scanner.nextDouble();
    System.out.print("\ty1: ");
    y = scanner.nextDouble();
   
    p1 = new Point(x, y);
   
    System.out.print("\tx2: ");
    x = scanner.nextDouble();
    System.out.print("\ty2: ");
    y = scanner.nextDouble();
   
    p2 = new Point(x, y);
   
    return new Line(p1, p2);
  }
}

 

Problem Description: Playıng Cards

/**
 * Playing Cards - Card Class
 * Alihan Hüyük
 * Please refer to the question description "Playing Cards"
 */

public class Card
{
  private int suit;
  private int value;
 
  // -1-
  public Card(int suit, int value)
  {
    this.suit = suit;
    this.value = value;
  }
 
  // -2-
  public boolean smallerThan(Card other)
  {
    if(suit < other.suit) return true;
    return value < other.value;
  }
 
  // -3-
  public String toString()
  {
    String string = "";
   
    if(value == 1) string += "Ace";
    else if(value == 2) string += "Two";
    else if(value == 3) string += "Three";
    else if(value == 4) string += "Four";
    else if(value == 5) string += "Five";
    else if(value == 6) string += "Six";
    else if(value == 7) string += "Seven";
    else if(value == 8) string += "Eight";
    else if(value == 9) string += "Nine";
    else if(value == 10) string += "Ten";
    else if(value == 11) string += "Jack";
    else if(value == 12) string += "Queen";
    else if(value == 13) string += "King";
   
    string += " of ";
   
    if(suit == 0) string += "Clubs";
    else if(suit == 1) string += "Diamonds";
    else if(suit == 2) string += "Spades";
    else if(suit == 3) string += "Hearths";
   
    return string;
  }
 
  // -4-
  public boolean equals(Card other)
  {
    return suit == other.suit && value == other.value;
  }
}

//==========================================================================

import java.util.ArrayList;

/**
 * Playing Cards - Deck Class
 * Alihan Hüyük
 * Please refer to the question description "Playing Cards"
 */

public class Deck
{
  ArrayList<Card> deck;
 
  // -1-
  public Deck()
  {
    deck = new ArrayList<Card>();
  }
 
  // -2-
  public void addRandom()
  {
    int suit = (int) (Math.random() * 4);
    int value = (int) (Math.random() * 13) + 1;
    Card newCard = new Card(suit, value);
   
    //checking if we can add this new card
    boolean canAdd = true;
    for(Card card : deck)
    {
      canAdd = !card.equals(newCard);
    }
   
    if(canAdd) deck.add(newCard);
    else addRandom(); //try with a different random card
   
    //A better way to implement this would be to make a list of cards which are not
    //in the deck and choose a random card among them.
  }
 
  // -3-
  public void sort()
  {
    //I will use buble sort for the implementation of this method.
    //You can refer to some external sources if explanation is needed.
   
    int lastIndex = deck.size() - 2;
   
    while(lastIndex >= 0)
    {
      for(int i = 0; i <= lastIndex; i++)
      {
        if(deck.get(i + 1).smallerThan(deck.get(i)))
        {
          //swapping i and i + 1
         
          Card temp = deck.get(i);
          deck.set(i, deck.get(i + 1));
          deck.set(i + 1, temp);
        }
      }
     
      lastIndex--;
    }
  }
 
  // -4-
  public void shuffle()
  {
    //I will shuffle the deck by performing a set number of random swaps
    //As there are maximum 52 cards, I chose that number to be 52.
   
    for(int i = 0; i < 52; i++)
    {
      //choosing cards to swap
      int i1 = (int) (Math.random() * deck.size());
      int i2 = (int) (Math.random() * deck.size());
     
      //swapping
      Card temp = deck.get(i1);
      deck.set(i1, deck.get(i2));
      deck.set(i2, temp);
    }
  }
 
  // -5-
  public void cut()
  {
    ArrayList<Card> newDeck = new ArrayList<Card>();
    int cutPosition = (int) (Math.random() * deck.size());
   
    for(int i = cutPosition; i < deck.size(); i++)
    {
      newDeck.add(deck.get(i));
      //first adding the cards after the cutPosition (in order)
    }
   
    for(int i = 0; i < cutPosition; i++)
    {
      newDeck.add(deck.get(i));
      //then adding the cards before the cutPosition (in order)
    }
       
    deck = newDeck;
  }
 
  // -6-
  public String toString()
  {
    String string = "";
   
    for(Card card : deck)
      string += card + "\n";
   
    //removing the excess "\n" left from the last iteration of for loop
    string.substring(0, string.length() - 1);
   
    return string;
  }
}

December 13, 2015 - 12:49 pm
Point - Vector Classes & Some Recommendations
by Kadir Can Çelik

CS101 – Questions About Classes

One question that comes to mind when learning to write programs is about how it will be useful in the future. As seen in lab07, we can simulate the behavior of a die and build a game upon it. In fact, what you can do with programming is probably only limited by your own imagination. In the following questions, I wanted to show briefly how useful would programming be if you want to do stuff about maths or physics. We will implement a Point and a Vector class. Actually, sciences is one of the areas that need programming as they need simulations and numerical computations. We will not do any fancy stuff for now but these baby steps may take us to that place, in future.

Some recommendations:

 

1) Write a class that represents a point in two dimensions using Cartesian coordinates. Obviously it will have two instance variables, corresponding to x coordinate and y coordinate.
To make it more interesting, assign a name automatically to every Point object like “P1”, “P2” etc…
Write two constructor methods, one without any parameters and one with two parameters which are coordinates.

2) Use the Point class as an instance variable to implement a Vector class. Although it may seem a good idea to have two instance variables for the end point and the start point, I suggest you to implement it only using one instance variable as vectors have equivalence relationship. This is just a technical detail, do not bother with it too much. Also, in Vector class, don't bother with the naming thing about the Point class, it was just to see how to implement such a counter into a class, and in fact it was unnecessary for the Point class in my opinion.

public class Point {
    private static int lastId = 0;
    private String name;
    private double x;
    private double y;
    // Default constructor w/o any parameters
    public Point () {
                x = 0.0;
                y = 0.0;
                lastId = lastId + 1;
                name = "P" + lastId;
            }
            // A constructor with two parameters for the two instance variables
            public Point (double x, double y) {
                this.x = x;
                this.y = y;
                lastId = lastId + 1;
                name = "P" + lastId;
            }
            // Accessor methods
            public double getX () {
                return x;
            }
            public double getY () {
                return y;
            }
            // Mutator methods
            public void setX (double x) {
                this.x = x;
            }
            public void setY (double y) {
                this.y = y;
            }
            public double getDistance (Point other) {
                double result;
                result = Math.sqrt (Math.pow (x - other.x, 2) + Math.pow (y - other.y, 2));
                return result; 
            }
            public Point clone() {
                Point result;
                result = new Point();
                result.setX (this.x);
                result.setY (this.y);
                return result;
            }
            public String toString () {
                String result;
                result = name + " x: " + x + " y: " + y;
                return result;
            }
            public boolean equals (Point other) {
                boolean result;
                result = (this.x == other.x && this.y == other.y);
                return result;
            }
            public int compareTo (Point other) {
                int result;
                double distance1;
                double distance2;
                        // Ouch, here we increment the lastId by two by creating two anonymous objects
                distance1 = this.getDistance(new Point ());
                distance2 = other.getDistance(new Point());
                lastId = lastId - 2;
                if ( distance1 < distance2 ) {
                            result = -1;
                        } else if ( distance1 == distance2 ) {
                            result = 0;
                        } else {
                            result = 1;
                        }
                        return result;
            }
} // End of Point class

public class Vector {
    private Point positionVector;
    // Default constructor
    public Vector() {
                positionVector = new Point();
            }
            // A constructor with two Point parameters
            public Vector (Point initialPoint, Point finalPoint) {
                positionVector = new Point();
                positionVector.setX (finalPoint.getX() - initialPoint.getX());
                positionVector.setY (finalPoint.getY() - initialPoint.getY());
            }
            public Point getPositionVector () {
                return (positionVector.clone());
            }
            public void setPositionVector (Point positionVector) {
                this.positionVector = positionVector.clone();
            }
            public double getLength() {
                return positionVector.getDistance();
            }
            public Vector clone() {
                Vector result;
                result = new Vector ();
                result.setPositionVector (positionVector);
                return result;
            }
            public String toString () {
                String result;
                result = positionVector.toString();
                return result;
            }
            public boolean equals (Vector other) {
                boolean result;
                result = (this.getPositionVector().equals (other.getPositionVector()));
                return result;
            }
            public int compareTo (Vector other) {
                int result;
                double length1;
                double length2;
                length1 = this.getLength();
                length2 = other.getLength();
                if ( length1 < length2 ) {
                            result = -1;
                        } else if ( length1 == length2 ) {
                            result = 0;
                        } else {
                            result = 1;
                        }
                        return result;
            }
            public double getScalarProduct (Vector other) {
                        double result;
                        result = this.positionVector.getX() * other.positionVector.getX();
                        result += this.positionVector.getY() * other.positionVector.getY();
                return result;
            }
            public double getAngleBetween (Vector other) {
                        double result;
                        result = Math.acos (this.getScalarProduct (other) / (this.getLength() * other.getLength()));
                        return result;                
            }
} // End of Vector class


Check TC Kimlik No. Validity
by Ünal Ege Gaznepoğlu

/**
* @author Unal Ege Gaznepoglu
* @date 2015/12/12
*
* As you know, there are some certain restrictions which a number should
* comply if that number is an Turkish ID Number. This class will store a
* long integer and when requested it will check if this number is a valid
* ID Number or not.
*
* Checking function will return number of errors. If it returns 0, then
* provided number is a Turkish Citizenship Number probably.
*
* For purposes of this program, we will only care about 3 of the
* rules.
*
* After creating a checker class, we can create another method to create
* random numbers which comply with all of the conditions.
* (Although this is not a P = NP problem (my opinion at first glance),
* I will first create a random number then check whether it is a
* Citizenship number or not. If it is not, then I will decrease the value by one.
* This will keep happening until it complies with all of the rules.
*
* Another approach might be solving solution set for all equations, then plugging in
* required amount of random digits. If requested, I can code it as well.
*/

public class TcKimlikNo
{
private long _number;

public TcKimlikNo(long number)
{
_number = number;
}

public long generate()
{
_number = Math.random()*900000000000L + 100000000000L;
while(this.check() != 0)
{
_number --;
}
return _number;
}
public int check()
{
//keeping up each result in this ArrayList.
ArrayList<Boolean> conditions = new ArrayList<Boolean>();

//to ease up the process, let's keep digits seperated in another ArrayList.
//There is no possibility of having a zero in first digit, so there is no
//specially coded situation in while loop.
ArrayList<Integer> digits = new ArrayList<Integer>();
long tempNumber = _number;
while(tempNumber > 0)
{
digits.add((int)(tempNumber % 10));
tempNumber = tempNumber /10;
}

ArrayList<Integer> temp = new ArrayList<Integer>();

for(int i =0;i<11;i++) //to revert wrong order.
{
temp.add(digits.get(10-i));
}

digits = temp;
//lets start checking some of the conditions.
//first is summing up all 10 digits, modulus of 10 which should be equal to 11th digit.

int sumOfDigits = 0;
for(int i = 0;i<10;i++)
{
sumOfDigits += digits.get(i);
}
conditions.add(digits.get(10) == (sumOfDigits % 10)); //first condition is finished.

//now lets check the second condition. 7*(1th,3th,5th,7th and 9th) - (2th,4th,6th,8th) % 10 should be 10th digit.
sumOfDigits = 0;
for(int i =0;i<9;i++)
{
if(i%2 == 0)
sumOfDigits += (7*digits.get(i));
else
sumOfDigits += (-1*digits.get(i));
}
conditions.add(digits.get(9) == (sumOfDigits%10));

//and the third condition: 8 times 1,3,5,7,9 = 11.
sumOfDigits = 0;
for(int i = 0;i<5;i++)
{
sumOfDigits += 8*digits.get(2*i);
}
conditions.add(digits.get(10) == (sumOfDigits%10));

//lets print out the conditions.
System.out.println(conditions);

//now lets count numbers of false conditions.
int sum=0;
for(int i = 0; i<conditions.size(); i++)
{
sum += (1-boolToInt(conditions.get(i)));
}

return sum;
}

private static int boolToInt(Boolean x) //although there are much easier ways to do this, I loved this alternative at stackoverflow and wanted to share it.
{
return -("false".indexOf(""+x));
}
}

 

 

 

December 2, 2015 - 3:20 pm
Three programs easiest to hardest
by Alihan Hüyük

 

A PROGRAMMER'S BIRTHDAY

Problem Description


import java.util.Scanner;

/**
 * Alihan Hüyük
 * Please refer to the question description "A Programmer's Birthday"
 */

public class Date
{
  // 1 : properties
  private int day;
  private int month;
  private int year;
 
  // 2 : default constructor
  public Date()
  {
    day = 7;
    month = 10;
    year = 1996;
  }
 
  // 3 : a constructor which takes three parameter for each of the properties
  public Date(int day, int month, int year)
  {
    // !! TRICKY PART
   
    while(day <= 0) //while not if, because the day can be -40 than we should add 30 to the day two times
    {
      day += 30;
      month--;
    }
    while(day > 30)
    {
      day -= 30;
      month++;
    }
   
    while(month <= 0)
    {
      month += 12;
      year--;
    }
    while(month > 12)
    {
      month -= 12;
      year++;
    }
   
    this.day = day;
    this.month = month;
    this.year = year;
  }
 
  // 4 : a constructor which takes only the number of days
  public Date(int day)
  {
    this(31 + day, 12, 1999);
    //the constructor takes care of the limits
  }
 
  // 5 : the static add and sub functions
  public static Date add(Date d1, Date d2)
  {
    return new Date(d1.day + d2.day, d1.month + d2.month, d1.year + d2.year);
    //the constructor takes care of the limits
  }
 
  public static Date sub(Date d1, Date d2)
  {
    return new Date(d1.day - d2.day, d1.month - d2.month, d1.year - d2.year);
    //the constructor takes care of the limits
  }
 
  // 6 : toString function with leading zeros
  public String toString()
  {
    String result = "";
   
    if(day < 10) result += "0"; //adds leading zeros if the day is an one-digit number
    result += day + ".";
   
    if(month < 10) result += "0";
    result += month + ".";
   
    result += year;
   
    return result;
  }
 
  // * : calculating how much time a person lived
  public static void main(String[] args)
  {
    Scanner scanner = new Scanner(System.in);
    Date birth;
    Date today;
    int a, b, c;
   
    System.out.println("Please enter your birthday. (as day, month, year; one by one");
    a = scanner.nextInt();
    b = scanner.nextInt();
    c = scanner.nextInt();
    birth = new Date(a, b, c);
    System.out.println();
   
    System.out.println("Please enter the current date. (as day, month, year; one by one");
    a = scanner.nextInt();
    b = scanner.nextInt();
    c = scanner.nextInt();
    today = new Date(a, b, c);
    System.out.println();
   
    System.out.println("You lived exactly this much: " + Date.sub(today, birth));
  }
}

 

 

 

THINKING RATIONAL

Problem Description

/**
 * Alihan Hüyük
 * Please refer to the question description "Thinking Rational"
 */

public class Rational
{
  // 1 : properties
  private int n;
  private int dn;
 
  // 2: default constructor
  public Rational()
  {
    n = 1;
    n = 1;
  }
 
  // 3: a constructor with two parameters for each property
  public Rational(int nominator, int denominator)
  {
    n = nominator;
    dn = denominator;
  }
 
  // 4: a constructor which takes a double number
  public Rational(double d)
  {
    // !! TRICKY PART
   
    dn = 1;
    while(d != (int)d) //this means d still has decimal points
    {
      d *= 10; //we multiply d with 10 to obtain an integer, ex.: 1.25 -> 125
      dn *= 10; //we count how many times we should divide the result to get back the original number
    }
   
    //d has not decimal points now
    n = (int) d;
  }
 
  // 5 : simplify function
  public void simplify()
  {
    // !! TRICKY PART
   
    int gcd = 1; //greatest common divisor
    for(int i = 2; i <= Math.min(n, dn); i++)
    {
      if(n % i == 0 && dn % i == 0)
        gcd = i;
    }
   
    n /= gcd;
    dn /= gcd;
  }
 
  // 6 : arithmetic operation functions
  public static Rational add(Rational q1, Rational q2)
  {
    Rational result = new Rational(q1.n * q2.dn + q1.dn * q2.n, q1.dn * q2.dn);
    result.simplify();
    return result;
  }
 
  public static Rational sub(Rational q1, Rational q2)
  {
    Rational result = new Rational(q1.n * q2.dn - q1.dn * q2.n, q1.dn * q2.dn);
    result.simplify();
    return result;
  }
 
  public static Rational mul(Rational q1, Rational q2)
  {
    Rational result = new Rational(q1.n * q2.n, q1.dn * q2.dn);
    result.simplify();
    return result;
  }
 
  public static Rational div(Rational q1, Rational q2)
  {
    Rational result = new Rational(q1.n * q2.dn, q1.dn * q2.n);
    result.simplify();
    return result;
  }
 
  // 7 : equals function
  public boolean equals(Rational other)
  {
    //if a:b = c:d then ad = bc
    return n * other.dn == dn * other.n;
  }
 
  // 8 : biggerThan and smallerThan
  public boolean biggerThan(Rational other)
  {
    //we are checking if a:b > c:d
   
    if(Math.signum(dn) == Math.signum(other.dn))
    {
      //if b and d has the same sign then a*d > b*c
      return n * other.dn > dn * other.n;
    }
    else
    {
      //if b and d has different signs then a*d < b*c
      return n * other.dn < dn * other.n;
    }
  }
 
  public boolean smallerThan(Rational other)
  {
    // !! SLIGHTLY TRICKY PART
    return !equals(other) && !biggerThan(other);
  }
 
  // 9 : this was a really bad idea
 
  // 10 : isInteger function
  public boolean isInteger()
  {
    //if the denominator divides the nominator, the number is an integer
    return n % dn == 0;
  }
 
  // 11 : toString function
  public String toString()
  {
    return n + " over " + dn;
  }
}

DIGITAL ATTENDANCE

Problem Description

/**
* Alihan Hüyük
* Please refer to the question description "Digital Attendance"
*/

public class Student
{
  //properties
  private String name;
  public boolean attendance;
  private Student nextStudent;
 
  //functionality 1 : initialize list with the first student’s name
  public Student(String name)
  {
    this.name = name;
    attendance = false;
    nextStudent = null; //there is not a next student yet
   
    //your secret "feature"
    if(name.equals("Alihan Hüyük")) attendance = true;
  }
 
  //functionality 2 : add students to the list one by one
  public void add(String name)
  {
    if(nextStudent == null)
    {
      //this is the end of the list so we should add the new student
      nextStudent = new Student(name);
    }
    else
    {
      // !! TRICKY PART
      //this is not the end of the list
      //we should continue to look for the end of the list
      nextStudent.add(name);
    }
  }
 
  //functionality 3 : how long the list is
  public int size()
  {
    if(nextStudent == null)
    {
      //this is the end of the list
      //there is exactly one student after this point
      return 1;
    }
    else
    {
      // !! TRICKY PART
      //this is not the end of the list
      //the number of students after this point is:
      return 1 + nextStudent.size();
    }
  }
 
  //functionality 4 : get the student with a specific name
  public Student find(String name)
  {
    if(this.name.equals(name))
    {
      //we found the student
      return this;
    }
    else if(nextStudent == null)
    {
      //this is the end of the list and we could not find the student
      return null;
    }
    else
    {
      // !! TRICKY PART
      //we need to continue searching
      //maybe the next student is who we are searching for
      return nextStudent.find(name);
    }
  }
}


 

Nov. 20, 2015 - 11:20 am

 

CS101-3
Mert MERMERCİ

EXERCISES FOR MIDTERM

Let’s consider a triangle which is made up with numbers.
    1           The one which is on the left can be a good example for that. Take a value from the user                 
  121          (the number for the example is 3) and print out a triangle.
12321

If you do that, let’s try a different one.
    1           Take a value from the user and print out a triangle like that (the number in the example    
  212          is 3).
32123

If you do the previous ones, let’s try something strange.
   
    *********     Take a height and a thickness value from the user and print out a diamond shape.
   ***********    (the height value is 1 and thickness value is 11 for the example)
    *********
     *******
      *****
       ***
        *

         

I know that these exercises are not tough but I think these can be good exercise for ‘for’ loops.( First two are working well for one digit numbers, I’m a beginner so if you have any comment or corrections please contact with me on mermertci@gmail.com .)

SOLUTION-1

 // NUMBER TRIANGLE
    int number;
    number = scan.nextInt();
   
    //First loop is for the lines of the triangle
    for(int r = 1; r <= number; r++)
    {
      //Second loop is for the blanks. 
      for(int s = 0; s < number - r; s++)
      {
        System.out.print(" ");
      }
      /*
       * Third loop is for printing out the values.
       * I divide the value part two pieces.
       * First piece is printing out the numbers till the value like 123.
       */
      for(int t = 1; t <= r; t++)
      {
        System.out.print(t);
      }
      /*
       * It's the second part of the value printing.
       * It prints out the reamining part 21.
       * When we combine with the upper one 12321 is printing out.
       */
      for(int u = r - 1;u > 0; u--)
      {
        System.out.print(u);   
      }
      /*Another loop for blanks.
       * This for loop is not necessary especially.
       * But if it is expected to print out values different from blank, it's necessary.
       */
      for(int v = 0; v < number - r; v++)
      {
        System.out.print(" ");
      }
      System.out.println();
    }

SOLUTION-2

 //NUMBER TRIANGLE 2
    int number2;
    number2 = scan.nextInt();
   
    for(int a = 1; a <= number2; a++)
    {
      for(int b = 0; b < number2 - a; b++)
      {
        System.out.print(" ");
      }
      for(int c = a; c > 0; c--)
      {
        System.out.print(c); 
      }
      for(int d = 2; d <= a ; d++)
      {
        System.out.print(d);
      }
      for(int e = 0; e < number2 - a; e++)
      {
        System.out.print(" ");
      }
      System.out.println();
    }

SOLUTION - 3

    //REAL DIAMOND
    int height2;
    int thickness2;
    System.out.println("Enter the height: ");
    height2 = scan.nextInt();
    System.out.println("Enter the thickness: ");
    thickness2 = scan.nextInt();
   
    /*
     * Thickness should be an odd number.
     * If it's not, the printing shape would not be a diamond.
     */
    if(thickness2 % 2 == 1)
    {
      // This loop is for the head of the diamond.
      for(int f = height2; f > 1; f--)
      {
        for(int g = 0; g < f; g++)
        {
          System.out.print(" ");
        }
        for(int h = 0; h < thickness2 - 2*f; h++)
        {
          System.out.print("*");
        }
        for(int i = 0; i < f; i++)
        {
          System.out.print(" ");
        }
        System.out.println();
      }
       // This loop is for the triangle in the diamond.
       for(int m = thickness2 ; m >= 1; m = m - 2)
      {
        for(int n = 0; n < (thickness2 - m)/2; n++)
        {
          System.out.print(" ");
        }
        for(int o = 0; o < m; o++)
        {
          System.out.print("*");
        }
        for(int p = 0; p < (thickness2 - m)/2; p++)
        {
          System.out.print(" ");
        }
        System.out.println();
      }
    }
    else
    {
      System.out.print("Invalid value");
    }

 

 


CS101 – Midterm1 Question by Gökberk DAĞAŞAN & Ali Semi YENİMOL

Write a full program that draws a diamond with asterisks ( “*” ) but only the edges of the diamond will be visible. Side length will be given by user. For example, when user enter 4, it will print:

*
* *
*   *
*     *
*   *
* *
*
Good luck in midterm1 everyone

SOLUTION
import java.util.Scanner;

public class DiamondWithSpace{
    public static void main(String [] args){
        //Variables
        int sideLength;
        int tmp;
        Scanner scan = new Scanner(System.in);
       
        //Prompting the user
        System.out.print( "Enter the side length of the diamond : ");
        sideLength = scan.nextInt();
       
       
        for(int a = 0 ; a < sideLength ; a++){
            tmp = sideLength;
            sideLength = a;
           
                  
            //Drawing the top of the diamond
            for ( int i = 0 ; i < sideLength ; i++){
                for( int k = 0 ; k < sideLength*2 ; k++){
                    if( k == sideLength - i || k == sideLength + i ){
                        System.out.print("*");
                    }
                    else{
                        System.out.print(" ");
                    }
                }
                System.out.println("");
            }
            //Drawing the bottom of the diamond
            for(int i = sideLength - 2; i >=0 ; i--){
                for(int k = 0 ; k < sideLength*2 ; k++){
                    if(k == sideLength - i || k == sideLength + i){
                        System.out.print("*");
                    }
                    else{
                        System.out.print(" ");
                    }
                }
                System.out.println("");
            }
            System.out.println("---------------------------------------------------");
            sideLength = tmp;
        }
    }
}
ALTERNATIVE SOLUTION
import java.util.Scanner ;

public class aa {
    public static void main(String[] args) {
        // Variables
        int height;
       
        // Code
        Scanner sc = new Scanner(System.in);
        height = sc.nextInt();
        // Upper part being printed
        for ( int i = 0 ; i < height ; i++ )
        {
            for ( int j = 0; j < height - i - 1; j++ )
            {
                System.out.print( " " );
            }
            System.out.print( "*" );
           
            for ( int k = 0; k < 2*i - 1; k++ )
            {
                System.out.print( " " );
            }
            if ( i != 0 )
            {
                System.out.print( "*" );
            }
            System.out.println();
        }
        // Bottom part being printed
        for ( int m = height - 2 ; m >= 0 ; m--)
        {
            for ( int b = 0; b < height - 1 - m; b++ )
            {
                System.out.print( " " );
            }
            System.out.print( "*" );
           
            for ( int z = 0; z < 2*m -1; z++ )
            {
                System.out.print( " " );
            }
            if ( m != 0 )
            {
                System.out.print ( "*" );
            }
            System.out.println();
           
        }
    }
}

 


CS101 JAVA QUESTIONS BY COBAN, CAGAN SELIM

import java.util.Scanner;
public class Question1
{  
Scanner sc = new Scanner(System.in);   
public static void main( String[] args){
       //Initializing the variables and scanner
        int val= sc.nextint();
        //Entering the loop
          for(i=1; i <= val ; i++){
              int factorialVal = factorialFunction.(i);
              double result = factorialVal/7;
   }
   
    System.out.print.ln(“Factorial of ”val  + “is” + result);
 }

Answer A:
import java.util.Scanner;
public class Question1
{  
    public static void main( String[] args){
       //Initializing the variables and scanner
        Scanner sc = new Scanner(System.in);
        int val= sc.nextInt();
        //Entering the loop
          for(int i=1; i <= val; i++){
              int factorialVal = factorialFunction(i);
              double result = factorialVal/7;
              System.out.println(result);
          }
    }

Answer B:
      The logical problem in this code segment is an uninteded integer division. When the all inputs are integers, “/” denotes does not mean division in a mathematical sense, it means integer division because both factorialVal and 7 are integers. As a consqeunce, the output will be integers instead of doubles. If we enter 5, we’ll see this output:
0.0
0.0
0.0
3.0
17.0

 

If the user has entered 4, your generated figure should be like this:
oxxx
xoxx
xxox
xxxo

                Answer:
               
import java.util.Scanner;
public class Question2
{  
    public static void main( String[] args){
       Scanner sc = new Scanner(System.in);
       int input = sc.nextInt();
       String leftString="";
       String rightString="";
       int l=-1;
       for(int c = input; c != 0; c--){
           l++;
           rightString = "";
           leftString = "";
           for(int i=0; i < l; i++){
               leftString += "x";
           }
           for(int i=0; i < c-1 ; i++){
               rightString += "x";
           }
             
           System.out.println(leftString + "o" + rightString);
       }
    }
}

public static int gradeMethod(double n) {
        double result=n;
        if(n >= 0){
            // Does nothing
        }
        else{
            result *= -1;
        }
       
        //Once the method gets the absolute value of n, continues to round
       
        int bufferRound = (int)result;
        double dif = result - bufferRound;
        if(dif >= 0.5){
            bufferRound++;
        }
        else{
        //Does nothing
        }
        return bufferRound;
      }

 

 

Nov. 16, 2015 - 12:02 pm

 

CS101 – Midterm 1 Questions by K. Can Çelik

1.   A positive integer is said to be “perfect” if the sum of all positive divisors except for the number itself is equal to that number. Write a static method that would take one formal parameter “number” of approriate type, that would return “true” if the number is perfect and “false” if the number is not perfect.

SOLUTION:

        public static boolean isWonderful (int number) {
                int sum;
                sum = 0;
                for ( int i = 1; i < number; ++i ) {
                        if ( number % i == 0 ) {
                                sum = sum + i;
                        }
                }
                return ( sum == number );
        }

2.   You are given a method called mixString, and it is guaranteed that the parameter s will have at least two characters in it.

        public static String mixString (String s) {
                        String result;
                        int strLen;
                        int lastIndex;
                        result = “”;
                        strLen = s.length();
                        lastIndex = strLen / 2 - 1;
                        for ( int i = 0; i <= lastIndex; ++i ) {
                                    result = result.concat (String.valueOf (s.charAt (i)));
                                    result = result.concat (String.valueOf (s.charAt (strLen - i - 1)));
                        }
                        if ( strLen % 2 == 1 ) {
                                    result = result.concat (String.valueOf (s.charAt (lastIndex + 1)));
                        }
                        return (result);
            }

It appears that a programmer used that method as follows:

String mixed = mixString (“wneflurdo”);

What would be the value of the variable mixed after the program returns from the function? Find the answer by tracing the program.

SOLUTION: “wonderful”

3.   Now that you traced the mixString method, you probably understood the purpose of that method. Write a method inverseMix that would inverse the effect of mixString, that is, this statement should be true for all appropriate String s:
            s == inverseMix (mixString (s));
            Your method's signature should be : “public static String inverseMix (String s)”.

SOLUTION :

        public static String inverseMix (String s) {
                        String result;
                        int strLen;
                        int counter;
                        result = "";
                        strLen = s.length();
                        counter = 0;
                        while ( counter < strLen ) {
                                    result = result.concat (String.valueOf (s.charAt (counter)));
                                    counter = counter + 2;
                        }
                        if ( strLen % 2 == 1 ) {
                                    counter = strLen - 2;
                        } else {
                                    counter = strLen - 1;
                        }
                        while ( counter > 0 ) {
                                    result = result.concat (String.valueOf (s.charAt (counter)));
                                    counter = counter - 2;
                        }
                        return (result);
        }


CS Programming Exercise
 Hüseyin Ziya İmamoğlu Section 5
                                                                                                      
Although, I checked the solutions with Dr. Java, there may be errors. If there’s any, please mail me through h.ziya.im@gmail.com. I am a beginner, so if you have simpler or more efficient ways of solving the problems, again please mail me.  Hope that, questions and answers will be helpful. Best wishes and good luck in the exam!

  
Answers

{
    String result = "";
    int length = str.length();
    for(int i = 1; i <= length ; i++)
    {
        String letter2 = "";
        String letter1 = str.substring(i-1,i);
        if(length > i)
        {
            letter2 = str.substring(i,i+1);
            if(letter1.equals("1") && letter2.equals("3"))
            {
                i = i + 1;  
               letter1 = "";              
            }
 
         }
      result = result + letter1;
      }
      return result;
   }

 

 

        public class PrimeNumberPrinter
{
    public static void main(String[] args)
    {
        //Variables
        int n;
        Scanner in = new Scanner(System.in);
        boolean isPrime = true;
        // Get the user input 
        System.out.println("Enter a positive integer please");
        n = in.nextInt();
       
        //Initialize the remainder
        int remainder = 0;
       
        //Do appropriate data evaluation
        if(n <= 1)
        {
            System.out.println("No prime number");
        }
        else
        {
       
        //If the n is more than 1, the numbers will include 2
        System.out.println("2");
       
        /* For each integer value bigger or equal to 3 ( since we included 2 we have to start counting from 3)  and less or equal to n, create an innet loop which will check whether the integer value is divisible by another integer value ranging from 2 two the integer value itself by checking the remainder. If it's equal to zero, the condition will turn false and it’s not going to be printed. If it's not, print it after completing the inner loop. The i will denote the integer value at a given instant. */
        
        for(int i = 3; i <= n; i++)
        {
             isPrime = true;
             for(int k = 2; k < i; k++)
            {
              remainder = i % k;
              if(remainder == 0)
            {
                isPrime = false;
            }
            }
            if(isPrime)
            { 
                System.out.println(i);
            }
        }
        }
    }
}

 

public class DiamondPrinter
{
    public static void main(String[] args)
    {
        //Variables
        int noOfRows;
        int noOfSymbols;
        int noOfSpaces;
        char symbol;
        Scanner in = new Scanner(System.in);
        Scanner scan = new Scanner(System.in);
       
        //Get the user input
        System.out.println("Please enter an odd integer value bigger than 1");
        noOfRows = in.nextInt();
        System.out.println("Please enter a symbol");
        symbol = scan.nextLine().charAt(0);
       
        //Initialize the varibles for the loop
        noOfSymbols = 1;
        noOfSpaces = noOfRows/2;
       
        //Create a loop for the diamond
       
        for(int i = 1; i <= noOfRows; i++)
        {
            for(int k = 1; k <= noOfSpaces; k++)
            {
                System.out.print(" ");
            }
           
            for(int j = 1; j <= noOfSymbols; j++)
            {
                System.out.print(symbol);
            }
            if(i < noOfRows/2 +1)
            {
                noOfSpaces --;
                noOfSymbols = noOfSymbols + 2;
            }
            else
            {
                noOfSpaces ++;
                noOfSymbols = noOfSymbols - 2;
            }
            System.out.println();
        }
    }
}

           
           
   


Nov. 13, 2015
CS 101 Midterm Preparation Questions

 

Note: Assume that all needed headers are imported. Although I have checked multiple times, sometimes autocorrect “fixes” the capital letters at beginning of the line. Remember that Java is a case-sensitive language and assume that I have written the correct one.

 

Written by Ünal Ege Gaznepoğlu

Easier:

1.       Write a program which will print out the following pattern with two different ways.

* * * * * * * *

  * * * * * * * *

* * * * * * * *

  * * * * * * * *

* * * * * * * *

  * * * * * * * *

* * * * * * * *

  * * * * * * * *

a.       Using the minimum amount of System.out.println, strings are free to use.

b.      Using the minimum amount of System.out.print, strings are forbidden to use.

Hint: In both cases, up to some extent, using for loops are highly recommended.

 

2.       Write a program which will detect whether entered string is a palindrome or not. A palindrome is a word or number which remains same if it is reversed. For example “12321” is a palindrome and “44332211” is not a palindrome.

Hint: There are two different approaches to this problem. Apply both of them.

 

a.       Revert the string and check if equal.

b.      Check characters two by two.

 

Medium:

1.       Your company is working on a graphing solution. Program should print out a graph of the given numbers and names to rows.

Example input:

CS,3

EE,5

ME,6

Output:

CS:  ***

EE:  *****

ME: ******

Your task is to code a method which will get only one input as a string and return the line for that input. For example, your method will only get “CS,3” string and return “CS: ***”  string. You can use \t to tidy up the line.

2.       Correct the given code segment so it does the intended function. If it already performs the intended function, then write TRUE, if not, simply write if the problem is a compile time error or a logic error. There might be more than one problem with the given code segment. If so, write for all of the errors.

 

a.       The factorial function. This method was supposed to calculate the factorial of the given number.

 

public static int factorial(int x)

{

int returnValue = 0;

               for(int i=1; i<=x; i++)

               {

                               returnValue = returnValue * i;

               }

}

 

b.      The root finder for second-order terms (quadratic equations). This method was supposed to find the roots for a given second order equation. The input is in terms of coefficents and output is in terms of a printout string which contains the estimations for the values.

 

public static String findQuadraticRoots(int a,int b,int c)

{

double delta = Math.pow(b,2) – 4*a*c;

if(delta > 0)

return ("The roots are " + (-b-Math.sqrt(delta))/(2*a) + “and “ (-b+Math.sqrt(delta))/(2*a));

if(delta =0)

return("There is only one root for this equation and that is" + new Integer(-b/2*a));

if(delta<0)

return("Unfortunately, there are no real roots for given equation. ");

}

Challenging:

1.       Write a method which calculates the Greatest Common Divisor and Least Common Multiplication of given numbers a and b without using arrays or recursion. Hint: You may interpret Euler’s algorithm or use some for’s to check common primes. Hint 2: You don’t need to check entire interval [2,min(a,b) -1], checking until Math.floor(sqrt[min(a,b)]) is enough. The proof is the graph of y = k/x which has the line y=x as a symmetry axis.

 

2.       Think about a rectangle which has the dimensions AxB. Write a program which

a.       Finds the smallest amount of equal squares needed to coat this rectangle.

b.      Finds the smallest amount of squares needed to coat this rectangle.

Hint: Use the functions from question 1.

Solutions For Problems

Easier:

1.       There are more than one solution for these problems. These are the ones that I have came up with.

a.      
String printOut = " ";
for(int i=0;i<15;i++)
{

      if(i%2 == 0)

          printOut += "*";

      else

          printOut += " ";
}

for(int i=0;i<8;i++)

{

if(i %2 == 0)

    System.out.println(printOut);

else

    System.out.println("" + printOut);

}

b.     
for(int i=0;i<8;i++)
{
    for(int j=0;j<16;j++)
    {
        if((i%2==0 && j%2==0) || (i%2==1 && j%2==1) )
            System.out.print("*");
        else
            System.out.print(" ");
    }
    System.out.println();
}

2.        

a.       Using this method dramatically reduces the total lines of code. You can use your reverse method from Lab06 or use this one.

public static String reverse(String inputStr)

{

      String returnStr = "";

      For(int i =0;i<inputStr.length();i++)

      {

                 returnStr += inputStr.charAt(inputStr.length()-i);

}

return returnStr;

}

 

public static void main(String[] args)

{

      Scanner scan = new Scanner(System.in);

      String userInput = scan.nextLine();

      if(reverse(userInput).equals(userInput))

                 System.out.println("This is a palindrome!");

      else

                 System.out.println("This is not a palindrome.");

}

 

b.      You can also solve this problem with the approach of checking characters at i’th and length-ith position.

 

public static void main(String[] Args)

{

      Scanner scan = new Scanner(System.in);

      String userInput = scan.nextLine();

      Boolean allSame = true;

      for(int i=0; i<(userInput.length()/2 +1) && allSame;i++)

      {

if(userInput.charAt(i) != userInput.charAt(userInput.length()-i))

                             allSame = false;

}

if(allSame)

System.out.println("Yes, this is a palindrome. ");

else

            System.out.println("No,it is not a palindrome. ")

}

Medium:

1.       First, get the input, obviously. Next move is parsing (identify and split to the functional parts) the input. This can be done with the methods “stringVariableName.indexAt()” and “stringVariableName.substring()”. After parsing the input into the row name and the numbers of stars, we should first send off the row name and then the needed number of stars.

The reason why I prefer nextLine above all other input receiving methods is that it consumes the END OF LINE character. It is a good programming habit not to leave any wild EOL in System.in buffer because it may later confuse your program.

 

public static String prepareGraphRow()

{

Scanner scan = new Scanner(System.in);

String graphLine,userInput;

int value;

graphLine= "";

userInput = scan.nextLine();

value = userInput.substring(userinput.indexOf(","),userInput.length());

graphLine += userInput.substring(0,userinput.indexOf(","));

graphLine += "\t”;

for(int i = 1;i<=value;i++)

{

                graphLine += "*";

}

return graphLine;

}

2.       As you know, there are logic errors (fallacies) and syntax errors.

a.       There were two different errors on this one.

                                                              i.      The initialization of returnValue. As it is zero, after multiplying with any variable the result is still zero. To fix this up, one must initialize it with 1. This is a logic error which does not alert the compiler.

                                                            ii.      Our method has a return type of "integer " but there is no return statement. This is a syntax error and compiler warns you if you do so.

b.      There were three different errors on this one.

                                                              i.      The syntax error at the first return  statement. After "and ”, we should add a “+” (without quotes) sign to correct this one. The missing + sign creates two different strings instead of one.  This is a syntax error as well.

                                                            ii.      This is a bit tricky without really running the program to see this mistake. In the second return line, the expression is written as b/2*a, however this is not equal to the b/(2*a) due to the operation priorities. This is a logic error and can take hours from your miserable life until you find it.

                                                          iii.      Although for every case you have returned some variable, but compiler does not understand this one because it does not know only and only one of the three conditionals can be true. So, writing up the method with if/else-if/else would be a better approach. Other solution is to mimic at the end of method as there is another return statement there, but this is not the best approach because your prior if/if/if statements might have some undefined situations.

Challenging:

1.       To calculate greatest common divisor, we can use Euclid’s algorithm. Euclid’s algorithm works in following way:

public static int euclidGCD(int a,int b){

int larger = Math.max(a,b);

int smaller = Math.min(a,b);

int temporaryValue;

while(larger  % smaller != 0)

{

temporaryValue = larger%smaller;

larger = smaller;

smaller = temporaryValue;

}

 

return larger; }

This method directly calculates the greatest common divisor for two integers. To calculate the least common multiplication, we can use the property AxB = GCD(A,B)*LCM(A,B)

 

Other approach to calculate the greatest common divisor is to use some for loops to find common prime factors of both numbers A and B. Be careful not to forget the multiple instances of the same prime factor. Example: Let A be 12 and B be 16. If we didn’t have the inner while condition then we would have gcd as 2 after this method but it is 4.

            int gcd = 1;

            for(int i=2;i<=Math.floor(Math.sqrt(Math.min(a,b)));i++)

            {

if( a%i == 0 && b%i == 0)

                        while(a%i ==0 && b%i ==0)

                        {

gcd *= i;

a /= i;

b/= i;

}

}

 

2.        

a.       To calculate the smallest amount of equal squares to coat a surface AxB, we can use greatest common divisor method . After finding the dimensions for one side of a square, then calculating A*B/(dimension^2) would give us the right answer.

 

b.      Without the word “equal”, there is a bit more bookkeeping to handle because we can use first larger squares and then get them smaller. Details for this problem can be found at Wikipedia within the title “Euclid’s Algorithm”. As I remember, there was a graphic animation of how this algorithm works on that page.

 

public static int findLeastSquare(int a, int b)

{

int amountOfSquares, greater,smaller,division,remainder;

greater = Math.max(a,b);

smaller = Math.min(a,b);

               while(greater % smaller != 0)

{

division = greater/smaller;

remainder = greater % smaller;

greater = smaller;

smaller = remainder;

amountOfSquares += division;

}

                                    return amountOfSquares;

}

 

 

I wish success in the first CS101 midterm which will take place in 21.11.2015.


CS101 – Midterm 1 Questions by K. Can Çelik

 

1) A positive integer is said to be “perfect” if the sum of all positive divisors except for the number itself is equal to that number. Write a static method that would take one formal parameter “number” of approriate type, that would return “true” if the number is perfect and “false” if the number is not perfect.SOLUTION:

 

        public static boolean isWonderful (int number) {

                int sum;

                sum = 0;

                for ( int i = 1; i < number; ++i ) {

                        if ( number % i == 0 ) {

                                sum = sum + i;

                        }

                }

                return ( sum == number );

        }

 

2) You are given a method called mixString, and it is guaranteed that the parameter s will have at least two characters in it.

 

        public static String mixString (String s) {

                        String result;

                        int strLen;

                        int lastIndex;

                        result = “”;

                        strLen = s.length();

                        lastIndex = strLen / 2 - 1;

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

                                   result = result.concat (String.valueOf (s.charAt (i)));

                                   result = result.concat (String.valueOf (s.charAt (strLen - i - 1)));

                        }

                        if ( strLen % 2 == 1 ) {

                                    result = result.concat (String.valueOf (s.charAt (lastIndex + 1)));

                        }

                        return (result);

            }

 

It appears that a programmer used that method as follows:

 

String mixed = mixString (“wneflurdo”);

 

What would be the value of the variable mixed after the program returns from the function? Find the answer by tracing the program.

 

SOLUTION: “wonderful”

 

3) Now that you traced the mixString method, you probably understood the purpose of that method. Write a method inverseMix that would inverse the effect of mixString, that is, this statement should be true for all appropriate String s:

s == inverseMix (mixString (s));

Your method's signature should be : “public static String inverseMix (String s)”.

 

SOLUTION :

 

        public static String inverseMix (String s) {

                        String result;

                        int strLen;

                        int counter;

                        result = "";

                        strLen = s.length();

                        counter = 0;

                        while ( counter < strLen ) {

                                   result = result.concat (String.valueOf (s.charAt (counter)));

                                   counter = counter + 2;

                        }

                        if ( strLen % 2 == 1 ) {

                                   counter = strLen - 2;

                        } else {

                                   counter = strLen - 1;

                        }

                        while ( counter > 0 ) {

                                   result = result.concat (String.valueOf (s.charAt (counter)));

                                   counter = counter - 2;

                        }

                        return (result);

        }