CSC 201-Lecture 7
CSC 201-Lecture 7
CSC 201-Lecture 7
Lecture - 7
Scenario
• Let us take a University scenario. I want to
calculate the grade of all the students
based on their marks in each course. How
do I do?
Arrays in Java
• An array is a group of variables of the same data
type referred to by a common name
• It is a contiguous block of memory locations
referred by a common name.
Student 0
Student 1
Student 2
Student 3
a[k] = k;
sum = sum + a[k];
}
System.out.println(“Sum of first 10 numbers is “+sum);
}// How about k < 11? How about increasing size of array?
Calculate the sum
public class sum
{
public static void main(String[] args)
{
int[] a = new int[11];
int sum = 0;
for(int m=0; m < a.length ; m++)
a[m] = m;
for(int k =0; k< a.length; k++)
sum += a[k];
System.out.println(sum);
}
}
Output here ?
Example- Printing 10 random
numbers
import java.util.Random;
public static void main(String[] args)
{
Random mynumber = new Random();
int[] student_marks = new int[10];
for(int i = 0; i < 10 ; i++)
{
student_marks[i] = mynumber.nextInt(10);
System.out.println(“Marks for student “+i” is
“student_marks[i]);
}
}
• What if you want to get an average of the
marks of all the students in a class?
Program to search a number in an
Array
Public static void main(String[] args)
{
int a[] = {10,5,3,12,45,7}; int i=0, found=0;
System.out.println(“Enter a number to search in the array:”);
Scanner s = new Scanner(System.in);
int num = s.nextInt();
while( i < a.length)
{
if(num == a[i])
{System.out.println(“Yes, it matched!”); found = 1;
break;
}
i++;
}
If(found == 0)
System.out.println(“Sorry, not found”);
}
What if you want the position of the element in the array if the number is found?
Two dimensional Arrays
• 2-D arrays are defined as an Array of
arrays.
• An array of ints will have type int[],
similarly we can have int[][], which means
array of arrays of ints.
Print a matrix using a 2–D array
Public static void main(String[] args)
{
int a[][] = new int[2][2];
for(int i=0; i< a.length;i++)
{
for(int j=0;j < a.length; j++)
{
a[i][j] = i;
System.out.print(a[i][j]);
}
System.out.println(“ “);
}
}