Stanford CS106A Assignment 2 Pythagorean Theorem Solution

Woohooo! Finally an easier one 🙂 This one, the professor pretty much went over in Lecture 6. Luckily, I took good notes. Here is the problem:

Here is my solution, also available on github:


Since the other problems here were Graphics programs, I stumbled a bit by creating a “GLabel”. Since this is a Console program, remember to use “println()” to display a message or “readInt()” stored as an integer to ask the user for feedback. If you keep these in mind, this is a pretty simple problem (probably the easiest one in Assignment 2).

<pre>/*
 * File: PythagoreanTheorem.java
 * Name: 
 * Section Leader: 
 * -----------------------------
 * This file is the starter file for the PythagoreanTheorem problem.
 */

import acm.program.*;

public class PythagoreanTheorem extends ConsoleProgram {
	public void run() {
		sayWelcomeMessage();
		askUserInput();
	}
	private void sayWelcomeMessage() {
		println( "Enter values to compute the Pythagorian theorem" );
	}
	private void askUserInput() {
		int a = readInt ("a:"); //asks user to enter an integer for a
		int b = readInt ("b:"); //asks user to enter an integer for b
		double x = (double)a; // converts variable "a" from an integer to a double 
		double c = Math.sqrt((x*x) + (b*b)); //calculates square root
		println("c:"+ c); //displays value as a double
	}
}</pre>

Enjoy the article? Join over 17,500+ Swift developers and enthusiasts who get my weekly updates.