0% found this document useful (0 votes)
31 views72 pages

Java Programming Basics: Variables & Loops

The document provides an introduction to Java programming, covering variables, data types, constants, conditional statements, loops, and patterns. It includes examples of primitive and non-primitive data types, as well as homework problems for practical application. The content is structured across multiple lectures, guiding learners through fundamental programming concepts and encouraging practice.

Uploaded by

vivekvish0134
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views72 pages

Java Programming Basics: Variables & Loops

The document provides an introduction to Java programming, covering variables, data types, constants, conditional statements, loops, and patterns. It includes examples of primitive and non-primitive data types, as well as homework problems for practical application. The content is structured across multiple lectures, guiding learners through fundamental programming concepts and encouraging practice.

Uploaded by

vivekvish0134
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java - Introduction to Programming

Lecture 2

Variables & Data Types

1. Variables
A variable is a container (storage area) used to hold data.
Each variable should be given a unique name (identifier).

package [Link];

public class Main {

public static void main(String[] args) {


// Variables
String name = "Aman";
int age = 30;

String neighbour = "Akku";


String friend = neighbour;
}
}

2. Data Types
Data types are declarations for variables. This determines the type and size of
data associated with variables which is essential to know since different data
types occupy different sizes of memory.

There are 2 types of Data Types :


- Primitive Data types : to store simple values
- Non-Primitive Data types : to store complex values

Primitive Data Types


These are the data types of fixed size.

Apna College
Data Type Meaning Size Range
(in Bytes)

byte 2’s complement integer 1 -128 to 127

short 2’s complement integer 2 -32K to 32K

int Integer numbers 4 -2B to 2B

long 2’s complement integer 8 -9,223,372,036,85


4,775,808
(larger values) to
9,223,372,036,85
4,775,807

float Floating-point 4 Upto 7 decimal


digits

double Double Floating-point 8 Upto 16


decimal digits

char Character 2 a, b, c ..
A, B, C ..
@, #, $ ..

bool Boolean 1 True, false

Non-Primitive Data Types


These are of variable size & are usually declared with a ‘new’ keyword.

Eg : String, Arrays

String name = new String("Aman");


int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;

3. Constants
A constant is a variable in Java which has a fixed value i.e. it cannot be assigned
a different value once assigned.

Apna College
package [Link];

public class Main {

public static void main(String[] args) {


// Constants
final float PI = 3.14F;
}
}

Homework Problems
1. Try to declare meaningful variables of each type. Eg - a variable
named age should be a numeric type (int or float) not byte.

2. Make a program that takes the radius of a circle as input,


calculates its radius and area and prints it as output to the user.

3. Make a program that prints the table of a number that is input by


the user.

(HINT - You will have to write 10 lines for this but as we proceed in
the course you will be studying about ‘LOOPS’ that will simplify
your work A LOT!)

KEEP LEARNING & KEEP PRACTICING :)

Apna College
Java - Introduction to Programming
Lecture 3

1. Conditional Statements ‘if-else’


The if block is used to specify the code to be executed if the condition specified
in if is true, the else block is executed otherwise.

int age = 30;


if(age > 18) {
[Link]("This is an adult");
} else {
[Link]("This is not an adult");
}

2. Conditional Statements ‘switch’


Switch case statements are a substitute for long if statements that compare a
variable to multiple values. After a match is found, it executes the
corresponding code of that value case.

The following example is to print days of the week:

int n = 1;
switch(n) {
case 1 :
[Link]("Monday");
break;
case 2 :
[Link]("Tuesday");
break;
case 3 :
[Link]("Wednesday");
break;
case 4 :
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6 :
[Link]("Saturday");
break;
default :
[Link]("Sunday");
}

Apna College
Homework Problems
1. Make a Calculator. Take 2 numbers (a & b) from the user and an
operation as follows :

1 : + (Addition) a + b

● 2 : - (Subtraction) a - b
● 3 : * (Multiplication) a * b
● 4 : / (Division) a / b
● 5 : % (Modulo or remainder) a % b

Calculate the result according to the operation given and


display it to the user.

2. Ask the user to enter the number of the month & print the name
of the month. For eg - For ‘1’ print ‘January’, ‘2’ print ‘February’ &
so on.

KEEP LEARNING & KEEP PRACTICING :)

Apna College
Java - Introduction to Programming
Lecture 4

Loops
A loop is used for executing a block of statements repeatedly until a particular
condition is satisfied. A loop consists of an initialization statement, a test
condition and an increment statement.

For Loop
The syntax of the for loop is :

for (initialization; condition; update) {


// body of-loop
}

for (int i=1; i<=20; i++) {


[Link](i);
}

While Loop
The syntax for while loop is :
while(condition) {
// body of the loop
}

int i = 0;
while(i<=20) {
[Link](i);
i++;
}

Do-While Loop
The syntax for the do-while loop is :
do {
// body of loop;
}
while (condition);

int i = 0;
do {
[Link](i);

Apna College
i++;
} while(i<=20);

Homework Problems
1. Print all even numbers till n.
2. Run
for(; ;) {

[Link]("Apna College");

loop on your system and analyze what happens. Try to think of the reason for
the output produced.

3. Make a menu driven program. The user can enter 2 numbers, either 1 or 0.

If the user enters 1 then keep taking input from the user for a student’s
marks(out of 100).

If they enter 0 then stop.

If he/ she scores :

Marks >=90 -> print “This is Good”

89 >= Marks >= 60 -> print “This is also Good”

59 >= Marks >= 0 -> print “This is Good as well”

Because marks don’t matter but our effort does.

(Hint : use do-while loop but think & understand why)

BONUS

Qs. Print if a number is prime or not (Input n from the user).

[In this problem you will learn how to check if a number is prime or not]

Apna College
Homework Solution (Lecture 3)

import [Link].*;

public class Conditions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
int operator = [Link]();

/**
* 1 -> +
* 2 -> -
* 3 -> *
* 4 -> /
* 5 -> %
*/

switch(operator) {
case 1 : [Link](a+b);
break;
case 2 : [Link](a-b);
break;
case 3 : [Link](a*b);
break;
case 4 : if(b == 0) {
[Link]("Invalid Division");
} else {
[Link](a/b);
}
break;
case 5 : if(b == 0) {
[Link]("Invalid Division");
} else {
[Link](a%b);
}
break;
default : [Link]("Invalid Operator");
}
}

Apna College
}

Apna College
Java - Introduction to Programming
Lecture 5

Patterns - Part 1

1.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;
int m = 4;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
2.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;
int m = 4;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(i == 0 || i == n-1 || j == 0 || j == m-1) {
[Link]("*");
} else {
[Link](" ");
}
}
[Link]();
}
}
}

Apna College
3.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 4;

for(int i=1; i<=n; i++) {


for(int j=1; j<=i; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
4.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 4;

for(int i=n; i>=1; i--) {


for(int j=1; j<=i; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
5.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 4;

for(int i=n; i>=1; i--) {


for(int j=1; j<i; j++) {
[Link](" ");
}

for(int j=0; j<=n-i; j++) {


[Link]("*");
}
[Link]();
}
}
}

Apna College
6.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;

for(int i=1; i<=n; i++) {


for(int j=1; j<=i; j++) {
[Link](j);
}
[Link]();
}
}
}

Apna College
7.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;

for(int i=n; i>=1; i--) {


for(int j=1; j<=i; j++) {
[Link](j);
}
[Link]();
}
}
}

Apna College
8.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;
int number = 1;

for(int i=1; i<=n; i++) {


for(int j=1; j<=i; j++) {
[Link](number+" ");
number++;
}
[Link]();
}
}
}

Apna College
9.

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;

for(int i=1; i<=n; i++) {


for(int j=1; j<=i; j++) {
if((i+j) % 2 == 0) {
[Link](1+" ");
} else {
[Link](0+" ");
}
}
[Link]();
}
}
}

Apna College
Homework Problems (Solutions in next Lecture’s Video)
1. Print a solid rhombus.

2. Print a number pyramid.

3. Print a palindromic number pyramid.

Apna College
Homework Solution (Lecture 4)

1. Print all even numbers till n.

1. public class Solutions {

2. public static void main(String args[]) {

3. int n = 25;

4.

5. for(int i=1; i<=n; i++) {

6. if(i % 2 == 0) {

7. [Link](i);

8. }

9. }

10. }

11. }

12.

3. Make a menu driven program. The user can enter 2 numbers, either 1 or 0.
If the user enters 1 then keep taking input from the user for a student’s
marks(out of 100).

If they enter 0 then stop.

If he/ she scores :

Marks >=90 -> print “This is Good”

89 >= Marks >= 60 -> print “This is also Good”

59 >= Marks >= 0 -> print “This is Good as well”

Because marks don’t matter but our effort does.

Apna College
(Hint : use do-while loop but think & understand why)

import [Link].*;

public class Solutions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int input;

do {
int marks = [Link]();
if(marks >= 90 && marks <= 100) {
[Link]("This is Good");
} else if(marks >= 60 && marks <= 89) {
[Link]("This is also Good");
} else if(marks >= 0 && marks <= 59) {
[Link]("This is Good as well");
} else {
[Link]("Invalid");
}

[Link]("Want to continue ? (yes(1) or no(0))");


input = [Link]();

} while(input == 1);
}
}

Qs. Print if a number n is prime or not (Input n from the user).

[In this problem you will learn how to check if a number is prime or not]
import [Link].*;

public class Solutions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();

boolean isPrime = true;


for(int i=2; i<=n/2; i++) {

Apna College
if(n % i == 0) {
isPrime = false;
break;
}
}

if(isPrime) {
if(n == 1) {
[Link]("This is neither prime not composite");
} else {
[Link]("This is a prime number");
}
} else {
[Link]("This is not a prime number");
}
}
}

Apna College
Java - Introduction to Programming
Lecture 6

Patterns - Part 2

1.

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 4;

//upper part
for(int i=1; i<=n; i++) {
for(int j=1; j<=i; j++) {
[Link]("*");
}

int spaces = 2 * (n-i);


for(int j=1; j<=spaces; j++) {
[Link](" ");
}

for(int j=1; j<=i; j++) {


[Link]("*");
}
[Link]();
}

Apna College
//lower part
for(int i=n; i>=1; i--) {
for(int j=1; j<=i; j++) {
[Link]("*");
}

int spaces = 2 * (n-i);


for(int j=1; j<=spaces; j++) {
[Link](" ");
}

for(int j=1; j<=i; j++) {


[Link]("*");
}
[Link]();
}
}
}

2.

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 5;

Apna College
for(int i=1; i<=n; i++) {
//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}

//stars
for(int j=1; j<=n; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
3.

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 5;

for(int i=1; i<=n; i++) {


//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}

//numbers
for(int j=1; j<=i; j++) {
[Link](i+" ");
}
[Link]();
}
}
}

Apna College
4.

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 5;
for(int i=1; i<=n; i++) {
//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}

//first part
for(int j=i; j>=1; j--) {
[Link](j);
}

//second part
for(int j=2; j<=i; j++) {
[Link](j);
}
[Link]();
}
}
}

Apna College
5.

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 5;

//upper part
for(int i=1; i<=n; i++) {
//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}
for(int j=1; j<=2*i-1; j++) {
[Link]("*");
}
[Link]();
}

//lower part
for(int i=n; i>=1; i--) {
//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}
for(int j=1; j<=2*i-1; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
Homework Problems
1. Print a hollow Butterfly.

2. Print a hollow Rhombus.

*****

* *

* *

* *

*****

3. Print Pascal’s Triangle.

11

121

1331

14641

4. Print half Pyramid.

Apna College
12

123

1234

12345

5. Print Inverted Half Pyramid.

11111

222

33

Apna College
Java - Introduction to Programming
Lecture 7

Methods/Functions
A function is a block of code that performs a specific task.
Why are functions used?
a. If some functionality is performed at multiple places in software, then
rather than writing the same code, again and again, we create a function
and call it everywhere. This helps reduce code redundancy.
b. Functions make maintenance of code easy as we have to change at one
place if we make future changes to the functionality.
c. Functions make the code more readable and easy to understand.

The syntax for function declaration is :


return-type function_name (parameter 1, parameter2, …… parameter n){
//function_body
}
return-type

The return type of a function is the data type of the variable that that function
returns.

For eg - If we write a function that adds 2 integers and returns their sum then
the return type of this function will be ‘int’ as we will return a sum that is an
integer value.
When a function does not return any value, in that case the return type of the
function is ‘void’.

function_name
It is the unique name of that function.
It is always recommended to declare a function before it is used.

Parameters
A function can take some parameters as inputs. These parameters are specified
along with their data types.
For eg- if we are writing a function to add 2 integers, the parameters would be
passed like –
int add (int num1, int num2)
Apna College
main function
The main function is a special function as the computer starts running the code
from the beginning of the main function. Main function serves as the entry point
for the program.

Example :

package [Link];

public class Main {


//A METHOD to calculate sum of 2 numbers - a & b
public static void sum(int a, int b) {
int sum = a + b;
[Link](sum);
}

public static void main(String[] args) {


int a = 10;
int b = 20;
sum(a, b); // Function Call

}
}

Qs. Write a function to multiply 2 numbers.

import [Link].*;

public class Functions {

//Multiply 2 numbers

public static int multiply(int a, int b) {

return a*b;

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

Apna College
int a = [Link]();

int b = [Link]();

int result = multiply(a, b);

[Link](result);

Qs. Write a function to calculate the factorial of a number.

​import [Link].*;

public class Functions {


// public static int calculateSum(int a, int b) {
// int sum = a + b;
// return sum;
// }

// public static int calculateProduct(int a, int b) {


// return a * b;
// }

public static void printFactorial(int n) {


//loop
if(n < 0) {
[Link]("Invalid Number");
return;
}
int factorial = 1;

for(int i=n; i>=1; i--) {


factorial = factorial * i;
}

[Link](factorial);
return;
}

Apna College
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();

printFactorial(n);
}
}

Qs. Write a function to calculate the product of 2 numbers.


import [Link].*;

public class Functions {

// public static int calculateSum(int a, int b) {

// int sum = a + b;

// return sum;

// }

public static int calculateProduct(int a, int b) {

return a * b;

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

int a = [Link]();

int b = [Link]();

[Link](calculateProduct(a, b));

Apna College
Homework Problems
1. Make a function to check if a number is prime or not.
2. Make a function to check if a given number n is even or not.
3. Make a function to print the table of a given number n.
4. Read about Recursion.

Apna College
Java - Introduction to Programming
Lecture 8

Time & Space Complexity

Time complexity of an algorithm quantifies the amount of time taken by an


algorithm to run as a function of the length of the input.

Types of notations
1. O-notation: It is used to denote asymptotic upper bound. For a given
function g(n), we denote it by O(g(n)). Pronounced as “big-oh of g of n”. It
is also known as worst case time complexity as it denotes the upper
bound in which the algorithm terminates.
2. Ω-notation: It is used to denote asymptotic lower bound. For a given
function g(n), we denote it by Ω(g(n)). Pronounced as “big-omega of g of
n”. It is also known as best case time complexity as it denotes the lower
bound in which the algorithm terminates.
3. 𝚯-notation: It is used to denote the average time of a program.

Examples :

Apna College
Linear Time Complexity. O(n)

Comparison of functions on the basis of time complexity

It follows the following order in case of time complexity:

n 3 2
O(n ) > O(n!) > O(n ) > O(n) > O([Link](n)) > O([Link](log(n))) > O(n) > O(sqrt(n)) > O(log(n)) > O(1)

Note: Reverse is the order for better performance of a code with corresponding
time complexity, i.e. a program with less time complexity is more efficient.

Space Complexity
Space complexity of an algorithm quantifies the amount of time taken
by a program to run as a function of length of the input. It is directly
proportional to the largest memory your program acquires at any
instance during run time.
For example: int consumes 4 bytes of memory.

Apna College
Java - Introduction to Programming
Lecture 10

Arrays In Java

Arrays in Java are like a list of elements of the same type i.e. a list of integers, a list of
booleans etc.
a. Creating an Array (method 1) - with new keyword
int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;

b. Creating an Array (method 2)


int[] marks = {98, 97, 95};

c. Taking an array as an input and printing its elements.


import [Link].*;

public class Arrays {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int size = [Link]();
int numbers[] = new int[size];

for(int i=0; i<size; i++) {


numbers[i] = [Link]();
}

//print the numbers in array


for(int i=0; i<[Link]; i++) {
[Link](numbers[i]+" ");
}
}
}

Apna College
Homework Problems
1. Take an array of names as input from the user and print them on the screen.
import [Link].*;

public class Arrays {

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

int size = [Link]();

String names[] = new String[size];

//input

for(int i=0; i<size; i++) {

names[i] = [Link]();

//output

for(int i=0; i<[Link]; i++) {

[Link]("name " + (i+1) +" is : " + names[i]);

2. Find the maximum & minimum number in an array of integers.

Apna College
[HINT : Read about Integer.MIN_VALUE & Integer.MAX_VALUE in Java]
import [Link].*;

public class Arrays {

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

int size = [Link]();

int numbers[] = new int[size];

//input

for(int i=0; i<size; i++) {

numbers[i] = [Link]();

int max = Integer.MIN_VALUE;

int min = Integer.MAX_VALUE;

for(int i=0; i<[Link]; i++) {

if(numbers[i] < min) {

min = numbers[i];

if(numbers[i] > max) {

max = numbers[i];

Apna College
[Link]("Largest number is : " + max);

[Link]("Smallest number is : " + min);

3. Take an array of numbers as input and check if it is an array sorted in


ascending order.

Eg : { 1, 2, 4, 7 } is sorted in ascending order.

{3, 4, 6, 2} is not sorted in ascending order.


import [Link].*;

public class Arrays {

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

int size = [Link]();

int numbers[] = new int[size];

//input

for(int i=0; i<size; i++) {

numbers[i] = [Link]();

boolean isAscending = true;

Apna College
for(int i=0; i<[Link]-1; i++) { // NOTICE [Link] - 1 as
termination condition

if(numbers[i] > numbers[i+1]) { // This is the condition for


descending order

isAscending = false;

if(isAscending) {

[Link]("The array is sorted in ascending order");

} else {

[Link]("The array is not sorted in ascending order");

Apna College
Java - Introduction to Programming
Lecture 11

2D Arrays In Java

It is similar to 2D matrices that we studied in 11th and 12th class.

a. Creating a 2D Array - with new keyword


int[][] marks = new int[3][3];

b. Taking a matrix as an input and printing its elements.


import [Link].*;

public class TwoDArrays {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int rows = [Link]();
int cols = [Link]();

int[][] numbers = new int[rows][cols];

//input
//rows
for(int i=0; i<rows; i++) {
//columns
for(int j=0; j<cols; j++) {
numbers[i][j] = [Link]();
}
}

for(int i=0; i<rows; i++) {


for(int j=0; j<cols; j++) {
[Link](numbers[i][j]+" ");
}
[Link]();
}
}

Apna College
}

c. Searching for an element x in a matrix.


import [Link].*;

public class TwoDArrays {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int rows = [Link]();
int cols = [Link]();

int[][] numbers = new int[rows][cols];

//input
//rows
for(int i=0; i<rows; i++) {
//columns
for(int j=0; j<cols; j++) {
numbers[i][j] = [Link]();
}
}

int x = [Link]();

for(int i=0; i<rows; i++) {


for(int j=0; j<cols; j++) {
//compare with x
if(numbers[i][j] == x) {
[Link]("x found at location (" + i + ", " + j +
")");
}
}
}

}
}

Apna College
Homework Problems
1. Print the spiral order matrix as output for a given matrix of numbers.
[Difficult for Beginners]

APPROACH :

Algorithm: (We are given a 2D matrix of n X m ).


1. We will need 4 variables:

a. row_start - initialized with 0.

b. row_end - initialized with n-1.

c. column_start - initialized with 0.

d. column_end - initialized with m-1.

2. First of all, we will traverse in the row row_start from column_start

Apna College
to column_end and we will increase the row_start with 1 as we have

traversed the starting row.

3. Then we will traverse in the column column_end from row_start to

row_end and decrease the column_end by 1.

4. Then we will traverse in the row row_end from column_end to

column_start and decrease the row_end by 1.

5. Then we will traverse in the column column_start from row_end to

row_start and increase the column_start by 1.

6. We will do the above steps from 2 to 5 until row_start <= row_end

and column_start <= column_end.

import [Link].*;

public class Arrays {

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int m = [Link]();

int matrix[][] = new int[n][m];

for(int i=0; i<n; i++) {

for(int j=0; j<m; j++) {

matrix[i][j] = [Link]();

[Link]("The Spiral Order Matrix is : ");

int rowStart = 0;

Apna College
int rowEnd = n-1;

int colStart = 0;

int colEnd = m-1;

//To print spiral order matrix

while(rowStart <= rowEnd && colStart <= colEnd) {

//1

for(int col=colStart; col<=colEnd; col++) {

[Link](matrix[rowStart][col] + " ");

rowStart++;

//2

for(int row=rowStart; row<=rowEnd; row++) {

[Link](matrix[row][colEnd] +" ");

colEnd--;

//3

for(int col=colEnd; col>=colStart; col--) {

[Link](matrix[rowEnd][col] + " ");

rowEnd--;

//4

for(int row=rowEnd; row>=rowStart; row--) {

Apna College
[Link](matrix[row][colStart] + " ");

colStart++;

[Link]();

2. For a given matrix of N x M, print its transpose.


import [Link].*;

public class Arrays {

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int m = [Link]();

int matrix[][] = new int[n][m];

for(int i=0; i<n; i++) {

for(int j=0; j<m; j++) {

matrix[i][j] = [Link]();

Apna College
[Link]("The transpose is : ");

//To print transpose

for(int j=0; j<m ;j++) {

for(int i=0; i<n; i++) {

[Link](matrix[i][j]+" ");

[Link]();

Apna College
Java - Introduction to Programming
Lecture 12

Strings

Declaration
String name = "Tony";

Taking Input
Scanner sc = new Scanner([Link]);
String name = [Link]();

Concatenation (Joining 2 strings)


String firstName = "Tony";
String secondName = "Stark";

String fullName = firstName + " " + secondName;


[Link](fullName);

Print length of a String


String firstName = "Tony";
String secondName = "Stark";

String fullName = firstName + " " + secondName;


[Link]([Link]());

Access characters of a string


String firstName = "Tony";
String secondName = "Stark";

String fullName = firstName + " " + secondName;

for(int i=0; i<[Link](); i++) {


[Link]([Link](i));
}

Apna College
Compare 2 strings
import [Link].*;

public class Strings {


public static void main(String args[]) {
String name1 = "Tony";
String name2 = "Tony";

if([Link](name2)) {
[Link]("They are the same string");
} else {
[Link]("They are different strings");
}

//DO NOT USE == to check for string equality


//Gives correct answer here
if(name1 == name2) {
[Link]("They are the same string");
} else {
[Link]("They are different strings");
}

//Gives incorrect answer here


if(new String("Tony") == new String("Tony")) {
[Link]("They are the same string");
} else {
[Link]("They are different strings");
}

}
}

Substring
The substring of a string is a subpart of it.
public class Strings {
public static void main(String args[]) {
String name = "TonyStark";

[Link]([Link](0, 4));

Apna College
}
}

ParseInt Method of Integer class


public class Strings {
public static void main(String args[]) {
String str = "123";
int number = [Link](str);
[Link](number);

}
}

ToString Method of String class


public class Strings {
public static void main(String args[]) {
int number = 123;
String str = [Link](number);
[Link]([Link]());

}
}

ALWAYS REMEMBER : Java Strings are Immutable.

Apna College
Homework Problems
1. Take an array of Strings input from the user & find the cumulative (combined)
length of all those strings.
import [Link].*;

public class Strings {

public static void main(String args[]) {

Scanner sc = new Scanner ([Link]);

int size = [Link]();

String array[] = new String[size];

int totLength = 0;

for(int i=0; i<size; i++) {

array[i] = [Link]();

totLength += array[i].length();

[Link](totLength);

2. Input a string from the user. Create a new string called ‘result’ in which you
will replace the letter ‘e’ in the original string with letter ‘i’.

Example :

original = “eabcdef’ ; result = “iabcdif”

Original = “xyz” ; result = “xyz”

Apna College
import [Link].*;

public class Strings {

public static void main(String args[]) {

Scanner sc = new Scanner ([Link]);

String str = [Link]();

String result = "";

for(int i=0; i<[Link](); i++) {

if([Link](i) == 'e') {

result += 'i';

} else {

result += [Link](i);

[Link](result);

3. Input an email from the user. You have to create a username from the email
by deleting the part that comes after ‘@’. Display that username to the user.

Example :

email = “apnaCollegeJava@[Link]” ; username = “apnaCollegeJava”

email = “helloWorld123@[Link]”; username = “helloWorld123”

Apna College
import [Link].*;

public class Strings {

public static void main(String args[]) {

Scanner sc = new Scanner ([Link]);

String email = [Link]();

String userName = "";

for(int i=0; i<[Link](); i++) {

if([Link](i) == '@') {

break;

} else {

userName += [Link](i);

[Link](userName);

Apna College
Java - Introduction to Programming
Exercise 1

Questions

1. Enter 3 numbers from the user & make a function to print their average.
2. Write a function to print the sum of all odd numbers from 1 to n.
3. Write a function which takes in 2 numbers and returns the greater of those
two.
4. Write a function that takes in the radius as input and returns the
circumference of a circle.
5. Write a function that takes in age as input and returns if that person is eligible
to vote or not. A person of age > 18 is eligible to vote.
6. Write an infinite loop using do while condition.
7. Write a program to enter the numbers till the user wants and at the end it
should display the count of positive, negative and zeros entered.
8. Two numbers are entered by the user, x and n. Write a function to find
𝑛
the value of one number raised to the power of another i.e. 𝑥 .
9. Write a function that calculates the Greatest Common Divisor of 2 numbers.
(BONUS)
10. Write a program to print Fibonacci series of n terms where n is input
by user :
0 1 1 2 3 5 8 13 21 .....
In the Fibonacci series, a number is the sum of the previous 2 numbers that
came before it.
(BONUS)

Apna College
Java - Introduction to Programming
Exercise 1 SOLUTIONS

1. Enter 3 numbers from the user & make a function to print their average.
//Try to convert it into a function on your own.

import [Link].*;

public class Solutions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
int c = [Link]();

int average = (a + b + c) / 3;
[Link](average);
}
}

2. Write a function to print the sum of all odd numbers from 1 to n.


import [Link].*;

public class Solutions {


public static void printSum(int n) {
int sum = 0;

for(int i=1; i<=n; i++) {


if(i % 2 != 0) {
sum = sum + i;
}
}

[Link](sum);
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
printSum(n);
}
}

3. Write a function which takes in 2 numbers and returns the greater of those
two.
import [Link].*;

public class Solutions {


public static int getGreater(int a, int b) {
if(a > b) {
return a;
} else {
return b;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
[Link](getGreater(a, b));
}
}

4. Write a function that takes in the radius as input and returns the
circumference of a circle.
import [Link].*;

public class Solutions {


public static Double getCircumference(Double radius) {
return 2 * 3.14 * radius;
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
Double r = [Link]();
[Link](getCircumference(radius));
}
}
5. Write a function that takes in age as input and returns if that person is eligible
to vote or not. A person of age > 18 is eligible to vote.
import [Link].*;

public class Solutions {


public static boolean isElligible(int age) {
if(age > 18) {
return true;
}
return false;
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int age = [Link]();
[Link](isElligible(age));
}
}

6. Write an infinite loop using do while condition.


import [Link].*;

public class Solutions {


public static void main(String args[]) {
do {

} while(true);
}
}

7. Write a program to enter the numbers till the user wants and at the end it
should display the count of positive, negative and zeros entered.
import [Link].*;

public class Solutions {


public static void main(String args[]) {
int positive = 0, negative = 0, zeros = 0;
[Link]("Press 1 to continue & 0 to stop");
Scanner sc = new Scanner([Link]);
int input = [Link]();
while(input == 1) {
[Link]("Enter your number : ");
int number = [Link]();
if(number > 0) {
positive++;
} else if(number < 0) {
negative++;
} else {
zeros++;
}

[Link]("Press 1 to continue & 0 to stop");


input = [Link]();
}

[Link]("Positives : "+ positive);


[Link]("Negatives : "+ negative);
[Link]("Zeros : "+ zeros);
}
}

8. Two numbers are entered by the user, x and n. Write a function to find
𝑛
the value of one number raised to the power of another i.e. 𝑥 .
//Try to convert it into a function on your own.

import [Link].*;

public class Solutions {


public static void main(String args[]) {
[Link]("Enter x");
Scanner sc = new Scanner([Link]);
int x = [Link]();
[Link]("Enter n");
int n = [Link]();

int result = 1;
//Please see that n is not too large or else result will exceed the size
of int
for(int i=0; i<n; i++) {
result = result * x;
}

[Link]("x to the power n is : "+ result);


}
}

9. Write a function that calculates the Greatest Common Divisor of 2 numbers.


(BONUS)
import [Link].*;

public class Solutions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n1 = [Link]();
int n2 = [Link]();

while(n1 != n2) {
if(n1>n2) {
n1 = n1 - n2;
} else {
n2 = n2 - n1;
}
}
[Link]("GCD is : "+ n2);
}
}

//Try to convert it into a function on your own.


10. Write a program to print Fibonacci series of n terms where n is input
by user :
0 1 1 2 3 5 8 13 21 .....
In the Fibonacci series, a number is the sum of the previous 2 numbers that
came before it.
(BONUS)
import [Link].*;

public class Solutions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();

int a = 0, b = 1;

[Link](a+" ");

if(n > 1) {
//find nth term
for(int i=2; i<=n; i++) {
[Link](b+" ");
//the concept below is called swapping
int temp = b;
b = a + b;
a = temp;
}

[Link]();
}
}
}
Java - Introduction to Programming
Lecture 13

String Builder

Declaration
StringBuilder sb = new StringBuilder("Apna College");
[Link](sb);

Get A Character from Index


StringBuilder sb = new StringBuilder("Tony");
//Set Char
[Link]([Link](0));

Set a Character at Index


StringBuilder sb = new StringBuilder("Tony");
//Get Char
[Link](0, 'P');
[Link](sb);

Insert a Character at Some Index


import [Link].*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("tony");
//Insert char
[Link](0, 'S');
[Link](sb);
}
}

Apna College
Delete char at some Index
import [Link].*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("tony");
//Insert char
[Link](0, 'S');
[Link](sb);

//delete char
[Link](0, 1);
[Link](sb);
}
}

Append a char
Append means to add something at the end.
import [Link].*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("Tony");
[Link](" Stark");
[Link](sb);
}
}

Print Length of String


import [Link].*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("Tony");
[Link](" Stark");
[Link](sb);

[Link]([Link]());
}
}

Apna College
Reverse a String (using StringBuilder class)

import [Link].*;

public class Strings {


public static void main(String args[]) {
StringBuilder sb = new StringBuilder("HelloWorld");

for(int i=0; i<[Link]()/2; i++) {


int front = i;
int back = [Link]() - i - 1;

char frontChar = [Link](front);


char backChar = [Link](back);

[Link](front, backChar);
[Link](back, frontChar);
}

[Link](sb);
}
}

Homework Problems
Try Solving all the String questions with StringBuilder.

Apna College
Java - Introduction to Programming
Lecture 14

Bit Manipulation

Get Bit
import [Link].*;

public class Bits {


public static void main(String args[]) {
int n = 5; //0101
int pos = 3;
int bitMask = 1<<pos;

if((bitMask & n) == 0) {
[Link]("bit was zero");
} else {
[Link]("bit was one");
}
}
}

Set Bit
import [Link].*;

public class Bits {


public static void main(String args[]) {
int n = 5; //0101
int pos = 1;
int bitMask = 1<<pos;

int newNumber = bitMask | n;


[Link](newNumber);
}
}

Apna College
Clear Bit
import [Link].*;
public class Bits {
public static void main(String args[]) {
int n = 5; //0101
int pos = 2;
int bitMask = 1<<pos;
int newBitMask = ~(bitMask);
int newNumber = newBitMask & n;
[Link](newNumber);
}
}

Update Bit

import [Link].*;

public class Bits {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int oper = [Link]();
// oper=1 -> set; oper=0 -> clear
int n = 5;
int pos = 1;

int bitMask = 1<<pos;


if(oper == 1) {
//set
int newNumber = bitMask | n;
[Link](newNumber);
} else {
//clear
int newBitMask = ~(bitMask);
int newNumber = newBitMask & n;
[Link](newNumber);
}

}
}

Apna College
Homework Problems
1. Write a program to find if a number is a power of 2 or not.
2. Write a program to toggle a bit a position = “pos” in a number “n”.
3. Write a program to count the number of 1’s in a binary representation
of the number.
4. Write 2 functions => decimalToBinary() & binaryToDecimal() to convert
a number from one number system to another. [BONUS]

Apna College
Sorting in JAVA

1. Bubble Sort
Idea: if arr[i] > arr[i+1] swap them. To place the element in their
respective position, we have to do the following operation N-1
times.
Time Complexity: O(N2)

Code
import [Link].*;

class Sorting {
public static void printArray(int arr[]) {
for(int i=0; i<[Link]; i++) {
[Link](arr[i]+" ");
}
[Link]();
}

public static void main(String args[]) {


int arr[] = {7, 8, 1, 3, 2};

//bubble sort
for(int i=0; i<[Link]-1; i++) {
for(int j=0; j<[Link]-i-1; j++) {
if(arr[j] > arr[j+1]) {
//swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

printArray(arr);
}
}

2. Selection Sort
Idea: The inner loop selects the minimum element in the
unsorted array and places the elements in increasing order.
Time complexity: O(N2)

Code
import [Link].*;

class Sorting {
public static void printArray(int arr[]) {
for(int i=0; i<[Link]; i++) {
[Link](arr[i]+" ");
}
[Link]();
}

public static void main(String args[]) {


int arr[] = {7, 8, 1, 3, 2};

//selection sort
for(int i=0; i<[Link]-1; i++) {
int smallest = i;
for(int j=i+1; j<[Link]; j++) {
if(arr[j] < arr[smallest]) {
smallest = j;
}
}
//swap
int temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}

printArray(arr);
}
}

3. Insertion Sort
Idea: Take an element from the unsorted array, place it in its
corresponding position in the sorted part, and shift the elements
accordingly.
Time Complexity: O(N2)

Code
import [Link].*;

class Sorting {
public static void printArray(int arr[]) {
for(int i=0; i<[Link]; i++) {
[Link](arr[i]+" ");
}
[Link]();
}

public static void main(String args[]) {


int arr[] = {7, 8, 1, 3, 2};

//insertion sort
for(int i=1; i<[Link]; i++) {
int current = arr[i];
int j = i - 1;
while(j >= 0 && arr[j] > current) {
//Keep swapping
arr[j+1] = arr[j];
j--;
}
arr[j+1] = current;
}
printArray(arr);
}
}
`

Common questions

Powered by AI

A function calculating the Fibonacci series employs loops to iteratively compute each term based on the previous two terms, using a repetitive process. Variables are used to store the current and previous terms needed for the calculation. Initially, the first two Fibonacci numbers are defined (often 0 and 1). Then, using a loop, the function repeatedly sums two preceding numbers to generate the next term in the series. The use of variables to temporarily store and swap values efficiently allows the function to continue this process up to the desired number of terms, resulting in an iterative and efficient computation .

Loops are critical in programming for executing a block of statements repeatedly until a predefined condition is met. The 'for' loop is particularly useful when the number of iterations is known beforehand. It combines initialization, the condition to be met, and the increment/decrement steps in a single line, making the code concise and easier to manage. In contrast, a 'while' loop evaluates the condition before the loop body, meaning the loop body might not execute even once if the condition is false. The 'do-while' loop, however, ensures that the loop body executes at least once since the condition check occurs after execution of the loop body .

Switch-case statements offer a more readable and organized way to handle conditions that depend on the value of a single variable. Unlike multiple if-else statements, which may become cumbersome and difficult to follow when many conditions are involved, a switch-case statement allows you to match a variable to a set of potential values and execute the corresponding code block for the first matching case. This format makes it easier to maintain and understand, especially when dealing with a larger set of conditions .

A 'do-while' loop is ideal in situations where the block of code must be executed at least once before the condition is evaluated. This is particularly useful when taking user input repeatedly until they choose to stop or meet a certain condition, such as entering marks until a zero is entered to stop. In the homework problem, the initial user input is always processed, and only subsequently, the continuation condition is checked, making 'do-while' a suitable choice .

Understanding prime numbers is crucial because it requires identifying a number's divisibility only by 1 and itself, a fundamental property for algorithmic implementations. This knowledge guides the algorithm's design to efficiently check for factors. In Java, a typical implementation involves iterating from 2 to the square root of the number, checking divisibility. If any number divides the candidate, it is not prime; if no divisors are found, it is prime. This approach minimizes iterations and enhances performance, making it efficient for determining primality of larger numbers .

StringBuilder optimizes string manipulation in Java by providing a mutable sequence of characters, which allows for modifications like append, insert, or delete operations without creating new String objects, thus reducing memory overhead. Unlike the immutable String class, StringBuilder can change its sequence through its methods efficiently. For example, adding characters using the 'append()' method modifies the existing string buffer, enhancing performance when multiple string modifications are needed. StringBuilder is particularly useful in scenarios where a lot of dynamic changes are performed on strings, such as building complex string outputs in loops .

The key elements of pattern printing programs in Java include understanding loops (nested loops for more complex patterns), conditionals within loops, and managing variables to control printing mechanisms. Mastery over these components allows programmers to manipulate and experiment with iterations and conditions, making it possible to develop more complex patterns. For example, by varying loop conditions and using if-statements within loops, programmers can control when and how many times specific characters (like stars or numbers) are printed, enabling the creation of diverse geometric shapes and numerical sequences .

The advantages of using functions include promoting code reusability, clarity, and maintainability. Functions encapsulate specific logic, such as calculating the average of numbers, which segregates this operation from the main method, enhancing readability and debugging efficiency. By having a dedicated function for average calculations, the main method can focus on flow control rather than computational details, leading to cleaner and more modular code. Functions can be reused across different sections of a program or in different projects, reducing code duplication and potential errors .

Input validation enhances the robustness of a calculator program by ensuring that the inputs provided by the user are within acceptable and expected ranges before processing them. For instance, when performing division or modulo operations, validating inputs to ensure that the divisor is not zero prevents runtime errors or undefined behaviors like division by zero. Implementing checks before executing these operations ensures that the program can handle exceptional cases gracefully and provide informative feedback to the user, such as "Invalid Division" for division by zero .

Conditionals enable structured decision-making in Java by allowing programs to execute actions or calculations based on certain conditions, leading to dynamic behavior tailored to varying inputs or states. Nested conditionals are beneficial when decisions depend on previous outcomes or multiple intertwined conditions. For instance, when evaluating academic performance, nested conditionals can first check if marks are within a valid range, then determine performance tiers (e.g., excellent, good, fair) based on score thresholds. This structure ensures accurate categorization based on multiple interrelated criteria .

You might also like