Week 10 14-17-04-2025
Week 10 14-17-04-2025
Aim
To practice programming using 1-dimensional arrays.
Objectives
After completing this week’s session, you should be able to:
Tasks
Note: All tasks have been adapted from Sedgwick.
1. Write a program that declares and initializes an array a [] of size1000 and accesses a [1000].
Does your program compile? What happens when you run it?
2. Describe and explain what happens when you try to compile a program with the following
statements:
int N = 1000;
int[] a = new int[N*N*N*N];
3. Given two vectors of length N that are represented with one-dimensional arrays, write program
that computes the Euclidean distance between them (the square root of the sums of the
squares of the differences between corresponding entries).
4. Write a program that reverses the order of a one-dimensional array a [] of String values.
Do not create another array to hold the result. Hint: Use the code in for exchanging two
elements from lecture 5.
5. What is wrong with the following code fragment?
int[] a;
for (int i =0; i < 10; i++)
a[i] = i * i;
6. What does the following code fragment print?
int[] a = new int[10];
for (int i = 0; i < 10; i++)
a[i] = 9 - i;
for (int i = 0; i < 10; i++)
a[i] = a[a[i]];
for (int i = 0; i < 10; i++)
System.out.pri ntln(a[i]);
7. What values does the following code put in the array a [] ?
int N = 10;
int[] a = new int[N];
a[0] = 1;
a[l] = 1;
for (int i = 2; i < N; i++)
a[i] = a[i-l] + a[i-2];
8. What does the following code fragment print?
int[] a = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
System.out.println(a == b);
System.out.println(a);