Skip to content

Instantly share code, notes, and snippets.

@rumaisaabdulhai
Created February 13, 2021 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rumaisaabdulhai/293eab2622a24e87243e006417037062 to your computer and use it in GitHub Desktop.
Save rumaisaabdulhai/293eab2622a24e87243e006417037062 to your computer and use it in GitHub Desktop.
Week 4 Classwork Solutions
/**
* This class contains the solutions to
* the Week 4 classwork exercises.
*/
public class WeekFourCW {
public static void main(String[] args) {
/* Problem 1: Create An Array
- Create your own array!
- It should consist of your 4 favorite foods
- Use what we learned about defining and declaring an array
- Think about what data type you should use for this task
*/
String[] favFoods = {"Biryani", "Ice Cream", "Chocolate", "Raspberries"};
/* Problem 2: Calculate Sum (No Loops)
Using what we learned about indexing, your challenge is
to calculate and print the sum of all values in the array
below.
Remember that you must get each element using the index
to find the sum. Do not directly use the values, like
int sum = 11 + 4 + 25 + 15 + ...;
*/
int[] array1 = {11, 4, 25, 15, 10, 33, 4, 6, 17};
int sum1 = array1[0] + array1[1] + array1[2] + array1[4] +
array1[5] + array1[6] + array1[7] + array1[8];
System.out.println("\nClasswork Problem 2\n"); // to separate problems
System.out.println("\tSum = " + sum1);
/* Problem 3: Calculate Sum (Using Loops)
Your challenge is to make code that prints the sum of all integers in
the array.
*/
System.out.println("\nClasswork Problem 3\n"); // to separate problems
int sum2 = 0;
int[] array2 = {0, 1, 2, 3, 4, 5, 6, 7, 8};
for (int i = 0; i < array2.length; i++) {
sum2 = sum2 + array2[i];
}
System.out.println("\tSum = " + sum2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment