Introduction to Computer Science
|
|
|
|
COMP 1412 INTRODUCTION TO CS 2 CODE ASSIGNMENT
|
Assignment Name: Printing odd numbers |
Student Name : John Doe |
|
Assignment Date: 9/4/2020 |
Student id : 123 |
Problem
Printing odd numbers in an integer array.
Challenges
· Finding pattern to find odd numbers
· Accessing elements
· Iteration
Code
Pseudo Code
Initialize int array with random int numbers
for (index=0 to last index)
if (current%2 not equal to zero)
print current element
Outputs
Figure 1 Output Screen of the Odd Numbers Question
REPL.IT LINK
https://repl.it/repls/CarefulWretchedRuntimelibrary#Main.java
2
COMP 1412 INTRODUCTION TO COMPUTER SCIENCE 2 FALL 2020
package data_structures;
public class Sample {
public static void main(String[] args) {
// int array created and initialized with integer
numbers 1-8
int[] numbers = {1,2,3,4,5,6,7,8};
//for loop to visit all elements of the int array
for(int i = 0 ; i < numbers.length ; i++){ // since
size of the array is dynamic numbers.length used to access the
last element
//Any odd number can be calculated using modulus
operator. Basically remainder of the division 2 is not zero
if(numbers[i]%2 != 0) {
System.out.println(numbers[i]); // only odd
numbers index will return true
}
}
}
}
package data_structures;
public class Sample {
public static void main(String[] args) {
// int array created and initialized with integer numbers 1-8
int[] numbers = {1,2,3,4,5,6,7,8};
//for loop to visit all elements of the int array
for(int i = 0 ; i < numbers.length ; i++){ // since size of the array is dynamic numbers.length used to access the last element
//Any odd number can be calculated using modulus operator. Basically remainder of the division 2 is not zero
if(numbers[i]%2 != 0) {
System.
out
.println(numbers[i]); // only odd numbers index will return true
}
}
}
}