31
Assignment Questions C 1. What are the major differences between C and Java? Ans: C Programming language JAVA •C breaks down to functions and so it is a  proced ural lang uage •JAVA breaks down to objects and so it is a data oriented language •C is a compile d code i.e. it con ver ts obj ect code in to machine code •Java is an Interpreted language i.e. it is first converted in to byte code and then executed by JVM (Java Virtual Machine). C is a low level language JAVA is a high level language •The User-Based Memory Management in C  by us ing lib rary call s like ma lloc( ) & free  •JAVA uses a garbage collector that deletes the obj ects that no longe r hav e any refere nces to them. •C does no t su ppo rt an y time of overl oad ing •JAVA s upp orts Met hod Overl oad ing i. e. we ca n have two or more functions with the same name 2. What is call by reference and call by value? Ans: In c call by value means the functio n passes a value to the variable where as in call by reference location number or address is passed to the function. Call by value actual argument is copied to the formal argument. changes made in the formal are no affected to the latter. Since the address is passed in call by reference changes made in formal arguments will affect the actual arguments too. 3. What are the differences between an unsigned short int and a long int? Ans : Unsigned short int of 2bytes size (usually) is an integer variable which always store  positiv e value s ranging from 0 to 65 535 (3 2 Kb). Lo ng int is a sig ne d va ria bl e wh ich st or es va lue ra ng ing fro m -21 4748 36 48 to +2147483648(2 GB).

assign1 ans

Embed Size (px)

Citation preview

Page 1: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 1/31

Assignment Questions

C

1. What are the major differences between C and Java?

Ans:

C Programming language JAVA

•C breaks down to functions and so it is a

 procedural language

•JAVA breaks down to objects and so it is a data

oriented language

•C is a compiled code i.e. it converts object

code in to machine code

•Java is an Interpreted language i.e. it is first

converted in to byte code and then executed by

JVM (Java Virtual Machine).

•C is a low level language •JAVA is a high level language

•The User-Based Memory Management in C

 by using library calls like malloc( ) & free

 

•JAVA uses a garbage collector that deletes the

objects that no longer have any references to

them.

•C does not support any time of overloading •JAVA supports Method Overloading i.e. we can

have two or more functions with the same name

2. What is call by reference and call by value?

Ans:

In c call by value means the function passes a value to the variable where as in call by

reference location number or address is passed to the function.

Call by value actual argument is copied to the formal argument. changes made in the

formal are no affected to the latter.

Since the address is passed in call by reference changes made in formal arguments will

affect the actual arguments too.

3. What are the differences between an unsigned short int and a long int?

Ans:

Unsigned short int of 2bytes size (usually) is an integer variable which always store

 positive values ranging from 0 to 65535 (32 Kb).

Long int is a signed variable which stores value ranging from -2147483648 to

+2147483648(2 GB).

Page 2: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 2/31

4. What is a const pointer?

Ans:

Const Pointer is that pointer which shows the one address on which the value is stored. Const

 pointer does not suppose to change the value once it assigned with the programme. If the pointer whose data type is constant is defined in a function, so this pointer has a scope within

function. It is also again a constant pointer.

 5. When should a type cast be used and when should it not be used?

Ans:

Type cast is used when the data type of the variable has to be changed in a particular expression

alone and not in the whole program. The value of the variable changes when the type cast is

used.

Example:

int x=6,y=4;

float a;

a= x/y;

printf(“%d\n”,a);

a=(float)x/y;

printf(%d”,a);

o/p:

1.0000000

1.5000000

A type cast should not be used to override a const or volatile declaration. Overriding these type

modifiers can cause the program to fail to run correctly. A type cast should not be used to turna pointer to one type of structure or data type into another 

 6. What is a pre-processor and what will it do for a program?

Ans:

Pre-processor as name implies process the source code before it passed to the compiler. It will

identify the directives present in the source code and convert it in to expanded source code. The

C preprocessor (cpp) is the preprocessor for the C and C++ computer programming languages.

Page 3: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 3/31

The preprocessor handles directives for source file inclusion (#include), macro definitions

(#define), and conditional inclusion (#if).

7. What is a heap?

Ans:

A heap is a specialized tree-based data structure that satisfies the heap property: if B is a child

node of A, then key(A) ≥ key(B). This implies that an element with the greatest key is always

in the root node, and so such a heap is sometimes called a max-heap. (Alternatively, if the

comparison is reversed, the smallest element is always in the root node, which results in a min-

heap.) The maximum number of children each node can have depends on the type of heap, but

in many types it is at most two. The heap is one maximally-efficient implementation of an

abstract data type called a priority queue. Heaps are crucial in several efficient graph

algorithms such as Dijkstra's algorithm, and in the sorting algorithm heap sort. A heap data

structure should not be confused with the heap which is a common name for dynamically

allocated memory.In dynamic memory allocation the memory is usually allocated from a large

 pool of unused memory called heap. It is also called as free store

8. Why does n++ execute much faster than n+1?

Ans:

All unary operators have a higher precedence than all binary arithmetic operators. Here ++ is a

unary operator and ‘+’ is a binary operator. Machine cycles required for the unary (INR) areless compared to binary operation (ADD).

9. What is the difference between "malloc" and "calloc"?

Ans:

malloc( ) take one argument and allocate bytes of memory where as calloc( ) take two

argument and allocate block of memory.

malloc( ) does not initialize the memory allocated, while calloc( ) initializes the

allocated memory to ZERO.

Syntax for calloc( ): ptr=(cast_type *)calloc(no_of_blocks , size_of_each_block);

Syntax for malloc( ): ptr=(cast_type *)malloc(Size_in_bytes);

10. How do we check whether a linked list is circular?

Ans:

Create two pointers ptr1 and ptr2.

Declare the pointer ptr1 to be pointing to the head node we start from.

Page 4: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 4/31

Declare pointer ptr2 inside a loop such that it points to the next node of the current

head.

 Now compare pointers ptr1 and ptr2 every time the ptr2 has been incremented.

In case the pointers ptr1 and ptr2 are equal, the linked list is circular; else the linked listis not circular.

11. Describe about storage allocation and scope of global, extern, static, local and register

variables?

Ans:

VARIABLE STORAGE ALLOCATION SCOPE

extern Memory is allocated when the

 program begins execution, and

remains allocated until the

 program terminates. Usually in

C, every byte of memory

allocated for an external variable

is initialized to zero

The scope of external variables

is global, i.e. the entire source

code in the file following the

declarations.

static The scope of static automatic

variables is identical to that of 

automatic variables, i.e. it is

local to the block in which it is

defined.

local Memory is allocated

automatically upon entry to a

 block and freed automatically

upon exit from the block.

The scope of local variables is

local to the block in which they

are declared, including any

 blocks nested within that block.

register Registers are memory located

within the CPU itself where data

can be stored and accessed

quickly. Normally, the compiler 

determines what data is to be

stored in the registers of the

CPU at what times.

 

12. Can we specify variable field width in a scanf() format string? If possible, how?

Yes, we can specify variable field width in a scanf() format string.

The format will be as : Scanf(“%nd”,&a); n=1,2,3,...

Page 5: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 5/31

For n=3, if the user enters a=1234567; the scanf () statement reads only first three digits of the

input and stores the value of ‘a’ to be a=123.

13. What are the advantages of using pointers in a program?

Ans:

Dynamic memory allocation is possible with pointers through which size of array can

 be allocated dynamically.

Passing arrays and structures to functions

Passing addresses to functions which in turn returns more than one variable

Creating data structures such as trees, linked lists etc

14. Can a Structure contain a Pointer to itself? Give an example

Ans:

Yes, a structure can contain a pointer to itself. so it is called as self referential structure. A self-

referential structure is one of the data structures which refer to the pointer to (points) to another 

structure of the same type.

Example:

typedef struct listnode

 {

void *data;

struct listnode *next;

} linked_list;

15. What is the difference between Structure and Union. Explain with an example.

Ans:

Syntax:

struct shop union shop

{ {

int pen; int pen;

char ink[10]; char ink[10];

Page 6: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 6/31

} }

Structure Union

Declared using the keyword struct Declared using the keyword union

Memory is allocated for both pen and ink Memory is allocated only for pen(ie. variable

which variable require more memory.

Both the variables can be initialized. Only first member (pen) can be initialized

 

16. What is the difference between the following two declarations? Explain

char a[];

char *a;

Ans:

char a[] is requests that some space for characters be set aside, to be known by the

name "a".

The pointer declaration "char *a;" on the other hand, requests a place which holds a

 pointer. The pointer is to be known by the name "a," and can point to any char anywhere.

 17. Why is not advisable to use ‘goto’.

Ans:

It is not advisable to use ‘goto’ because whenever it has been declared it requires the logic of 

the code to move frequently from point to point, often in an unstructured or unobvious way.

This will lead to a code that will be difficult to understand.

18. How can you determine the number of elements in an array, when sizeof yields the

size in bytes?

Ans:

The function sizeof() gives the size of the array in bytes. So, to determine the no of elements in

the array, the total size of the array is divided by the size of the individual array.

For example:

int a[10];

int n = sizeof(a) / sizeof(a[0]);

}

Page 7: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 7/31

19. What are enums, for which scenarios we will use them?

Ans:

Enumerated data type is used to create our own data type and define values for the

variables. You can use them to create sets of constants for use with variables and properties.

Makes it easy to change values in the future and reduces the error 

Enumerations make for clearer and more readable code, particularly when meaningful

names are used.

20. What are header (“#include”) files searched for?

Ans:

Header files search for the corresponding standard header files that are supplied with the C

compilation system. The angle brackets (< >) tell the pre-processor to search for the header file

in the standard place for header files on our system. Programmers who wish to declare

standardized identifiers in more than one source file can place such identifiers in a single

header file

21. When will I get the runtime error, “Segmentation fault”.

Ans:

Segmentation error occurs when one tries to use the memory which does not have any physical

location for the memory in the program. It is a type of memory violation.

for example:

int a[10]={1,2,3,4,5};

 printf(“%d”,a[25]);

22. Write a program to find the number of five hundreds, hundreds, fifties, twenties,

tens, fives, two’s and one’s in a amount given using while loop.

 23. A number is special if it is divisible (no remainder) by 15. A number is big if it is

greater than 999. A number is weird if it is divisible by 5 and 6 but not 18. A number is

scary if it is big or weird.

Write a program to check which of the following, 450, 540, 600, and 675 are special but

not scary.

Declare four variables called special, big, weird, and scary and make suitable assignments

to these variables as a number is tested.

Ans:

Page 8: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 8/31

#include<stdio.h>

#include<conio.h>

Void main()

{

#

24. Write a C program which converts the number in seconds to hour, minute and

seconds. If the number is less than 1000, the program should print the message “You

should enter an integer number greater than or equal to 1000”

Sample runs:

Enter the number of seconds> 7322

7322 seconds is equivalent to 2 hours 2 minutes 2 seconds.

Enter the number of seconds> 500

You should enter an integer number greater than or equal to 1000

Program:

#include<stdio.h>

#include<conio.h>

main()

{

int input,minutes,seconds,hrs;

printf("Enter the time in seconds");

scanf("%d",&input);

if(input>=1000)

{

hrs=input/3600;

minutes=((input % 3600)/60);

seconds=(input % 3600) % 60;

Page 9: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 9/31

printf("\nThe time in hrs minutes and seconds\n\n%d hrs %d minutes %d

seconds",hrs,minutes,seconds);

}

else

printf("You should enter an integer number greater than or equal to 1000");

getch();

}

Output:

Enter the time in seconds 6845

The time in hrs minutes and seconds

1 hrs 54 minutes 5 seconds

Enter the time in seconds 500

You should enter an integer number greater than or equal to 1000

25. Write a program to convert numeral to alphabets.

Program:

#include<stdio.h>

#include<conio.h>

void pw(long,char[]);

char *one[]={" "," one"," two"," three"," four"," five"," six"," seven","eight"," Nine"," ten","eleven"," twelve"," thirteen"," fourteen","fifteen","

sixteen"," seventeen"," eighteen"," nineteen"};

char *ten[]={" "," "," twenty"," thirty"," forty"," fifty"," sixty","seventy"," eighty"," ninety"};

void main()

{

long n;

Page 10: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 10/31

clrscr();

 printf("Enter any number(max upto 9 digits): ");

scanf("%9ld",&n);

if(n<=0)

 printf("Enter numbers greater than 0");

else

{

 pw((n/10000000),"crore");

 pw(((n/100000)%100),"lakh");

 pw(((n/1000)%100),"thousand");

 pw(((n/100)%10),"hundred");

 pw((n%100)," ");

}

getch();

}

void pw(long n,charch[])

{

(n>19)?printf("%s %s ",ten[n/10],one[n%10]):printf("%s ",one[n]);

if(n)printf("%s ",ch);

26. Write a program to remove the duplicate elements of the array.

27. Write a program to compare two strings entered by the user without help of strcmp()

function.

28. Write a program to determine the ranges of char, short, int, and long variables, both

signed and unsigned, by printing appropriate values from standard headers and by direct

computation. Harder if you compute them: determine the ranges of the various floating-

point types.

PROGRAM:

#include <stdio.h>

Page 11: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 11/31

#include<conio.h>

#include <limits.h>

void main ()

{

clrscr();

 printf("Size of Char %d\n", CHAR_BIT);

 printf("Size of Char Max %d\n", CHAR_MAX);

 printf("Size of Char Min %d\n", CHAR_MIN);

 printf("Size of int min %d\n", INT_MIN);

 printf("Size of int max %d\n", INT_MAX);

 printf("Size of long min %ld\n", LONG_MIN);

 printf("Size of long max %ld\n", LONG_MAX);

 printf("Size of short min %d\n", SHRT_MIN);

 printf("Size of short max %d\n", SHRT_MAX);

 printf("Size of unsigned char %u\n", UCHAR_MAX);

 printf("Size of unsigned long %lu\n", ULONG_MAX);

 printf("Size of unsigned int %u\n", UINT_MAX);

 printf("Size of unsigned short %u\n", USHRT_MAX);

getch();

}

29. While purchasing certain items, a discount of 10% is offered if the quantity

purchased is more than 1000. If quantity and price per item are input through the

keyboard, write a program to calculate the total expenses.

Program:

#include<stdio.h>

#include<conio.h>

main()

{

int no,i;

Page 12: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 12/31

float dis=0,total=0,input[10][10];

printf("Enter the number of products purchased");

scanf("%d",&no);

printf("Enter the quantity and price of each product");

for(i=0;i<no;i++)

{

scanf("%f%f",&input[i][0],&input[i][1]);

if(input[i][0]>=1000.0000)

dis=10;

else

dis=0;

total=total + (input[i][0]*input[i][1])-(input[i][0]*input[i][1]*dis/100);

}

printf("The total expense is %f \n Thankyou visit again ",total);

getch();

}

 

Output:

Enter the number of products purchased 2

Enter the quantity and price 2000 40.2

500 2

The total expense is 73360.00

Thankyou visit again

30. The current year and the year in which the employee joined the organization are

entered through the keyboard. If the number of years for which the employee has

served the organization is greater than 3 then a bonus of Rs.2500 /- is given to the

employee. If the years of service are not greater than 3, then the program should

not do anything.

Page 13: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 13/31

Program:

#include<stdio.h>

#include<conio.h>

main()

{

int cy,dy;

 printf(“Enter the the current year and joining year”);

scanf(“%d%d”,&cy,&dy);

if(cy-dy>=3)

 printf(“Hurray you have got a bonus of Rs.2500/-“);

getch();

}

Output:

Enter the the current year and joining year 

2012

2006

Hurray you have got a bonus of Rs.2500/-

Page 14: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 14/31

Java

1. Which part of Java is platform independent? Explain how Architecture neutral isachieved in Java.

Ans:

javac(java compiler) just compiles source code to byte code it doesn't matter on

which operating system it is running. But while running the class file (*.class) using jvm

(java *) it checks what is the operating system, processor, etc... And converts that into MLL

(machine level language instructions) this is why JVM is platform dependent and javac is

not.

2. Name some pure object oriented languages.

Ans:

Simula, SmallTalk, Eiffel

3. What is a class? What is the difference between a class and an object?

Ans:

Class is a blueprint/framework which has no physical existence and it is collection of 

similar properties and behaviour of objects. object is nothing which has physical existence,

own behaviour and properties. it is also known as instance of class.

A class is basically a definition, and contains the object's code. An object is an instanceof a class

Page 15: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 15/31

for example :

  String word = new String();

The class is the String class, which describes the object (instance) word. When a class isdeclared, no memory is allocated so class is just a template. When the object of the class is

declared, memory is allocated.

4. Does java support the concepts of multiple inheritance & pointers? If not why?

Ans:

Java doesn't support multiple inheritance because it may lead to confusion for a

 programmer and this is against to java language to be a simple (one of the features of OOP's).

When a class inherits from more than class, it will lead to the diamond problem - say A is the

super class of B and C & D is a subclass of both B and C. D inherits properties of A from twodifferent inheritance paths i.e. via both B & C. This leads to ambiguity and related problems,

so multiple inheritance is not allowed in Java.

Java does not support pointers (at least it does not allow you to modify the address

contained in a pointer or to perform pointer arithmetic). Because pointers are unsafe. Java

uses reference types to hide pointers and programmers feel easier to deal with reference types

without pointers.

5. What is the difference between Boolean & operator and the && operator?

Ans:

The bitwise AND operator ( & )

(Boolean expression1) & (Boolean expression2)

The bitwise AND operator (&) is to evaluate the above expression, Java first evaluates

 both Boolean expression1 and Boolean expression2.Hence only if both Boolean

expression1 and Boolean expression2 evaluate to true, the whole expression evaluates to

true.

. The conditional AND operator ( && )

  (Boolean expression1) && (Boolean expression2)

Here Java first evaluates Boolean expression1, only if it evaluates to true, Boolean

expression2 is evaluated. Hence Boolean expression2 is not evaluated if Boolean

expression1 evaluates to false.

The conditional AND operator, sometimes called the short-circuit operator is more

efficient that the bitwise AND operator. As it saves the processing of expression2 by

first evaluating expression1 and ascertaining that the final result will be false

6. What is the difference between >> and >>> operators?

Page 16: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 16/31

Ans:

The >>> operator is identical to the >> operator, except that the bits that fill in the

shifted left bits have the value of 0. The >>> operator is said to be an unsigned shift

 because it does not preserve the sign of 

the operand.

>> : operator once moves the bits towards right. It doesn't move the sign bit.

>>>: operator once moves the bits towards right, the sign bit also will gets moving.

While dealing with (+)ve numbers there is no difference between >>> and >> operators.

Both operators shift zeros into the upper bits of a number.

The difference arises when dealing with (-)ve numbers. Since (-)ve numbers,(-)ve numbers

have their high order bit set to 1.The >>> (Zero Fill Shift Operator) shifts zeros into all the

upper bits, INCLUDING THE HIGH ORDER BIT, Thus making the (-)ve number into a

(+)ve number.

7. What is a local member and a class variable?

Ans: Class variables are the variables declared with the static modifier as a field of a class. These

variables are created and initialized during the class loading itself and only one copy of 

such variables is shared among all the instances of the class. We normally use the name of 

the class to access such variables. class variables - declared inside class and not within any

method, available to all the methods inside the class.

Local variables are the variables declared locally inside a method definition or the variables

which are defined as the parameters of a method. The scope of such a variable is limited to

that method only. Local variables defined inside a method definition need to be initialized

explicitly otherwise the code will throw a compile-time error.

8. What are the different access modifiers available in Java?

Ans:

Private Access Modifier - private:

Methods, Variables and Constructors that are declared private can only be

accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces

cannot be private.

Variables that are declared private can be accessed outside the class if publicgetter methods are present in the class.

Page 17: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 17/31

Using the private modifier is the main way that an object encapsulates itself and

hide data from the outside world.

Public Access Modifier - public:

A class, method, constructor, interface etc declared public can be accessed from any

other class. Therefore fields, methods, blocks declared inside a public class can be

accessed from any class belonging to the Java Universe.

However if the public class we are trying to access is in a different package, then the

 public class still need to be imported.

Because of class inheritance, all public methods and variables of a class are inherited by

its subclasses.

 Protected Access Modifier - protected :

Variables, methods and constructors which are declared protected in a superclass can beaccessed only by the subclasses in other package or any class within the package of the

 protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields

can be declared protected, however methods and fields in a interface cannot be declared

 protected.

Protected access gives the subclass a chance to use the helper method or variable, while

 preventing a nonrelated class from trying to use it

9. What does it mean that a method or field is static?

Ans: 

Static variables and methods are instantiated only once per class. In other words they are

class variables, not instance variables. If you change the value of a static variable in a

 particular object, the value of that variable changes for all instances of that class.

Static methods can be referenced with the name of the class rather than the name of a

 particular object of the class (though that works too). That's how library methods like

System.out.println() work. out is a static field in the java.lang.System class.

10. Difference between JRE/JVM/JDK?

Ans:

JRE JVM JDK  

JRE or the Java

Runtime Environment is a

minimum set that

includes a Java

interpreter, Java API

libraries, Java browser 

 plug-in, which make up

the minimum

The JVM or Java

Virtual Machine is the core

of the Java platform and is

a part of both the JDK and

JRE that translates Java

 byte codes and executes

them as native code on the

client machine.JDK 

JDK or the Java Development

Kit is a set of a Java compiler, a

Java interpreter, developer tools,

Java API libraries, documentation

which can be used by Java

developers to develop Java-based

applications.

Page 18: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 18/31

environment to execute

Java-based applications.

includes a JRE as as subset.

JRE is also a

software bundle same as

JDK excluded withsome binary

files( especially compiler 

- javac and

rmic).Required to run

applications of production

environment ( on client

host system ).

JVM is available in

 both JDK and JRE.

Java.exe file is usedto initiate VM process.The

default heap size is 2MB

and the Max.heap size is

64MB.VM comes in two

flavours

JDK is a software bundle

consists of binary files such as

(javac,java,javadoc,jdb,javap,rmic....),java library files

(both old and new)and some

header files. Development

environment requires this software

For running java

 programs, JRE is

sufficient.

The JVM is called

"virtual" because it

 provides a machine

interface that does not

depend on the underlying

operating

system and machine

hardware architecture

You need JDK , if at all you

want to write your own programs,

and to compile them.

JRE stands for java

runtime environment

which provide thenecessary jar file that

compile source code into

 byte code. and it contain

 java virtual machine

JVM is the java virtual

machine which is used to

convert the byte code touser understandable code

JDK is the java development

kit contains the executable

files

11. What is a Null object?

Ans:

 Null is the reserved constant used in Java to represent a void reference i.e a pointer to

nothing. Internally it is just a binary 0, but in the high level Java language, it is a magic

constant, quite distinct from zero, that internally could have any representation.

12.Write a program that accepts empno, name, and basic and finds PF and HRA at

12% and 40% of basic respectively.

Program:

employee

import java.io.*;

Page 19: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 19/31

 public class employee {

 public static void main(String args[])throws IOException

{

int empno,basic;

float pf,hra;

String ename;

DataInputStream d=new DataInputStream(System.in);

System.out.println("Enter the employee number");

empno=Integer.parseInt(d.readLine());

System.out.println("Enter the employee name");

ename=d.readLine();

System.out.println("Enter the basic salary");

basic=Integer.parseInt(d.readLine());

pf= (int) (0.12 * basic);

hra=(int) (0.4 * basic);

System.out.println("the employee pf"+pf);

System.out.println("the employee hra"+hra);

}}

Output

Enter the employee number 

111

Enter the employee name

Saleem

Enter the basic salary

10000

the employee pf1200.0

the employee hra4000.0

Page 20: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 20/31

13. Write a program to accept marks in 4 subjects, find the average and display the

grades (F, C, B, A, S). average < 50 – F, average < 60 – C, average < 70 –B,

average < 85 – A, average > 85 –S

Program

import java.io.*;

 public class student

{

 public static void main(String args[])throws IOException

{

int sno,m1,m2,m3,m4,total,avg;

String sname;

DataInputStream d=new DataInputStream(System.in);

System.out.println("Enter the student number");

sno=Integer.parseInt(d.readLine());

System.out.println("Enter the student name");

sname=d.readLine();

System.out.println("Enter the mark1");

m1=Integer.parseInt(d.readLine());

System.out.println("Enter the mark2");

m2=Integer.parseInt(d.readLine());

System.out.println("Enter the mark3");

m3=Integer.parseInt(d.readLine());

System.out.println("Enter the mark4");

m4=Integer.parseInt(d.readLine());

total=m1+m2+m3+m4;

avg=total/4;

System.out.println("the total is"+total);

Page 21: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 21/31

System.out.println("average is"+avg);

 

else if(avg >= 51 && avg <= 60)

System.out.println("grade is C");

else if(avg >= 61 && avg <= 70)

System.out.println("grade is B");

else if(avg >= 71 && avg <= 85)

System.out.println("grade is A");

else if(avg > 86)

System.out.println("grade is S");

else

System.out.println("grade is Fail");

}

}

Output

Enter the student number 

1

Enter the student name

Gayathri

Enter the mark1

50

Enter the mark2

85

Enter the mark3

86

Enter the mark4

Page 22: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 22/31

40

the total is 261

average is 65

grade is B

14. Write a program to accept a number and find whether it is a prime or not.

Program

import java.io.*;

 public class prime

{

public static void main(String[] args)throws IOException

{

int i,num;

DataInputStream d=new DataInputStream(System.in);

System.out.println("Enter the number");

num=Integer.parseInt(d.readLine());

for (i=2; i < num ;i++ ){

int n = num%i;

if (n==0){

System.out.println("The number is not Prime!");

break;

}

}

Page 23: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 23/31

if(i == num){

System.out.println("The number Prime number!");

}

}

}

Output

Enter the number 

17

The number Prime number!

81

The number is not Prime! .

15. Write a program to echo the arguments given in the command line.

16. Write a function that takes a string as argument and displays it vertically char by

char. Traverse the array by incrementing a pointer.

PROGRAM

import java.io.*;

 public class stringfunction

{

 public static void message(String mess)throws IOException

{

System.out.println(mess);

int i;

char a[]=new char[20];

for(i=0;i<mess.length();i++)

{

a[i]=mess.charAt(i);

Page 24: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 24/31

 

}

System.out.println("the Result is:");

for(i=0;i<mess.length();i++)

{

System.out.println(a[i]);

 

}

}

public static void main(String[] agrs)throws IOException

{

message("ApTech");

 

}

}

Output:

ApTech

the Result is:

a

P

t

E

C

H

Page 25: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 25/31

17. Write a program that accepts 10 nos in an array and search for an inputed

number in it.

Program

import java.io.*;

 public class numbersearch

{

public static void main(String args[])throws IOException

{

int i,search;

DataInputStream d=new DataInputStream(System.in);

int a[]=new int[10];

System.out.println("enter the values:");

for(i=0;i<10;i++)

{

a[i]=Integer.parseInt(d.readLine());

}

System.out.println("enter the number you need to search:");

search=Integer.parseInt(d.readLine());

for(i=0;i<10;i++)

{

if(a[i]==search)

{

System.out.println("the number is"+search+"in the"+i+"position of array");

}

}

 

}

Page 26: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 26/31

}

Output

enter the values:

2

4

6

8

10

12

enter the number you need to search:

8

the number is 8 in the 3 position of array

18. Write a program that gets input from user asking how many nos he/she would like

to enter. Accept the numbers in any array and sort them in ascending order.

Program

import java.io.*;

 public class sort1

{

public static void main(String args[])throws IOException

{

int i,temp,j,k,num;

DataInputStream d=new DataInputStream(System.in);

int a[]=new int[50];

System.out.println("how many number you like to enter");

num=Integer.parseInt(d.readLine());

System.out.println("enter the values:");

Page 27: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 27/31

for(i=0;i<num;i++)

{

a[i]=Integer.parseInt(d.readLine());

}

for(j=0;j<num;j++)

for(k=num-1;k>j;k--)

if(a[j]>a[k])

{

temp=a[j];

a[j]=a[k];

a[k]=temp;

}

System.out.println("The sorted Order is:");

for(i=0;i<num;i++)

{

System.out.println(a[i]);

}

}}

OUTPUT

how many number you like to enter 

5

enter the values:

58

27

38

Page 28: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 28/31

35

30

The sorted Order is:

28

30

35

38

58

19. Write a program that accepts a string and find no characters in it, without using

any standard library functions

PROGRAM:

import java.io.*;

classelem

{

 public static void main(String args[])

{

int i=0;

StringBuffer string = new StringBuffer();

char c;

System.out.println("Enter the String:");

try

{

while((c=(char)System.in.read())!='\n')

{

i++;

}

Page 29: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 29/31

System.out.println("The String Length is:" + (i-1));

}

catch(IOException e)

{

System.out.println("Error!");

}

}}

Output:

Enter the String:

Computer 

The String Length is 8

20.Write a class for Employee. Variables contained in the class are id, name and

department. Create 10 objects for Employee class and store them in the array.

While creating the object, values for the variables are obtained as input from the user.

Iterate the array and print the details of the employee.

PROGRAM:

import java.io.*;

importjava.lang.*;

class employee

{

intempid;

String empname,dept;

Page 30: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 30/31

employee()

{}

voidsetdata(intno,Stringname,Stringdep)

{

empid = no;

empname=name;

dept=dep;

}

voidprintdata()

{

System.out.println("Employee Number: " + empid);

System.out.println("Employee Name: " + empname);

System.out.println("Employee Department: " + dept);

}}

classemp

{

 public static void main(String[] args)

{

employee[] emparray= new employee[10];

for(int i=0;i<10;i++)

emparray[i] = new employee();

try

{

for(int i=0;i<10;i++)

{

System.out.println("Enter the details of employee" +(i+1)+":");

Page 31: assign1 ans

8/2/2019 assign1 ans

http://slidepdf.com/reader/full/assign1-ans 31/31

InputStreamReaderinp = new InputStreamReader(System.in) ;

BufferedReaderbufRead = new BufferedReader(inp);

System.out.println("Enter the employee number of the employee:");

String empid = bufRead.readLine();

intempno=Integer.parseInt(empid);

System.out.println("Enter the name of the employee:");

String empname = bufRead.readLine();

System.out.println("Enter the department of the employee:");

String dept = bufRead.readLine();

emparray[i].setdata(empno,empname,dept);

}

for(int j=0;j<10;j++)

{

System.out.println("Employee"+(j+1)+":");

emparray[j].printdata();

}}

catch(IOException e)

{

System.out.println("Error");

}}}