You are on page 1of 4

Assignment_2 121CCS-3 Introduction to programming

Semester I, Year 1443 AH - 2021 AD

 Student's Name:  Date:

 Student's Id #  Section #

Due Date: November 27, 2021


Handwritten Assignment
Send through Blackboard

Q1: Write Java program to sort an array in an ascending order


then trace the program (how the program will be executed). (
‫كتابة برنامج يرتب المصفوفة ترتيب تصاعدي مع تتبع البرنامج كيف يتم تنفيذ‬
‫)البرنامج وتوضيح ماهي المخرجات والمدخالت‬

‫الشرح‬

The below program demonstrates how to sort an array in


ascending order using loops.

Enter size of array and then enter all the elements of that
array. Now with the help of for loop and temp variable we
sort the array in ascending order.

/*Java Program to Sort an Array in Ascending Order*/


import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;

public class Main


{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n; //Array Size Declaration
System.out.println("Enter the number of elements :");
n=sc.nextInt(); //Array Size Initialization
Integer arr[]=new Integer[n]; //Array Declaration
System.out.println("Enter the elements of the array :");
for(int i=0;i<n;i++) //Array Initialization
{
arr[i]=sc.nextInt();
}
int temp = 0; //Temporary variable to store the element
for (int i = 0; i < arr.length; i++) //Holds each Array
element
{
for (int j = i+1; j < arr.length; j++) //compares with
remaining Array elements
{
if(arr[i] > arr[j]) //Compare and swap
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in
ascending order: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}

.output

Enter the number of elements :10


Enter the elements of the array :
6784351897
Elements of array sorted in ascending order:
1345677889

Q2: Write a java program that finds the average of each


row in a two-dimensional array then trace the program
(how the program will be executed). ( ‫كتابة برنامج يطبع الوسيط‬
‫لكل صف في مصفوفة ثنائية االبعاد مع تتبع للبرنامج كيف يتم تنفيذه وتوضيح‬
‫)ماهي المدخالت والمخرجات‬
‫الشرح‬

import java.util.*;
class TwoDimensionalScanner
{
public static void main(String args[])
{

Scanner sc=new Scanner(System.in);


System.out.println("Enter Row length of an array : ");
int row=sc.nextInt();
System.out.println("Enter column length of an array : ");
int column=sc.nextInt();
int sum=0;
int n = column * row;
double average = sum/n;
int a[][]=new int[row][column];//declaration
System.out.print("Enter " + row*column + " Elements to Store in Array :\n");
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
{
a[i][j] = sc.nextInt();
sum=+a[i][j];
}
}

// Print total sum of array

System.out.print(" the sum. is "+ sum);


System.out.print("The average of the 2D array is " + average);
}

You might also like