Last active
August 29, 2015 14:06
-
-
Save michaelglass/8e747ca294e57d2943a4 to your computer and use it in GitHub Desktop.
nested loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num_columns = 7 | |
num_rows = 4 | |
col_sums = Array.new(num_columns, 0) | |
(0...num_rows).each do |col| | |
row_sum = 0 | |
(0...num_columns).each do |row| | |
val = row*col | |
print "#{val}\t" | |
row_sum += val | |
col_sums[row] += val | |
end | |
puts "*#{row_sum}\t" | |
end | |
col_sums.each {|sum| print "#{sum}\t" } | |
puts |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NestedForLoop { | |
public static void main(String[] args) { | |
int numRows = 4; | |
int numColumns = 7; | |
int[] columnSums = new int[numColumns]; | |
for (int row = 0; row < numRows; row++) { | |
int rowSum = 0; | |
for (int column=0; column < numColumns; column++) { | |
int value = row * column; | |
System.out.print(value + "\t"); | |
rowSum += value; | |
columnSums[column] += value; | |
} | |
System.out.println("*" + rowSum); | |
} | |
for (int columnSum : columnSums ) { | |
System.out.print(columnSum + "\t"); | |
} | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment