Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views42 pages

Java File

The document contains a series of Java programming exercises by Anurag Gupta, covering various concepts such as palindrome checking, swapping numbers, Fibonacci series, command-line arguments, OOP principles, inheritance, polymorphism, exception handling, multithreading, and file I/O. Each program includes code snippets, objectives, and expected outputs. Additionally, it includes a Spring Framework application demonstrating dependency injection with an Employee class.

Uploaded by

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

Java File

The document contains a series of Java programming exercises by Anurag Gupta, covering various concepts such as palindrome checking, swapping numbers, Fibonacci series, command-line arguments, OOP principles, inheritance, polymorphism, exception handling, multithreading, and file I/O. Each program includes code snippets, objectives, and expected outputs. Additionally, it includes a Spring Framework application demonstrating dependency injection with an Employee class.

Uploaded by

Anurag Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Anurag Gupta 2200911540025 CSDS-1 G1

PROGRAM NO 01
OBJECTIVE:- Use Java compiler and eclipse platform to write and execute java program.

(a) Palindrome Number


package Anurag;
public class palindrome {
public static void main(String[] args) {
int r, sum = 0, temp;
int n = 454;
temp = n;
while (n > 0) {
r = n % 10;
sum = (sum * 10) + r;
n = n / 10;
}
if (temp == sum)
System.out.println("palindrome number");
else
System.out.println("not a palindrome number");
}
}

Output:-

(b) Swap of Two Number


package Anurag;
public class swap {
public static void main(String[] args)
{
int a, b, c;
a = 56;
b = 45;
System.out.println("a=" + a);
System.out.println("b=" + b);
c = a;
a = b;
b = c;
System.out.println("a=" + a);
System.out.println("b=" + b);
}
Anurag Gupta 2200911540025 CSDS-1 G1
Output:-

(c) Fibonnaci Series


package Anurag;
public class fibonnaci {
public static void main(String[] args) {
int n1 = 0, n2 = 1, n3, i, count = 10;
System.out.print(n1+" ");
System.out.print(n2+" ");
for (i = 2; i < count; ++i)
{
n3 = n1 + n2;
System.out.print(n3+" ");
n1 = n2;
n2 = n3;
}
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 02
OBJECTIVE:- Creating simple java programs using command line arguments
package Anurag;
class Main {
public static void main(String[] args) {
System.out.println("Command-Line arguments are");
for(String str: args) {
System.out.println(str);
}
}
}
Input:-

Output:-
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 03
OBJECTIVE:- Understand OOP concepts and basics of Java programming.

Baisc Concepts of Java


1. Class and Object:
- Class: A blueprint or template for creating objects, defining a datatype by bundling data and methods that work on the
data.
- Object: An instance of a class. When a class is instantiated, it creates an object.

2. Encapsulation:
- Encapsulation involves wrapping data (variables) and methods (functions) into a single unit called a class.
- This concept hides the internal state of the object and requires all interaction to be performed through an object's
methods. It protects the data from unauthorized access and modification.

3. Inheritance:
- Inheritance is a mechanism where a new class inherits the properties and behavior of an existing class.
- This promotes code reuse and establishes a natural hierarchical relationship between classes. The class that inherits is
called a subclass, and the class from which it inherits is called a superclass.

4. Polymorphism:
- Polymorphism means "many forms" and allows objects to be treated as instances of their parent class rather than
their actual class.
- The most common use of polymorphism is when a parent class reference is used to refer to a child class object. It is
achieved through method overloading (compile-time polymorphism) and method overriding (runtime polymorphism).

5. Abstraction:
- Abstraction involves hiding the complex implementation details and showing only the essential features of the object.
- It is achieved using abstract classes and interfaces. Abstraction focuses on what an object does instead of how it does
it, reducing complexity and increasing efficiency in coding.

(a) Abstaction
package Anurag;
abstract class Shape {
public abstract void draw();
}
class Circle extends Shape {
public void draw() { System.out.println("Circle!"); }
}
public class Abstact {
public static void main(String[] args) {
Shape circle = new Circle();
circle.draw();
}
Anurag Gupta 2200911540025 CSDS-1 G1
}
Output:-

(b) Encapsulation
class Person {
private String name;
private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Anurag");
peson.setAge(19);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 04
OBJECTIVE:- Create Java programs using inheritance and polymorphism.
(a).INHERITANCE

package Anurag;
class college {
public void college_name() {
System.out.println("JSS COLLEGE");}
}
class class_room extends college {
public void section() {
college_name();
System.out.println("CSDS-1");}
}
class section extends class_room {
public void Class_room(String Name, int Roll_no, String Sub) {
section();
System.out.println("Name: " + Name);
System.out.println("Roll no.: " + Roll_no);
System.out.println("Subject: " + Sub);
}
}
public class inherent {
public static void main(String[] args) {
section JSS = new section();
JSS.Class_room("Anurag", 20, "Java");
System.out.println();
JSS.Class_room("Ashish", 40, "Python");
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1

(b).POLYMORPHISM

(i) CompileTimePolymorphism

class MathOperations {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
}
public class CompileTimePolymorphism {
public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum of two integers: " + math.add(10, 20));
System.out.println("Sum of three integers: " + math.add(10, 20, 30));
System.out.println("Sum of two doubles: " + math.add(10.5, 20.5));
}
}
Output:-

(ii) RunTimePolymorphism

class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
Anurag Gupta 2200911540025 CSDS-1 G1
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public class RuntimePolymorphism {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound();
myCat.makeSound();
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 05
OBJECTIVE:- Implement error-handling techniques using exception handling and multithreading.
Exception Handling
(a).Try Catch

package Anurag;
public class Main {
void divide(int a, int b) {
int res;
try {
res = a / b;
System.out.println("Division process has been done successfully.");
System.out.println("Result came after division is: " + res);
} catch (java.lang.ArithmeticException ex) {
System.out.println("Should avoid dividing by 0 " + ex);
}
}
public
static void main(String argvs[]) {
Main obj = new Main();
obj.divide(1, 0);
}
}
Output:-

(b).Try Catch Nested

package Anurag;
public class Main {
void divideAndProcess(final int a, final int b) {
try {
final int res;
try {
res = a / b;
System.out.println("Division process has been done successfully.");
System.out.println("Result after division is: " + res);
int[] array = new int[1];
array[1] = res;
} catch (final java.lang.ArithmeticException ex) {
System.out.println("Should avoid dividing by 0 " + ex);
}
} catch (final ArrayIndexOutOfBoundsException ex) {
System.out.println("Array index out of bounds " + ex);
}
Anurag Gupta 2200911540025 CSDS-1 G1
}
public static void main(final String[] argvs) {
final Main obj = new Main();
obj.divideAndProcess(1, 0);
obj.divideAndProcess(4, 2);
}
}
Output:-

c).Try Catch Finally

package Anurag;
public class Main {
void divide(final int a, final int b) {
final int res;
try {
res = a / b;
System.out.println("Division process has been done successfully.");
System.out.println("Result after division is: " + res);
} catch (final java.lang.ArithmeticException ex) {
System.out.println("Should avoid dividing by 0 " + ex);
} finally {
System.out.println("Finally block executed. Cleaning up if necessary.");
}
}
public static void main(final String[] argvs) {
final Main obj = new Main();
obj.divide(1, 0);
}
}
Output:-

(d).Throw
package Anurag;
public class ThrowExample {
public static void checkValue(int value) {
if (value < 0) {
throw new IllegalArgumentException(
Anurag Gupta 2200911540025 CSDS-1 G1
"Negative value is not allowed: " + value);
}
System.out.println("Value is acceptable: " + value);
}
public static void main(String[] args) {
try {
checkValue(10);
checkValue(-5);
} catch (IllegalArgumentException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
}
Output:-

(e).Throws
import java.io.IOException;
class Main {
void m() throws IOException {
throw new IOException("device error");
}
void n() throws IOException {
m();
}
void p() {
try {
n();
} catch (Exception e) {
System.out.println("exception handled");
}
}
public static void main(String args[]) {
Main obj = new Main();
obj.p();
System.out.println("normal flow...");
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1
Multithreading
class MultithreadingDemo extends Thread {
@Override
public void run() {
try {
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
} catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
public class Main {
public static void main(String[] args) {
int n = 8;
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 06
OBJECTIVE:- Create java program with the use of java packages.
Mathoperations
package mathoperations;
public class ArithmeticOperations {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public double divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
return (double) a / b;
}
}
Main
package main;
import mathoperations.ArithmeticOperations;
public class MainApplication {
public static void main(String[] args) {
ArithmeticOperations operations = new ArithmeticOperations();
int a = 10;
int b = 5;
System.out.println("Addition: " + operations.add(a, b));
System.out.println("Subtraction: " + operations.subtract(a, b));
System.out.println("Multiplication: " + operations.multiply(a, b));
System.out.println("Division: " + operations.divide(a, b));
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1

PROGRAM NO 07
OBJECTIVE:- Construct java program using Java I/O package.
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
try {
BufferedReader reader =
new BufferedReader(new FileReader("src/Read.txt"));
BufferedWriter writer =
new BufferedWriter(new FileWriter("src/Write.txt"));
String line;
while ((line = reader.readLine()) != null) {
String processedLine = line.toUpperCase();
writer.write(processedLine);
writer.newLine();
}
reader.close();
writer.close();
System.out.println("File processing complete. Check the output file.");
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 08
OBJECTIVE:- Create industry oriented application using Spring Framework
Employee.java
package com.Anurag;
public class Employee {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
void display(){
System.out.println(id+" "+name+" "+city);
}
}

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="obj" class="com.Anurag.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Anurag Gupta</value>
Anurag Gupta 2200911540025 CSDS-1 G1
</property>
<property name="city">
<value>Kanpur</value>
</property>
</bean>
</beans>
Test.java
package com.Anurag;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee e=(Employee)factory.getBean("obj");
s.display();
}
}
Output:-
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 12
OBJECTIVE:- WAP to print the sum of all numbers up to a given number.
#include <stdio.h>
#include<conio.h>
int main()
{
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
sum =sum + i;
}
printf("Sum = %d", sum);
getch();
return 0;
}
Input:-
Enter a positive integer: 78
Output:-
Sum = 3081
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 13
OBJECTIVE:- WAP to print the sum of all numbers up to a given number.
#include<stdio.h>
#include<conio.h>
int main()
{
int x,fact=1,n;
printf("Enter a number to find factorial: ");
scanf("%d",&n);
for(x = 1; x<=n ;x++)
fact=fact*x;
printf("Factorial of %d is: %d",n,fact);
getch();
return 0;
} Input:-
Enter a number to find factorial: 6
Output:-
Factorial of 6 is: 720
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 14
OBJECTIVE:- WAP to print sum of even and odd numbers from 1 to N numbers
#include <stdio.h>
#include<conio.h>
int main()
{
int i, number, Even_Sum = 0, Odd_Sum = 0;
printf("Enter a Number : ");
scanf("%d", &number);
for(i = 1; i <= number; i++)
{
if ( i%2 == 0 )
{Even_Sum = Even_Sum + i;}
else
{Odd_Sum = Odd_Sum + i;}
}
printf("The Sum of Even Numbers upto %d = %d", number, Even_Sum);
printf("\nThe Sum of Odd Numbers upto %d = %d", number, Odd_Sum);
getch();
return 0;
}
Input:-
Enter a Number : 65
Output:-
The Sum of Even Numbers upto 65 = 1056
The Sum of Odd Numbers upto 65 = 1089
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 15
OBJECTIVE:- WAP to print the Fibonacci series.
#include <stdio.h>
#include<conio.h>
int main() {
int i, n;
int t1 = 0,t2 = 1;
int nextTerm = t1 + t2;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: %d %d ", t1, t2);
for (i = 3; i <= n; i++) {
printf("%d ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
getch();
return 0;
}
Input:-
Enter the number of terms: 14
Output:-
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 16
OBJECTIVE:- WAP to check whether the entered number is prime or not
#include <stdio.h>
#include<conio.h>
int main() {
int n, i,s=0;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n == 0 || n == 1)
s = 1;
for (i = 2; i <= n/2; i++)
{
if (n % i == 0) {
s = 1;
break;}
}
if (s == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
getch();
return 0;
}
Input:-
Enter a positive integer: 67
Output:-
67 is a prime number.
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 17
OBJECTIVE:- WAP to find the sum of digits of the entered number.
#include<stdio.h>
#include<conio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
getch();
return 0;
}
Input:-
Enter a number:98
Output:-
Sum is=17
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 18
OBJECTIVE:- WAP to find the reverse of a number.
#include <stdio.h>
#include<conio.h>
int main() {
int n, reverse = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n=n /10;
}
printf("Reversed number = %d", reverse);
getch();
return 0;
}
Input:-
Enter an integer: 78668
Output:-
Reversed number = 86687
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 19
OBJECTIVE:- WAP to print Armstrong numbers from 1 to 100
#include <math.h>
#include <stdio.h>
#include<conio.h>
int main()
{
int i, sum, num, count = 0;
printf("All Armstrong number between 1 and 1000 are:\n");
for (i = 1; i <= 100; i++) {
num = i;
while (num != 0) {
num /= 10;
count++;
}
num = i;
sum = pow(num % 10, count)
+ pow((num % 100 - num % 10) / 10, count);
if (sum == i) {
printf("%d ", i);
}
count = 0;
}
getch();
return 0;
}
Output:-
All Armstrong number between 1 and 1000 are:
123456789
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 20
OBJECTIVE:- WAP to convert binary number into decimal number and vice versa.
#include <math.h>
#include <stdio.h>
#include<conio.h>
int main(){
int n,r,rev=0,p=0;
printf("Enter binary number=");
scanf("%d",&n);
while(n>0)
{r=n%10;
if(r!=0)
{
rev= rev+(int)pow(2,p);
}
n=n/10;
p++;
}
printf("Decimal number=%d",rev);
getch():
return 0;
}
Input:-
Enter binary number=10101
Output:-
Decimal number=21
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 21
OBJECTIVE:- WAP that simply takes elements of the array from the user and finds the sum of these
elements.
#include <math.h>
#include<stdio.h>
#include<conio.h>
int main(){
clrscr();
int arr [1000],n,i,sum=0;
printf("Enter Size of Array: ");
scanf("%d",&n);
for( i =0;i<n;i++)
{scanf("%d",&arr[i]);}
for( i =0;i<n;i++)
{sum=sum+arr[i];}
printf("Sum: %d",sum);
getch();
return 0;
}
Input:-
Enter Size of Array: 4
2691
Output:-
Sum: 18
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 22
OBJECTIVE:- WAP that inputs two arrays and saves sum of corresponding elements of these arrays in
a third array and prints them.
#include <math.h>
#include<stdio.h>
#include<conio.h>
int main()
{ clescr();
int i,ar1[4],ar2[4],sum[4];
printf("Enter first array:-\n");
for(i=0;i<4;i++){
printf("ar1[%d]=",i);
scanf("%d",&ar1[i]);
}
printf("Enter second array:-\n");
for(i=0;i<4;i++){
printf("ar2[%d]=",i);
scanf("%d",&ar2[i]);
}
for(i=0;i<4;i++){
sum[i]=ar1[i]+ar2[i];
}
printf("Sum of arrays:-");
for(i=0;i<4;i++){
printf("\nsum[%d]=%d",i,sum[i]);
}
getch();
return 0;
}
Input:-
Enter first array:-
ar1[0]=2
ar1[1]=4
ar1[2]=6
ar1[3]=7
Enter second array:-
ar2[0]=2
ar2[1]=8
ar2[2]=5
ar2[3]=8
Output:-
Sum of arrays:-
sum[0]=4
sum[1]=12
sum[2]=11
sum[3]=15
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 23
OBJECTIVE:- WAP to find the minimum and maximum element of the array.
#include <math.h>
#include<stdio.h>
#include<conio.h>
int main(){
clrscr();
int i;
int max=-1;
int min=10000;
printf("Array is 43,24,223,432,2\n");
int arr[5]={43,24,223,432,2};
for(i=0;i<5;i++)
if(arr[i]>max)
max=arr[i];
printf("Max is %d\n",max);
for(i=0;i<5;i++)
if(arr[i]<min)
min=arr[i];
printf("Min is %d",min);
getch();
return 0;
}
Output:-
Array is 43,24,223,432,2
Max is 432
Min is 2
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 24
OBJECTIVE:- WAP to search an element in a array using Linear Search.
#include <math.h>
#include<stdio.h>
#include<conio.h>
int main(){
clrscr();
int arr[5]={4,2,5,62,1};
int k,i,a=0;
printf("Enter Number for cheking: ");
scanf("%d",&k);
for(i=0;i<5;i++)
{
if( k==arr[i]){
a=1;
break;}
}
if(a==1)
printf("Number Found");
else
printf("Not Found");
getch();
return 0;
}
Output:-
Enter Number for cheking: 45
Not Found
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 25
OBJECTIVE:- WAP to sort the elements of the array in ascending order using Bubble Sort technique.
#include <math.h>
#include <stdio.h>
#include <conio.h>
int main()
{
clrscr();
int array[100], n, c, d, swap;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d integers: ", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c =0 ; c < n - 1; c++){
for (d = 0 ; d < n - c - 1; d++){
if (array[d] > array[d+1]) {
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d ", array[c]);
getch();
return 0;
}
Input:-
Enter number of elements: 4
Enter 4 integers: 4 2 8 6
Output:-
Sorted list in ascending order:
2468
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 26
OBJECTIVE:- WAP to add and multiply two matrices of order nxn.
#include <math.h>
#include<stdio.h>
#include<conio.h>
void main()
{ clrscr();
int a[10][10], b[10][10], c[10][10]={0}, d[10][10]={0},i,j,k,m,n,p,q;
printf("Enter no. of rows and columns in matrix A: ");
scanf("%d%d",&m,&n);
printf("Enter no. of rows and columns in matrix B: ");
scanf("%d%d",&p,&q);
if(m!=p || n!=q)
{
printf("Matrix Addition is not possible");
return;
}
else if(n!=p)
{
printf("Matrix Multiplication is not possible");
return;
}
else
{ printf("Enter elements of matrix A:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d", &a[i][j]);
printf("Enter elements of matrix B:\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d", &b[i][j]);

//Matrix Addition

for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j] = a[i][j] + b[i][j];
printf("\nResult of Matirx Addition:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ", c[i][j]);
printf("\n");
}
Anurag Gupta 2200911540025 CSDS-1 G1

//Matrix Multiplication

for(i=0;i<m;i++)
for(j=0;j<q;j++)
for(k=0;k<p;k++)
d[i][j] += a[i][k]*b[k][j];

printf("\nResult of Matirx Multiplication:\n");


for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d ", d[i][j]);
printf("\n");
}
}
getch();
}
Input:-
Enter no. of rows and columns in matrix A: 3 3
Enter no. of rows and columns in matrix B: 3 3
Enter elements of matrix A:
368
713
416
Enter elements of matrix B:
619
532
280
Output:-
Result of Matirx Addition:
9 7 17
12 4 5
696

Result of Matirx Multiplication:


64 85 39
53 34 65
41 55 38
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 27
OBJECTIVE:- WAP that finds the sum of diagonal elements of a mxn matrix.
#include <math.h>
#include <stdio.h>
#include<conio.h>
int main (){
clrscr();
int array[10][10];
int i, j, m, n, a = 0, sum = 0;
printf("Enter the order of the matix: ");
scanf("%d %d", &m, &n);
if (m == n )
{ printf("Enter the the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j){
scanf("%d", &array[i][j]);
}
}
//Sum Of Diagonal
for (i = 0; i < m; ++i) {
sum = sum + array[i][i];
a = a + array[i][m - i - 1];
}
printf("\nThe sum of the main diagonal elements is = %d\n", sum);
printf("The sum of the off diagonal elements is = %d\n", a);
}
else
printf("The given order is not square matrix\n");
getch();
return 0;
}
Input:-
Enter the order of the matix: 3 3
Enter the the matrix
146
738
341
Output:-
The sum of the main diagonal elements is = 5
The sum of the off diagonal elements is = 12
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 28
OBJECTIVE:- WAP to implement strlen (), strcat (),strcpy () using the concept of Functions.
#include <math.h>
#include <stdio.h>
#include<conio.h>
// Function to calculate the length of a string
int strlen_custom(const char *str)
{
int length = 0;
while (str[length] != '\0')
{
length++;
}
return length;
}
// Function to concatenate two strings
void strcat_custom(char *dest, const char *src)
{
int dest_length = strlen_custom(dest);
int i = 0;
while (src[i] != '\0')
{
dest[dest_length + i] = src[i];
i++;
}
dest[dest_length + i] = '\0';
}
// Function to copy one string to another
void strcpy_custom(char *dest, const char *src)
{
int i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
int main()
{ clrscr();
char str1[100], str2[100];
printf("Enter a string: ");
gets(str1);
// Test strlen_custom()
int length = strlen_custom(str1);
Anurag Gupta 2200911540025 CSDS-1 G1
printf("Length of the string: %d\n", length);
printf("Enter another string: ");
gets(str2);
// Test strcat_custom()
strcat_custom(str1, str2);
printf("Concatenated string: %s\n", str1);
// Test strcpy_custom()
char copy[100];
strcpy_custom(copy, str1);
printf("Copied string: %s\n", copy);
getch();
return 0;
}
Input:-
Enter a string: Anurag
Enter another string: Gupta
Output:-
Length of the string: 6
Concatenated string: AnuragGupta
Copied string: AnuragGupta
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 29
OBJECTIVE:- Define a structure data type TRAIN_INFO. The type contain Train No.: integer type
Train name: string Departure Time: aggregate type TIME Arrival Time: aggregate type
TIME Start station: string End station: string The structure type Time contains two
integer members: hour and minute. Maintain a train timetable and implement the
following operations:
a. List all the trains (sorted according to train number) that depart from a particular
section.
b. List all the trains that depart from a particular station at a particular time.
c. List all he trains that depart from a particular station within the next one hour of
a given time.
d. List all the trains between a pair of start station and end station.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include<conio.h>
// Structure for time
typedef struct {
int hour;
int minute;
} Time;

// Structure for train information


typedef struct {
int trainNo;
char trainName[100];
Time departureTime;
Time arrivalTime;
char startStation[100];
char endStation[100];
} TRAIN_INFO;

// Function to list all trains departing from a particular section


void listTrainsFromSection(TRAIN_INFO timetable[], int numTrains, char section[])
{
printf("Trains departing from section: %s\n", section);
printf("--------------------------------\n");

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


if (strstr(timetable[i].startStation, section) != NULL) {
printf("Train No: %d, Train Name: %s\n", timetable[i].trainNo, timetable[i].trainName);
}
}
printf("--------------------------------\n");
}
Anurag Gupta 2200911540025 CSDS-1 G1

// Function to list all trains departing from a particular station at a particular time
void listTrainsFromStationAtTime(TRAIN_INFO timetable[], int numTrains, char station[], Time time)
{
printf("Trains departing from station: %s at %02d:%02d\n", station, time.hour, time.minute);
printf("--------------------------------\n");

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


if (strcmp(timetable[i].startStation, station) == 0 && timetable[i].departureTime.hour == time.hour &&
timetable[i].departureTime.minute == time.minute) {
printf("Train No: %d, Train Name: %s\n", timetable[i].trainNo, timetable[i].trainName);
}
}
printf("--------------------------------\n");
}
// Function to list all trains departing from a particular station within the next one hour of a given time
void listTrainsFromStationWithinOneHour(TRAIN_INFO timetable[], int numTrains, char station[], Time time)
{
printf("Trains departing from station: %s within the next one hour of %02d:%02d\n", station, time.hour, time.minute);
printf("--------------------------------\n");
for (int i = 0; i < numTrains; i++) {
if (strcmp(timetable[i].startStation, station) == 0 && timetable[i].departureTime.hour >= time.hour &&
timetable[i].departureTime.minute >= time.minute && (timetable[i].departureTime.hour < time.hour + 1 ||
(timetable[i].departureTime.hour == time.hour + 1 && timetable[i].departureTime.minute < time.minute))) {
printf("Train No: %d, Train Name: %s\n", timetable[i].trainNo, timetable[i].trainName);
}
}
printf("--------------------------------\n");
}
// Function to list all trains between a pair of start station and end station
void listTrainsBetweenStations(TRAIN_INFO timetable[], int numTrains, char startStation[], char endStation[])
{
printf("Trains between stations: %s and %s\n", startStation, endStation);
printf("--------------------------------\n");
for (int i = 0; i < numTrains; i++) {
if (strcmp(timetable[i].startStation, startStation) == 0 && strcmp(timetable[i].endStation, endStation) == 0) {
printf("Train No: %d, Train Name: %s\n", timetable[i].trainNo, timetable[i].trainName);
}
}
printf("--------------------------------\n");
}
int main()
{ clrscr();
// Example timetable data
TRAIN_INFO timetable[] = {
{1001, "Express 1", {9, 0}, {11, 30}, "Station A", "Station D"},
{1002, "Express 2", {10, 15}, {12, 45}, "Station B", "Station E"},
Anurag Gupta 2200911540025 CSDS-1 G1
{1003, "Fast Train", {11, 30}, {13, 45}, "Station A", "Station C"},
{1004, "Local Train", {14, 0}, {16, 30}, "Station C", "Station D"},
{1005, "Express 3", {15, 45}, {18, 0}, "Station B", "Station F"}
};
int numTrains = sizeof(timetable) / sizeof(timetable[0]);
// Example usage of the operations
// a. List all trains departing from a particular section
listTrainsFromSection(timetable, numTrains, "Station A");
// b. List all trains departing from a particular station at a particular time
Time time1 = {11, 30};
listTrainsFromStationAtTime(timetable, numTrains, "Station A", time1);
// c. List all trains departing from a particular station within the next one hour of a given time
Time time2 = {10, 0};
listTrainsFromStationWithinOneHour(timetable, numTrains, "Station B", time2);
// d. List all trains between a pair of start station and end station
listTrainsBetweenStations(timetable, numTrains, "Station C", "Station D");
getch();
return 0;
}
Output:-
Trains departing from section: Station A
--------------------------------
Train No: 1001, Train Name: Express 1
Train No: 1003, Train Name: Fast Train
--------------------------------
Trains departing from station: Station A at 11:30
--------------------------------
Train No: 1003, Train Name: Fast Train
--------------------------------
Trains departing from station: Station B within the next one hour of 10:00
--------------------------------
Train No: 1002, Train Name: Express 2
--------------------------------
Trains between stations: Station C and Station D
--------------------------------
Train No: 1004, Train Name: Local Train
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 30
OBJECTIVE:- WAP to swap two elements using the concept of pointers.
#include <math.h>
#include <stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main(){
clrscr();
int a,b;
printf("Enter a Number a : ");
scanf("%d",&a);
printf("Enter a Number b : ");
scanf("%d",&b);
swap(&a,&b);
printf("%d %d",a,b);
getch():
return 0;
}
Input:-
Enter a Number a : 7
Enter a Number b : 4
Output:-
47
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 32
OBJECTIVE:- WAP to compare the contents of two files and determine whether they are same or
not.
#include<conio.h>
#include <stdio.h>
#include <stdlib.h>
/* Function declaration */
int compareFile(FILE * fPtr1, FILE * fPtr2, int * line, int * col);
int main(){
FILE * fPtr1; //File pointer to hold reference of input file
FILE * fPtr2;
char path1[100],path2[100];
int diff,line, col;
/* Input path of files to compare */
printf("Enter path of first file: ");
scanf("%s", path1);
printf("Enter path of second file: ");
scanf("%s", path2);
/* Open all files to compare */
fPtr1 = fopen(path1, "r");
fPtr2 = fopen(path2, "r");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr1 == NULL || fPtr2 == NULL)
{/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
diff = compareFile(fPtr1, fPtr2, &line, &col); // Call function to compare file
if (diff == 0)
{
printf("\nBoth files are equal.");
}
else
{
printf("\nFiles are not equal.\n");
printf("Line: %d, col: %d\n", line, col);
}
fclose(fPtr1); //Finally close files to release resources
fclose(fPtr2);
return 0;
}

//Function to compare two files.


Anurag Gupta 2200911540025 CSDS-1 G1
//Returns 0 if both files are equivalent, otherwise returns
//-1 and sets line and col where both file differ.
int compareFile(FILE * fPtr1, FILE * fPtr2, int * line, int * col)
{
char ch1, ch2;
*line = 1;
*col = 0;
do
{
ch1 = fgetc(fPtr1); // Input character from both files
ch2 = fgetc(fPtr2);
if (ch1 == '\n') // Increment line
{
*line += 1;
*col = 0;
}
if (ch1 != ch2) // If characters are not same then return -1
return -1;
*col += 1;
} while (ch1 != EOF && ch2 != EOF);
if (ch1 == EOF && ch2 == EOF) /* If both files have reached end */
return 0;
else
return -1;
}
//File1
//Learn C programming
//Working with files and directories.

//File2
//Learn C programming
//Working with array and pointers.

Input:-
Enter path of first file: data\File1.txt
Enter path of second file: data\File2.txt
Output:-
Files are not equal.
Line: 2, col: 14
Anurag Gupta 2200911540025 CSDS-1 G1
PROGRAM NO 32
OBJECTIVE:- WAP to check whether a given word exists in a file or not. If yes then find the number
of
times it occurs.
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
//File contain lines:
//how are you.
//this is a boy
//i am good
{
Clrscr():
FILE* filePointer;
int wordExist=0;
int bufferLength = 255;
char search[100];
printf("Enter word to be search=");
scanf("%s",search);
char line[bufferLength];
filePointer = fopen("D:\\file.txt", "r");
while(fgets(line, bufferLength, filePointer))
{
char *ptr = strstr(line, search);
if (ptr != NULL)
{
wordExist=1;
break;
}
}
fclose(filePointer);
if (wordExist==1)
{printf("Word exists.");}
else {printf("Word doesn't exist.");}
getch();
return 0
}
Input:-
Enter word to be search=is
Output:-
Word exists.

You might also like