Solutions for All CSE Students

Think Globally
&
Search Locally

Blog

Solutions For All CSE / IT & MCA Students

view:  full / summary

OOPS JAVA Interview q's paper-2

Posted on October 18, 2014 at 3:50 AM Comments comments (0)

Oops interview questions - posted on June 27, 2013 at 16:05 PM by Kshipra Singh

1. What are the basic concepts of OOP?

The four basic concepts of OOP are:

a.) Abstraction

b.) Polymorphism

c.) Inheritance

d.) Encapsulation

2. What is dynamic or run time polymorphism?

- It is also referred to as method overriding. Here, there can be two methods with same name and signature but different implementation.

- The function here is resolved during run time rather than compile time.

3. What is Encapsulation?

- It is a technique to hide the properties and behaviours of an object.

- The access is provided only as required.

- It prevents other objects from altering or accessing the properties of an encapsulated object.

4. Differentiate between abstraction and encapsulation.

- Abstraction is design oriented while abstraction is implementation oriented.

- The focus of abstraction is on the interface i.e. the outside view of the object while encapsulation prevents other objects or methods from looking into the properties and behaviour of that object.

5. What is Inheritance?

- It is the process which allows the objects of one class to acquire the properties of objects of another class.

- The class that inherits is called sub-class while the class from which the object is inherited is called superclass.

- Inheritance helps in re-using the code and polymorphism.

6. Explain method overriding.

- When a subclass declares a method possessing similar arguments as a method declared by one of its superclass, method overriding takes place.

- Using this technique, the behaviour specific to a particular subclass can be defined.

- The methods marked public, final or static can not be overridden

7. Can you give some examples of tokens?

Some of the examples of tokens are:

- Keywords,

- Identifiers,

- Constants,

- Operators,

- Brackets,

- Commas.

8. What is friend function?

- Friend function is a friend of a class.

- It is allowed to access Public, private or protected data of that class.

- It can be declared anywhere in the class declaration

- It doesn’t have any effect of access control keywords like private, public or protected.

9. Define Modularity?

- It is the property of big a system divided into small modules which can be integrated as per the requirement.

10. Explain: a.) Persistence. b.) Colloboration

a.) Persistence.

- It is the property of an object which extends its existence into space and time.

b.) Colloboration

- Process by which several objects co-operate to deliver a higher level result.

11. What is a ternary operator?

- It is also called as a conditional operator.

- It is an operator that can take three arguments.

- The data types of arguments and results are different.

12. What are sealed modifiers?

- Access modifiers which cannot be inherited by other methods.

- They can be applied to properties, events and methods but not to static members.

13. Explain: a.) Static binding b.) Dynamic binding

a.) Static binding-

It is a binding in which the name of the class can be associated with it during compilation. Also referred to as early binding.

b.) Dynamic binding –

It is a binding in which the name of the class can be associated with it during execution time. Also referred to as late binding.

14. What are the different ways for a method to be overloaded?

A method can be overloaded by:

- Varying the numbers of parameters

- Using different data types for the parameters

- Using different sequence of the parameters.

What is OOP?

The object oriented programming is commonly known as OOP. Most of the languages are developed using OOP concept. Object-oriented programming (OOP) is a programming concept that uses "objects" to develop a system...................

Read answer

OOAD interview test (50 questions)

Oops interview test (20 questions)

What are the various elements of OOP?

Various elements of OOP are: Object, Class , Method

Class – A class is a collection of data and operations on data. Data and operations / functions / methods are placed together in a single unit, i.e., class. This feature is known as encapsulation................

Read answer

What are the characteristics of Object Oriented programming language?

Some key features of the Object Oriented programming are: Emphasis on data rather than procedure, Programs are divided into entities known as objects, Data Structures are designed such that they characterize objects...............

Read answer

What are the basic Concepts used in the Object-Oriented Programming language?

Object, Class, Data Abstraction and Encapsulation, Polymorphism..................

Read answer

Explain an object, class and Method.

An object is an entity that keeps together state and behaviors. For instance, a car encapsulates state such as red color, 900 cc etc and behaviors as 'Start', 'Stop' etc., so does an object.................

Read answer

Define Encapsulation and Information Hiding in OOP.

Encapsulation means keeping actions and attributes together under a single unit. This can also be understood using a motor bike example.............

Read answer

Explain Inheritance and Polymorphism in OOP.

Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances..............

Read answer

What are the advantages of OOP?

It presents a simple, clear and easy to maintain structure. It enhances program modularity since each object exists independently...................

Read answer

Oops - Jan 12, 2009 at 21:14 PM by Vidya Sagar

What is composition? Explain the purpose of composition.

Assembling existing components instead of creating new ones is called composition. In OOP it is called as objects composition. It is the process of placing object in another object. It is the model of has-a relationship. An employee object can contain an object of type project which is another object.

Purpose of com

OOPS JAVA Interview q's paper-1 For IV CSE (50Q's)

Posted on October 18, 2014 at 3:50 AM Comments comments (0)

1. What is OOPS?

OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

2. Write basic concepts of OOPS?

Following are the concepts of OOPS and are as follows:.

Abstraction.

Encapsulation.

Inheritance.

Polymorphism.

3. What is a class?

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object.

4. What is an object?

Object is termed as an instance of a class, and it has its own state, behavior and identity.

5. What is Encapsulation?

Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data can be restricted to the members of that class.

Levels are Public,Protected, Private, Internal and Protected Internal.

Also Read: Top 50 Common Job Interview Questions and answers

6. What is Polymorphism?

Polymorphism is nothing butassigning behavior or value in a subclass to something that was already declared in the main class. Simply, polymorphism takes more than one form.

7. What is Inheritance?

Inheritance is a concept where one class shares the structure and behavior defined in another class. Ifinheritance applied on one class is called Single Inheritance, and if it depends on multiple classes, then it is called multiple Inheritance.

8. What are manipulators?

Manipulators are the functions which can be used in conjunction with the insertion (<<) and extraction (>>) operators on an object. Examples are endl and setw.

9. Define a constructor?

Constructor is a method used to initialize the state of an object, and it gets invoked at the time of object creation.

Rules forconstructor are:.

Constructor Name should be same asclass name.

Constructor must have no return type.

10. Define Destructor?

Destructor is a method which is automatically called when the object ismade ofscope or destroyed. Destructor name is also same asclass name but with the tilde symbol before the name.

Also Read: PHP Interview Questions and Answers for freshers

11. What is Inline function?

Inline function is a technique used by the compilers and instructs to insert complete body of the function wherever that function is used in the program source code.

12. What is avirtual function?

Virtual function is a member function ofclass and its functionality can be overridden in its derived class. This function can be implemented by using a keyword called virtual, and it can be given during function declaration.

Virtual function can be achieved in C++, and it can be achieved in C Languageby using function pointers or pointers to function.

13. What isfriend function?

Friend function is a friend of a class that is allowed to access to Public, private or protected data in that same class. If the function is defined outside the class cannot access such information.

Friend can be declared anywhere in the class declaration, and it cannot be affected by access control keywords like private, public or protected.

14. What is function overloading?

Function overloading is defined as a normal function, but it has the ability to perform different tasks. It allowscreation of several methods with the same name which differ from each other by type of input and output of the function.

Example:

void add(int& a, int& b);

void add(double& a, double& b);

void add(struct bob& a, struct bob& b);

15. What is operator overloading?

Operator overloading is a function where different operators are applied and depends on the arguments. Operator,-,* can be used to pass through the function , and it has their own precedence to execute.

Example:

class complex {

double real, imag;

public:

complex(double r, double i) :

real(r), imag(i) {}

complex operator+(complex a, complex b);

complex operator*(complex a, complex b);

complex& operator=(complex a, complex b);

}

a=1.2, b=6

Also Read: Top JavaScript Interview Questions and Answers

16. What is an abstract class?

An abstract class is a class which cannot be instantiated. Creation of an object is not possible withabstract class , but it can be inherited. An abstract class can be contain members, methods and also Abstract method.

A method that is declared as abstract and does not have implementation is known as abstract method.

Syntax:

abstract void show(); //no body and abstract keyword

17. What is a ternary operator?

Ternary operator is said to be an operator which takes three arguments. Arguments and results are of different data types , and it is depends on the function. Ternary operator is also called asconditional operator.

18. What is the use of finalize method?

Finalize method helps to perform cleanup operations on the resources which are not currently used. Finalize method is protected , and it is accessible only through this class or by a derived class.

19. What are different types of arguments?

A parameter is a variable used during the declaration of the function or subroutine and arguments are passed to the function , and it should match with the parameter defined. There are two types of Arguments.

Call by Value – Value passed will get modified only inside the function , and it returns the same value whatever it is passed it into the function.

Call by Reference – Value passed will get modified in both inside and outside the functions and it returns the same or different value.

20. What is super keyword?

Super keyword is used to invoke overridden method which overrides one of its superclass methods. This keyword allows to access overridden methods and also to access hidden members of the superclass.

It also forwards a call from a constructor to a constructor in the superclass.

Also Read: Top 20 JSP Interview Questions and Answers

21. What is method overriding?

Method overriding is a feature that allows sub class to provide implementation of a method that is already defined in the main class. This will overrides the implementation in the superclass by providing the same method name, same parameter and same return type.

22. What is an interface?

An interface is a collection of abstract method. If the class implements an inheritance, and then thereby inherits all the abstract methods of an interface.

23. What is exception handling?

Exception is an event that occurs during the execution of a program. Exceptions can be of any type – Run time exception, Error exceptions. Those exceptions are handled properly through exception handling mechanism like try, catch and throw keywords.

24. What are tokens?

Token is recognized by a compiler and it cannot be broken down into component elements. Keywords, identifiers, constants, string literals and operators are examples of tokens.

Even punctuation characters are also considered as tokens – Brackets, Commas, Braces and Parentheses.

25. Difference between overloading and overriding?

Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the same method with different arguments , and it may or may not return the same value in the same class itself.

Overriding is the same method names with same arguments and return types associates with the class and its child class.

Also Read: Android Interview Ques & Ans for Fresher

26. Difference between class and an object?

An object is an instance of a class. Objects hold any information , but classes don’t have any information. Definition of properties and functions can be done at class and can be used by the object.

Class can have sub-classes, and an object doesn’t have sub-objects.

27. What is an abstraction?

Abstraction is a good feature of OOPS , and it shows only the necessary details to the client of an object. Means, it shows only necessary details for an object, not the inner details of an object. Example – When you want to switch On television, it not necessary to show all the functions of TV. Whatever is required to switch on TV will be showed by using abstract class.

28. What are access modifiers?

Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are 5 types of access modifiers , and they are as follows:.

Private.

Protected.

Public.

Friend.

Protected Friend.

29. What is sealed modifiers?

Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers can also be applied to properties, events and methods. This modifier cannot be applied to static members.

30. How can we call the base method without creating an instance?

Yes, it is possible to call the base method without creating an instance. And that method should be,.

Static method.

Doing inheritance from that class.-Use Base Keyword from derived class.

Also Read: Top Ruby Language Interview Questions and Answers

31. What is the difference between new and override?

The new modifier instructs the compiler to use the new implementation instead of the base class function. Whereas, Override modifier helps to override the base class function.

32. What are the various types of constructors?

There are three various types of constructors , and they are as follows:.

- Default Constructor – With no parameters.

- Parametric Constructor – With Parameters. Create a new instance of a class and also passing arguments simultaneously.

- Copy Constructor – Which creates a new object as a copy of an existing object.

33. What is early and late binding?

Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.

34. What is ‘this’ pointer?

THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which differentiates between the current object with the global object. Basically, it refers to the current object.

35. What is the difference between structure and a class?

Structure default access type is public , but class access type is private. A structure is used for grouping data whereas class can be used for grouping data and methods.

Structures are exclusively used for dataand it doesn’t require strict validation , but classes are used to encapsulates and inherit data which requires strict validation.

Also Read: Top 50 C# Language Interview Questions and Answers

36. What is the default access modifier in a class?

The default access modifier of a class is Private by default.

37. What is pure virtual function?

A pure virtual function is a function which can be overridden in the derived classbut cannot be defined. A virtual function can be declared as Pure by using the operator =0.

Example -.

Virtual void function1() // Virtual, Not pure

Virtual void function2() = 0 //Pure virtual

38. What are all the operators that cannot be overloaded?

Following are the operators that cannot be overloaded -.

Scope Resolution (:: )

Member Selection (.)

Member selection through a pointer to function (.*)

39. What is dynamic or run time polymorphism?

Dynamic or Run time polymorphism is also known as method overriding in which call to an overridden function is resolved during run time, not at the compile time. It means having two or more methods with the same name,same signature but with different implementation.

40. Do we require parameter for constructors?

No, we do not require parameter for constructors.

Also Read: Top C Interview Questions and Answers

41. What is a copy constructor?

This is a special constructor for creating a new object as a copy of an existing object. There will be always only on copy constructor that can be either defined by the user or the system.

42. What does the keyword virtual represented in the method definition?

It means, we can override the method.

43. Whether static method can use non static members?

False.

44. What arebase class, sub class and super class?

Base class is the most generalized class , and it is said to be a root class.

Sub class is a class that inherits from one or more base classes.

Super class is the parent class from which another class inherits.

45. What is static and dynamic binding?

Binding is nothing but the association of a name with the class. Static binding is a binding in which name can be associated with the class during compilation time , and it is also called as early Binding.

Dynamic binding is a binding in which name can be associated with the class during execution time , and it is also called as Late Binding.

Also Read: OOPs Interview Questions and Answers for Fresher

46. How many instances can be created for an abstract class?

Zero instances will be created for an abstract class.

47. Which keyword can be used for overloading?

Operator keyword is used for overloading.

48. What is the default access specifier in a class definition?

Private access specifier is used in a class definition.

49. Which OOPS concept is used as reuse mechanism?

Inheritance is the OOPS concept that can be used as reuse mechanism.

50. Which OOPS concept exposes only necessary information to the calling functions?

Data Hiding / Abstraction

Finding object size in java

Posted on September 13, 2014 at 6:05 AM Comments comments (0)

import java.io.*;

import java.awt.*;

 

class AB

{

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

{

Frame f=new Frame("Finding object size");

ByteArrayOutputStream bOut = new ByteArrayOutputStream();

ObjectOutputStream oOut = new ObjectOutputStream(bOut);

String jedi = "Anakin";

oOut.writeObject(f);

 

oOut.close();

System.out.println("The size of the object is: "+bOut.toByteArray().length);

ByteArrayInputStream bIn = new ByteArrayInputStream();

ObjectInputStream oIn = new ObjectInputStream(bIn);

}

}

Java native Example

Posted on August 20, 2014 at 7:00 AM Comments comments (0)

What is native keyword - Use of native keyword in Java

 

The native modifier indicates that a method is implemented in platform-dependent code, often in C.

native is a modifier (thus a reserved keyword) and that native can be applied only to methods—not classes, not variables, just methods.

Note that a native method's body must be a semicolon (;) (like abstract methods), indicating that the implementation is omitted.

Use of native methods in Java

 

Although it is rare, occasionally you may want to call a subroutine that is written in a language other than Java.

Typically, such a subroutine exists as executable code for the CPU and environment in which you are working—that is, native code.

For example,

 

You may want to call a native code subroutine to achieve faster execution time.

Or, you may want to use a specialized, third-party library, such as a statistical package.

Java provides the native keyword, which is used to declare native code methods.

Once declared, these methods can be called from inside your Java program just as you call any other Java method.

To declare a native method, precede the method with the native modifier, but do not define any body for the method.

For example:

public native int meth() ;

After you declare a native method, you must write the native method and follow a rather complex series of steps to link it with your Java code.

Most native methods are written in C. The mechanism used to integrate C code with a Java program is called the Java Native Interface (JNI).

A detailed description of the JNI is beyond the scope of this tutorial, but the following description provides sufficient information for most applications.

The easiest way to understand the process is to work through an example. To begin, enter the following short program, which uses a native method called test():

 

// A simple example that uses a native method.

public class NativeDemo {

 

int i;

 

public static void main(String args[]) {

NativeDemo ob = new NativeDemo();

ob.i = 10;

 

System.out.println("This is ob.i before the native method:" + ob.i);

ob.test(); // call a native method

System.out.println("This is ob.i after the native method:" + ob.i);

}

 

// declare native method

public native void test();

 

// load DLL that contains static method

static {

System.loadLibrary("NativeDemo");

}

}

strictfp new key-word of java-2

Posted on August 20, 2014 at 6:35 AM Comments comments (0)

 

The strictfp keyword is used to force the precision of floating point calculations (float or double) in Java conform to IEEE’s 754 standard, explicitly. Without using strictfp keyword, the floating point precision depends on target platform’s hardware, i.e. CPU’s floating point processing capability. In other words, using strictfp ensures result of floating point computations is always same on all platforms.

 

The strictfp keyword can be applied for classes, interfaces and methods.

strictfp class  StrictFPClass {

double num1 = 10e+102;

double num2 = 6e+08;

double calculate() {

return num1 + num2;

}

}




Atomic Elements n Keywords of java

Posted on August 20, 2014 at 6:30 AM Comments comments (0)

THE ATOMIC ELEMENTS OF JAVA (Lexicals or Tokens):)

1.WHITESPACES Java is a free form language. This means that you need not have to follow any indentation rules. That is we can write the program all on one line or in any strange way as we like as long as there is atleast one whitespace character between each token that was not already delineated by an operator or separator. In java a whitespace may be a space,tab or newline.

2.IDENTIFIERS Identifiers are used for class names, method names, and variable names. An identifier may be any descriptive sequence of uppercase or lower case letters or the underscore and dollar sign characters. They must not begin with a number .Also java is case sensitive so ‘PRICE’ is a different identifier than ‘price’. Examples of valid identifiers are count,price,AvgPrice,a3,$sample ……Some invalid identifiers are 2price,high-value etc.

3.LITERALS A constant value in java is created by using literal representation of it.Following are examples of some literals. 200-integer literal 98.4-floating point value. ’x’-A character constant. “this is a sample”-A string. A literal cn be used anywhere a value of this type is allowed.

4.COMMENTS. There are three types of comments defined by java. We are familiar with the single line and multiline comments. The third type is called documentation comment. This comment is used to produce an HTML file that documents our program. The documentation comment begins with /** and ends with */.

5.SEPARATORS. Some characters are used as separators in java. The most commonly used separator in java is the semicolon(;).Separators are given in the following table. SYMBOL NAME PURPOSE () Paranthesis Used to contain a list of parameters in method definition and invocation. {} Braces Used to contain the values of automatically initialized arrays .Also used to define a block of code, for classes methods and local scopes. [] Brackets Used to declare array types. Also used when dereferencing array values ; Semicolon Terminates the statements. , Comma Separate consecutive identifiers in a variable declaration. Also used to chain statements inside a for statement. . Period Used to separate package names from sub packages and classes. Also used to separate a variable or method from a reference variable.

6.KEYWORDS Java language defines 49 reserved keywords. These keywords combined with the syntax of the operators and separators form the definition of the java language.These keywords cannot be used as the names for variables,classes or methods.The following table shows the java reserved keywords.In addition to the java keywords, java reserves ‘true’,;false’ and ‘null’. JAVA RESERVED KEYWORDS abstract continue goto package synchronized assert default if private this boolean do implements protected throw break double import public throws byte else istanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch

TT - GRAND TEST for ECE-1 RISE PRAKASAM

Posted on August 2, 2014 at 7:05 AM Comments comments (0)

:roll:

GRAND TEST : RVS

 

1.#include

int main(){

int no[2][2]={{0},{1,2}};

clrscr();

printf(‘%d’,no[0][0]);

}

a)0 b)nothing c)error d)1

 

2.#include

int main()

{

int no[][3]={{0},{1,{2},3}};

clrscr();

printf("%d",no[0][0]);

}

a)error b)nothing c)0 d)3

3.#include

int main()

{

int i=10;

int no[2][4]={1,0,2};

clrscr();

printf("%d",sizeof(no));

 

}

a)6 b)8 c)2 d)16

4.#include

int main()

{

int i=-1;

int no[3][3]={{1,2,3},{4,5,6},{7,8,9}};

clrscr();

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

printf("%d,",0[no[i]]);

 

}a)1,2,3 b)1,5,9 c)1,4,7 d)

5.#include

int main()

{

int i=-1;

int no[3][3]={{1,2,3},{4,5,6},{7,8,9}};

clrscr();

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

printf("%d,",1[0[no]]);

}

a)2,2,2 b)4,5,6 c)5,5,5 d)4,4,4

6.

main(){

char*str=”I love java”;

str=str+3;

printf(“%s”,str);

}

a.i love java b)error c)ove java d)ve java

7.

main(){

char*s[3]={”I love java”,”C++”,”MySQL”};

char**str;

str[0]=s[0];

printf(“%s”,s[0]);

}

a)error b)i love java c)I d)null

8.void main()

{

char *s="\123\n";

printf("%d",sizeof(s));

}

a)4 b)2 c)6 d)error

9.void main()

{

int i;

clrscr();

for(i=1;i<4;i++)

switch(i)

{

switch(i+1)

case 1: printf("%d",i);break;

{

case 2:printf("%d",i);break;

case 3:printf("%d",i);break;

}

switch(i);

}

}

a)23 b)error c)123 d)234

10.

struct student

{

Intsno;

Float fee;

floatwt;

}

main()

{

Structstudent s={100,2000.50};

Printf(“\n%d\t%f\t%f”,s.sno,s.fee,s.wt);

}

a)error b)100 2000.50 0.000000 c)100 2000.50 d)none

11.

union un

{

int no;

char name[20];

};

main()

{

Union un u;

u.no=100;

strcpy(u.name,”xxxx”);

printf(“%d%s”,u.no,u.name);

}

a)100 xxxx b)100 garbage c)error

d)garbage xxxx

12.

Intsquare(int x)

{

return x*x;

}

Which function pointer points statement is correct to point above function.

a) Int (*fptr)(int) b)int (fptr*)

c)int (fptr)(int*) e)none

13.

typedef char names[20];

which statement is correct

a) Typedef names n; b)names n

c)names:n d)none

 

14.

update(int*p)

{

*p+=10;

}

main()

{

Int x=10;

update(&x);

printf(“%d”,x);

}

a)10 b)ref error c)20 d)20

15.

struct test

{

Int x;

Int y;

};

 

main()

{

struct test t[2];

test[0].x=test[0].y=10;

test[1]=test[0];

printf(“%d\t%d”,test[1].x,test[1].y);

}

a)error b)10 10 c)garbage values d)none

 

16. max2(inta,intb,charch)

{

If(ch==’b’)

return a>b?b:a;

return (int)ch;

}

main()

{

Printf(“%d”,max2(10,20,’a’))

}

a)10 b)20 c)a d)97

17. enum color{RED,GREEN=3,BLUE};

main()

{

struct bfield

{

unsigned type:3;

};

 

struct bfield b;

b.type=BLUE;

printf("\n%d",b.type);

}a)4 b)3 c)5 d)error

 

18.# include

main()

{ char*str="i love java";

char*s;

while(s!=NULL)

{

s=strtok(str," ");

str=str+strlen(s)+1;

puts(s);

}

}

a)i love java b)error

c)i d)i

love

java

19.

# include

main()

{

char*str="C_lang";

printf("\n%s",strchr(str,'l'));

}

a)C_ b)l c)lang d)none

20.

# include

main()

{

char*str="C_lang";

printf("\n%s",memset(str,'x',4));

}

a)ng b)xxxxng c)0000ng d)x0ffng

21. struct a

{ struct b

{

int x;

}B;

int x;

};

main()

{

struct a A={100};

A.B.x=A.x=10;

a.x=111;

printf("\n%d",A.B.x);

}

a)100 b)10 c)error d)111

22.

main()

{

const int y=111;

int*x;

x=y;

printf("%d ",*x);

x=&y;

*x+=1;

printf("%d",*x);

}

a)111 112 b)address 112 c)error d)none

23.

main()

{

struct a

{ int x,y;

}z={10,20};

fun1(z);

}

fun1(struct a B)

{

B.x=100;

printf("%d",B.x);

}

a)100 b)10 c)error d)none

24.

main()

{

char *s[]={"ongole","chennaai","ooty"};

printf("\n%d",*(*(s+2)+1));

}

a)c b)99 c)error d)111

25.

main()

{

char *s1="c";

char*s2="c++";

clrscr();

printf("%c",*s1+*s2-76);

}

a)y b)z c)error d)z

 

 

 

 

 

 

 

 

 

 

 

 

 

 



TT - 3 for ECE-1 RISE PRAKASAM

Posted on August 2, 2014 at 7:05 AM Comments comments (0)

1.#include

int main(){

int i,j;

i=j=(2,3),0;

while(--i&&j++)

printf(" %d %d",i,j);

return 0;

}

a)1 3 b)none c)13 02 d)24 25

 

2. int main()

{

int i=1,n;

clrscr();

for(i=0,n=0;i<=5;n+=i++);

printf("%d",n);

}

 

a)25 b)21 c)garbage d)15

 

3.

# include

main()

{

if('\n');

else if(NULL)

printf("RISE");

else;

}

a)Misplaced else error b)nothing

c)RISE d)if can’t end error

 

4. int main()

{

int i,no[5]={{0},2,{0}};

clrscr();

for(i=0;i<=4;no[i]=i++)

printf("%d ",no[i]);

 

}

a.0 1 2 3 4 b. 0 3 2 3

c.0 2 0 0 0 d.1 2 3 4 5

5.int main()

{

char c=125;

do

printf("%d ",c);

while(c++);

return 0;

}

a) finate loop prints 125,126,127,….0

b)infinite loop c)compilation error d) finite loop prints 125,126,127,128,129…

 

6. #include

int main()

{

int i=10;

int no[2][4]={1,0,2};

printf("%d",sizeof(no));

 

}

a)6 b)8 c)2 d)16

 

7. main(){

char*str=”I love java”;

str=str+3;

printf(“%s”,str);

}

a.i love java b)error c)ove java d)ve java

8.

void main()

{

char *s="\123\n";

printf("%d",sizeof(s));

}

a)4 b)2 c)6 d)error

9. main()

{

char *str="ECETT";

clrscr();

printf("%s %s %c ",str+1,str,*str++);

}

a)ETT CETT E b)ECE TT T c)error d)CET CETT C

10. main()

{

char a[]="%d\n";

clrscr();

a[1]='c';

printf(a,68);

getch();

}

a)error b)D c)c d)D with new line

11.

main()

{

printf(“%d”,10?0?5:1:12)

}

a) 1 b)12 c)12 d)0

 

12. void main()

{

int a=3;

clrscr();

if(a==1);

a=2<<1;

printf("%d",a,a=~a);

}

 

a. 4

b. nothing

c. -5

d. 1

13. main(){

char*s[3]={”I love java”,”C++”,”MySQL”};

char**str;

str[0]=s[0];

printf(“%s”,s[0]);

}

a)error b)i love java c)I d)null

14. #include

main()

{

char not=!EOF;

clrscr();

printf("\n%d %d",EOF,not);

}

a. 0 0 b.error c.-1 0 d.-1 1

15.

# include

main()

{

char not='\0';

int i;

i=not==NULL;

clrscr();

printf("%d",i);

}

a.48 b.compile time error

c.0 d.1

 

 

16.What will be output of following c code?

#include

int main(){

int i=3,j=2;

clrscr();

while(i--?--j:j++)

printf("%d",j);

return 0;

}

 

a.-1 b)0 1 c)0 d)1

 

17.

dis()

{

no++;

}

main()

{

dis();

printf(“%d”,no);

++no;

}

int no=100;

a)100 b)101 c)error d)102

 

 

 

18.

int main()

{

int i=4;

clrscr();

 

do{

printf("%d ",--i,i=1);

 

} while(5,4,3,2,1,i);

 

return 0;

 

 

}

 

a)4 3 2 1 b)0 c)error e)none

 

19.

# include

main ()

{

int no=10000;

clrscr();

while (printf("%d",no, no/=10)-1);

 

}

 

a) 1001001001 b)100101

 

c) indefinateloop d) 1000100101

 

20.

# include

main()

{

int i=1;

clrscr();

while(i<=4?i++:0 )

printf("%d ",i);

}

a)2 3 4 5 b)3 4 5 c) 1 2 3 4 5 d)error

 

 

TT paper 2 by rvs

Posted on July 15, 2014 at 1:40 AM Comments comments (0)

1#include<stdio.h>

void main()

{

clrscr();

if((2==2) && printf("0") || 0)

printf("true");

else

printf("false");

}

a)true b)0true c)false d)0

----------------------------------------------------------

2.#include<stdio.h>

void main()

{

int ch='\0';

clrscr();

ch++;

while(1 && ch)

printf("%d",ch--);

}

a)NULL b)0 c)1  d)infinate loop

----------------------------------------------------------

3.#include<stdio.h>

void main()

{

int ch=NULL || EOF+1 && EOF ;

clrscr();

printf("%d",ch);

}

a)0 b)1 c)-1 d)48

----------------------------------------------------------

4.#include<stdio.h>

void main()

{  printf("a\/b=c",'%d',"%d");

}

a)a=c b)a\/b=c c)a/b=c  d)error

----------------------------------------------------------

5.#include<stdio.h>

void main()

{ clrscr();

printf("%d",1||-?('\n'==10!=0):printf("ok"));

}

a)1 b)0 c)error d)ok

6.#include<stdio.h>

void main()

{

float x=10.2345F;

int a;

clrscr();

a=x-(int)x;

printf("\n%f",(float)a);

}

a)10.234500  b)0.000000  c)error   d)10.2345

7.#include<stdio.h>

void main()

{

clrscr();

printf("a%cb",'\\b');

}

a)a\b  b)a\\b  c)b d)error

8.#include<stdio.h>

void main()

{

float f=2.0;

clrscr();

printf("%d\t\t%d",a,sizeof(2.0f+2));

 

}

a)4 b)8 c)6 d)error

 

----------------------------------------------------------

9. #include<stdio.h>

void main()

{

char ch='ab';

clrscr();

do

{

printf("%c",ch++);

}while(ch!='c'+1);}

a)abc b)ab b)abcd  d)error

10. #include<stdio.h>

void main()

{

int i,no=0;

clrscr();

for(i=0;i<=5;no+=i++,i==5?printf("%d",no):0);

}

a)15 b)10 c)100 d)150

11. #include<stdio.h>

void main()

{char ch='0a';

switch(ch)

{

case '0a':

puts("\nfirst"); break;

case 48:

puts("\nsecond");break;

default: printf("wrong");

}

}

a)first b)wrong     c)error  d)second

12. #include<stdio.h>

void main()

{

int a=5^8;

printf("%d",a*a);

}

a)13 b)169 c)-169 d)-13

13.        #include <stdio.h>

        int main()

        {            int i = 0, j = 0;

            while (i < 5, j < 10)

            {

                i++;        j++;

            }

            printf("%d, %d\n", i, j);

        }

a)0,0 b)5,5 c)10,10    d)error

14. #include <stdio.h>

        int main()

{ int a=7,b=2;

printf("\n%d",(int)((float)a/b-(int)a/b));

        }

a)0.5 b)0 c)0.500000 d)error

15. #include <stdio.h>

        int main() {

if(1)

if(0);

else if(1)

printf("\nOver");

else;

        }

a)Over  b)syntax missing error   c)nothing d)misplaced else

 

16. #include <stdio.h>

        int main()

{

int i=10,j=9;

clrscr();

while(--i && j++);

printf("\n%d %d",i,j);

        }

a)1  19  b)0 18 c)1 10 d)1 19

17. #include <stdio.h>

        int main()

{

int a = 6;

int b = 12;

clrscr();

while(a<b){

printf("\n%d %d",a,b,a+=2,b-=2);

}

        }

How many loops took in the above program

a)1   b)2    c)3    d)0

18. #include <stdio.h>

        int main()

{ do

{

printf("a");

do

printf("\b");

while(0);

printf("c");

}while('\0');

        }

a)a\bc   b)c     c)a\b   d)error

 

 

19.write a program to print

54321012345 (use only one for)

 

20.  print

0

1 0

0 1 0

1 0 1 0

0 1 0 1 0

 

 

ANS :

1.a

2.c

3.b

4.c

5.a

6.b

7.a

8.b

9.a

10.b

11.d

12.b

13.c

14.b

15.a

16.b

17.b

19.....

# include <math.h>

main(){

int i;

for(i=5;i>=-5;i++)

printf("%d",abs(i));

---------------------------

main(){

int i,j;

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

{

}



TT for ECE-I by RVS

Posted on July 14, 2014 at 1:35 AM Comments comments (1)

# q9 carries 2 m total 10m     /* all the ebst */


1#include<stdio.h>

void main()

{

            clrscr();

            if((2==2) &&printf("0") || 0)

            printf("true");

            else

            printf("false");

}

a)true  b)0true            c)false d)0

-----------------------------------------------------------------------------------------------------------------------------

2#include<stdio.h>

void main()

{

            int ch='\0';

            clrscr();

            ch++;

 

            while(1 && ch)

            printf("%d",ch--);

 

}

a)NULL            b)0       c)1      d)infinate loop

-----------------------------------------------------------------------------------------------------------------------------

3.#include<stdio.h>

void main()

{

            int ch=NULL || EOF+1 && EOF;

            clrscr();

            printf("%d",ch);

 

}

a)0       b)1       c)-1      d)48

----------------------------------------------------------------------------------------------------------------------------

4.#include<stdio.h>

void main()

{

                        printf("a\/b=c",'%d',"%d");

 

}

a)a=c   b)a\/b=c          c)a/b=c                        d)error

---------------------------------------------------------------------------------------------------------------------------

5.#include<stdio.h>

void main()

{

            clrscr();

            printf("%d",1||-1?('\n'==10!=0):printf("ok"));

}

a)1       b)0       c)error d)ok

6.#include<stdio.h>

void main()

{

            float x=10.2345F;

            int a;

            clrscr();

            a=x-(int)x;

            printf("\n%f",(float)a);

}

a)10.234500                b)0.000000                  c)error                         d)10.2345

7.#include<stdio.h>

void main()

{

            clrscr();

            printf("a%cb",'\\b');

}

a)a\b               b)a\\b              c)b       d)error

8.#include<stdio.h>

void main()

{

            float f=2.0;

            clrscr();

            printf("%d\t\t%d",a,sizeof(2.0f+2));

 

}

a)4       b)8       c)6       d)error

write aprogram to print

54321012345

 

 


C Aptitude for Final Yr. CSE/IT/MCA

Posted on June 27, 2012 at 3:35 AM Comments comments (0)

Subject: C

 

1.The C language terminator is

    a.semicolon

     b.colon

     c.period

    d.exclamation mark

 

2.What is false about the following

    A compound statement is

    a.A set of simple statments

    b.Demarcated on either side by curlybrackets

    c.Can be used in place of simplestatement

    d.A C function is not a compoundstatement.

 

A compound statement is a list ofstatements enclosed by braces

A compound statement consists of zeroor more statements enclosed in curly ...

A compound statement is any group ofvalid C statements enclosed in braces.

 

 

3.What is true about the following

    C Functions

    a.By default returns an integer

     b.Should always return an integer

     c.Should always return a float

     d.Should always return more than onevalue.

 

4.Main must be written as

    a.the first function in the program

    b.Second function in the program

    c.Last function in the program

    d.anywhere in the program

 

5.Which of the following about automatic variables within a function

is correct ?

   a.its type must be declared beforeusing the variable

   b.they are local

   c.they are not initialised to zero

   d.they are global.

 

6.Write one statement equalent to the following two statements

x=sqr(a);

return(x);

Choose from one of the alternatives

    a.return(sqr(a));

    b.printf("sqr(a)");

    c.return(a*a*a);

    d.printf("%d",sqr(a));

 

7.Which of the following about the C comments is incorrect ?

    a.comments can go over multiple lines

    b.comments can start any where in theline

    c.a line can contain comments without any language statements

    d.commentscan occur within comments

 

 

8.What is the value of y in the following code?

    x=7;y=0;

    if(x=6)

    y=7;

   else

   y=1;

 

If executes truepart only

 

  a.7

   b.0

  c.1

  d.6

 

9.Read the function conv() given below

   conv(int t)

   {

     int u;

     u=5/9 * (t-32);

     return(u);

   }

What

   a.15

  b.0

   c.16.1

   d.29

 

Fahrenheit To Centigrade: 5/9 * (

Fahrenheit - 32); note: .55555 = 5/9. Centigrade To Fahrenheit: ...

 

10.which of the following represents true statement

either x is inthe range of 10 and 50 or y is zero

     a.x>=20 && x<=50 ||y==0;

     b.x>=10 && x<=40 ||y==0;

     c.x>=10 && x>50 ||y==0;

    d.x>=10 && x<=50 || y==0;

 

11.Which of the following is not an infinite loop ?

    a.while(1){

        ....

         }

    b.for(;;){

         ...

        }

   c.x=0;

     do{

       /*x unaltered within theloop*/

        ...

       }while(x==0);

  d.# define TRUE 0

             ...

           while(TRUE){

           ....

          }

 

12.what does the following function print?

            func(int i)

               {

                if(i%2)

return 0;

       else

 return 1;

    }

             main()

             {

              int i=3;

              i=func(i);

              i=func(i);

             printf("%d",i);

            }

    a.3

   b.1

    c.0

    d.2

 

13.how does the C compiler interpret the following two statements

     p=p+x;

 

     q=q+y;

 

    a.p=p+x;

     q=q+y

     b.p=p+xq=q+y

     c.p=p+xq;

     q=q+y

     d.p=p+x/q=q+y

 

For questions 14,15,16,17 use the following alternatives

 

        a.int

       b.char

       c.string

       d.float

14.'9'

15."1 e 02"

16.10e05

17. 15

____________________________________

 

18.read the folllowing code

# define MAX 100

# define MIN 100

....

....

if(x>MAX)

x=1;

else if(x<MIN)

x=-1;

x=50;

 

if the initial value of x=200,what is the vlaue after executing this code?

a.200

b.1

c.-1

d.50

 

19.a memory of 20 bytes is allocated to a string declared as char*s

then the following two statements are executed:

s="Etrance"

l=strlen(s);

what is the value of l ?

a.20

b.8

c.9

d.21

20.given the piece of code

int a[50];

int *pa;

pa=a;

to access the 6th element of the array which of the following is incorrect?

a.*(a+5)

b.a[5]

c.pa[5]

d.*(*pa + 5)

21.consider the following structure:

struct num nam{

int no;

char name[25];

};

struct num namn1[]={{12,"Fred"},{15,"Martin"},{8,"Peter"},{11,Nicholas"}};

.....

.....

printf("%d%d",n1[2],no,(*(n1 + 2),no) + 1);

What does the above statement print?

a.8,9

b.9,9

c.8,8

d.8,unpredictable value

22.identify the in correct expression

a.a=b=3=4;

b.a=b=c=d=0;

float a=int b=3.5;

d.int a;

float b;

a=b=3.5;

23.regarding the scope of the varibles;identify the incorrect statement:

a.automatic variables are automatically initialised to 0

b.static variables are are automatically initialised to 0

c.the address of a register variable is not accessiable

d.static variables cannot be initialised with any expression

24.cond 1?cond 2?cond 3?:exp 1:exp 2:exp 3:exp 4;

is equivalent to which of the following?

a.if cond 1

exp 1;

else if cond 2

exp 2;

else if cond 3

exp 3;

else

exp 4;

b.if cond 1

if cond 2

if cond 3

exp 1;

else

exp 2;

else

exp 3;

else

exp 4;

c.if cond 1 && cond 2 && cond 3

exp 1 |exp 2|exp 3|exp 4;

d.if cond 3

exp 1;

else if cond 2

exp 2;

else if cond 3

exp 3;

else

exp 4;

25.the operator for exponencation is

a.**

b.^

c.%

d.not available

26.which of the following is invalid

a.a+=b

b.a*=b

c.a>>=b

d.a**=b

27.what is y value of the code if input x=10

y=5;

if (x==10)

else if(x==9)

elae y=8;

a.9

b.8

c.6

d.7

28.what does the following code do?

fn(int n,int p,int r)

{

static int a=p;

switch(n){

case 4:a+=a*r;

case 3:a+=a*r;

case 2:a+=a*r;

case 1:a+=a*r;

}

}

a.computes simple interest for one year

b.computes amount on compound interest for 1 to 4 years

c.computes simple interest for four year

d.computes compound interst for 1 year

29.a=0;

while(a<5)

printf("%d\n",a++);

how many times does the loop occurs?

a.infinite

b.5

c.4

d.6

30.how many times does the loop iterated ?

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

printf("Hi\n");

a.10

b.2

c.5

d.....

31.what is incorrect among teh following

A recursive functiion

a.calls itself

b.is equivalent to a loop

c.has a termination cond

d.does not have a return value at all

32.which of the following go out of the loopo if expn 2 becoming false

a.while(expn 1){...if(expn 2)continue;}

b.while(!expn 1){if(expn 2)continue;...}

c.do{..if(expn 1)continue;..}while(expn 2);

d.while(!expn 2){if(expn 1)continue;..}

33.consider the following program

B

main()

OB {unsigned int i=10;

while(i>=0){

printf("%u",i)

i--;

}

}

how many times the loop wxecuted

a.10

b.9

c.11

d.infinite

34.pick out the add one out

a.malloc()

b.calloc()

c.free()

d.realloc()

35.consider the following program

main()

{

int a[5]={1,3,6,7,0};

int *b;

b=&a[2];

}

the value of b[-1] is

a.1

b.3

c.-6

d.none

36.# define prod(a,b)=a*b

main()

{

int x=2;

int y=3;

printf("%d",prod(x+2,y-10)); }

 

the output of the program is

a.8

b.6

c.7

d.none

37.consider the following program sigment

int n,sum=1;

switch(n) {

case 2:sum=sum+2;

case 3:sum*=2;

break;

default:sum=0;}

if n=2, what is the value of sum

a.0

b.6

c.3

d.none

38.identify the incorrect one

1.if(c=1)

2.if(c!=3)

3.if(a<B)THEN

4.if(c==1)

a.1 only

b.1&3

c.3 only

d.all

39.teh format specified for hexa decimal is

a.%d

b.%o

c.%x

d.%u

40.find the output of the following program

main()

{

int x=5, *p;

p=&x;

printf("%d",++*p);

}

a.5

b.6

c.0

d.none

41.consider the following C code

main()

{

int i=3,x;

while(i>0)

{

x=func(i);

i--;

}

int func(int n)

{

static sum=0;

sum=sum+n;

return(sum);

}

the final value of x is

a.6

b.8

c.1

d.3

43.int *a[5] refers to

a.array of pointers

b.pointer to an array

c.pointerto a pointer

d......

46.which of the following statements is incorrect

a.typedef struct new{

int n1;

char n2;

} DATA;

b.typedef struct {

int n3;

char *n4;

}ICE;

c.typedef union {

int n5;

float n6;

} UDT;

d.#typedef union {

int n7;

float n8;

} TUDAT;

 

********************************************************************************

Only These Are The Questions Avilable For C Paper.

 

********************************************************************************

ANSWERS:

-----------

 

1-5 D,C,D,C,C

 

6-10 D,C,C,A,D

 

11-15 D,C,A,A,A

 

16-20 B,C,D,C,A

 

21-25 C,D,B,D,A

 

26-30 C,B,B,A,D

 

31-35 B,C,C,C,B

 

36-40 A,B,A,B,B

 

41-45 A,D,D,D,A

 

46-50 B,C,C,A,A

 

Example On FIFO

Posted on June 27, 2012 at 3:30 AM Comments comments (0)

 

// program on FIFO

 

    # include <stdio.h>

    # include <sys/types.h>

    # include <sys/stat.h>

    # include <fcntl.h>    

    int main()

    {

    int fd;

    char buff[100];

    /*creating FIFO */

    if((mkfifo("./MyFifo",S_IFIFO|S_IRWXU|S_IRWXG|S_IRWXO))<0)

    perror("\nmkfifo error...");

 

 

    /*creating reader process...*/

    

    fd=open("./MyFifo",O_RDONLY|O_NONBLOCK);

 

    while(read(fd,buff,sizeof(buff))>0)

    printf("%s",buff);

 

    /*creating write process */

    

    fd=open("./MyFifo",O_WRONLY);

    write(fd,"Hello world",12);

    close(fd);        

    }

 

 

Write a Java Program to read 5 strings and sort the strings in ascending order

Posted on December 15, 2011 at 5:25 AM Comments comments (1)

// AIM :  Write a Java Program to read 5 strings and sort the strings in ascending order 


import java.io.*;


class strsort
{
       public static void main(String arg[]) throws IOException
        {

int i,j,len;
String s[]=new String[5],swp;

DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter  5 strings ?");
for(i=0;i<=4;i++)
s[i]=in.readLine();


for(i=0;i<=3;i++)
{
for(j=i+1;j<=4;j++)
0)
{
swp=s[i];
s[i]=s[j];
s[j]=swp;
}

}
System.out.println("After sort....");

for(i=0;i<=4;i++)
   System.out.println(s[i]);


        }
}

Write a java Program to print Fibonacci up to n (10) terms.

Posted on December 15, 2011 at 5:25 AM Comments comments (0)

//Aim : Write a java Program to print Fibonacci up to  n (10) terms.

//importing io classes
import java.io.*;


class  Fibonacci_rec
{
public int fibo(int n)
{
if (n == 1)
return 1;
else if (n == 2)
return 1;
else
return fibo(n-1) + fibo(n-2);
}
/*
This method will do exactly that, it will invoke the two previous versions of itself,
and those invoked will invoke their previous selves and so on until one of them reaches
f(2) or f(1). It's easy to use this method in a loop to print out many Fibonacci numbers:
*/


public static void main(String[] args)
{

Fibonacci_rec f=new Fibonacci_rec();
for (int i=1; i<10; i++)
System.out.println(f.fibo(i));


}
}

Write a java program to generate fibonacci nos up to the nth value

Posted on December 15, 2011 at 5:20 AM Comments comments (0)

Aim : Write a java program to generate fibonacci nos up to the nth value

//importing io classes
import java.io.*;



class  Fibonacci
{
public static void main(String[] args) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
String s;
int a=1,b=1,c=a+b;
int n;

System.out.print("Enter nth value?");
s=in.readLine();
n=Integer.parseInt(s);
                System.out.print(a+","+b+",");
while(c<=n)
{
                        System.out.print(c+",");
a=b;
b=c;
c=a+b;
}
}
}

Write a Java Program to test the given string is palindrome or not

Posted on December 15, 2011 at 5:20 AM Comments comments (0)

//AIM:  Write a Java Program to test the given string is palindrome or not

import java.io.*;

class pal
{
       public static void main(String arg[]) throws IOException
        {

int i,j,len;
String s;

DataInputStream in=new DataInputStream(System.in);

System.out.print("Enter a string ?");
s=in.readLine();
len=s.length();

                        System.out.println("Len="+len);
                       
                        for(i=0,j=len-1;i<(len/2);i++,j--)
{
if(s.charAt(i)!=s.charAt(j))
break;
}

                        if(i==(len/2))
   System.out.println("Pal string");
else
   System.out.println("Not a Pal string");

        }
}

UDP simple client/server to transfer a file

Posted on September 24, 2011 at 1:25 AM Comments comments (0)

# include "unp.h"

/* UDP echo server dg_echo function to transfer a file : */

void dg_echo(int sockfd,SA*pcliaddr,socklen_t clilen)
{
FILE*f;
int n,i=0,ch;
socklen_t len;
char mesg[MAXLINE];
for(;;){
len=clilen;
n=Recvfrom(sockfd,mesg,MAXLINE,0,pcliaddr,&len);
printf(" sending data.");
f=fopen("myfile","r");
while((ch=getc(f))!=-1)
mesg[i++]=ch;
mesg[i]=0; //init null
Sendto(sockfd,mesg,i,0,pcliaddr,len);
}
}


/*UDP echo server main function:*/


#include"unp.h"
int main(int argc,char **argv[])
{
int sockfd;
struct sockaddr_in servaddr,cliaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERV_PORT);
Bind(sockfd,(SA*)&servaddr,sizeof(servaddr));
dg_echo(sockfd,(SA*)&cliaddr,sizeof(cliaddr));
}

# include "unp.h"

/* UDP ECHO Client: dg_cli function  to transfer the file*/

void dg_cli(FILE *fp,int sockfd,const SA* pservaddr,socklen_t servlen)
{
int n;
char sendline[MAXLINE], recvline[MAXLINE+1];

while ( Fgets(sendline,MAXLINE,fp)!=NULL)
{
sendto(sockfd, sendline, strlen(sendline), 0, pservaddr,servlen);
n= Recvfrom(sockfd,recvline, MAXLINE,0,NULL,NULL);
recvline[n]=0;
Fputs(recvline, stdout);
}
}



/* UDP client main function: */

int main(int argc, char **argv)

{

int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family= AF_INET;
servaddr.sin_port = htons(SERV_PORT);
Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
sockfd = Socket(AF_INET, SOCK_DGRAM, 0);
dg_cli(stdin, sockfd, (SA*) &servaddr, sizeof(servaddr));
exit(0);
}











UDP client /server program to transfer a string in reverse

Posted on August 27, 2011 at 7:20 AM Comments comments (0)

/* UDP server code to reverse a string */








/* close() */
/* memset() */

#define LOCAL_SERVER_PORT 1500
#define MAX_MSG 100

int main(int argc, char *argv[]) {
int l,x,y;
char swp;
int sd, rc, n, cliLen, flags;
struct sockaddr_in cliAddr, servAddr;
char msg[MAX_MSG];

/* socket creation */
sd=socket(AF_INET, SOCK_DGRAM, 0);
if(sd<0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}

/* bind local server port */
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(LOCAL_SERVER_PORT);
rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
if(rc<0) {
printf("%s: cannot bind port number %d \n",
argv[0], LOCAL_SERVER_PORT);
exit(1);
}

printf("%s: waiting for data on port UDP %u\n",
argv[0],LOCAL_SERVER_PORT);


flags = 0;


/* server infinite loop */
while(1) {

/* init buffer */
memset(msg,0x0,MAX_MSG);

/* receive message */
cliLen = sizeof(cliAddr);
n = recvfrom(sd, msg, MAX_MSG, flags,
(struct sockaddr *) &cliAddr, &cliLen);

if(n<0) {
printf("%s: cannot receive data \n",argv[0]);
continue;
}

/*reversing string */
l=strlen(msg);

for(x=0,y=l-1;x<l/2;x++,y--)
{
swp=msg[x];
msg[x]=msg[y];
msg[y]=swp;
}
/* print received message */
printf("%s: from %s:UDP%u : %s \n",
argv[0],inet_ntoa(cliAddr.sin_addr),
ntohs(cliAddr.sin_port),msg);


sleep(1);
sendto(sd,msg,n,flags,(struct sockaddr *)&cliAddr,cliLen);


}/* end of server infinite loop */

return 0;

}



/* UDP client code */


/* for exit() */







/* memset() */
/* select() */

#define REMOTE_SERVER_PORT 1500
#define MAX_MSG 100


#define SOCKET_ERROR -1

int isReadable(int sd,int * error,int timeOut) { // milliseconds
fd_set socketReadSet;
FD_ZERO(&socketReadSet);
FD_SET(sd,&socketReadSet);
struct timeval tv;
if (timeOut) {
tv.tv_sec = timeOut / 1000;
tv.tv_usec = (timeOut % 1000) * 1000;
} else {
tv.tv_sec = 0;
tv.tv_usec = 0;
} // if
if (select(sd+1,&socketReadSet,0,0,&tv) == SOCKET_ERROR) {
*error = 1;
return 0;
} // if
*error = 0;
return FD_ISSET(sd,&socketReadSet) != 0;
} /* isReadable */



int main(int argc, char *argv[]) {

int sd, rc, i, n, echoLen, flags, error, timeOut;
struct sockaddr_in cliAddr, remoteServAddr, echoServAddr;
struct hostent *h;
char msg[MAX_MSG];


/* check command line args */
if(argc<3) {
\n", argv[0]);
exit(1);
}

/* get server IP address (no check if input is IP address or DNS name */
h = gethostbyname(argv[1]);
if(h==NULL) {
printf("%s: unknown host '%s' \n", argv[0], argv[1]);
exit(1);
}

h_name,
h_addr_list[0]));

h_addrtype;
memcpy((char *) &remoteServAddr.sin_addr.s_addr,
h_length);
remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);

/* socket creation */
sd = socket(AF_INET,SOCK_DGRAM,0);
if(sd<0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}

/* bind any port */
cliAddr.sin_family = AF_INET;
cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliAddr.sin_port = htons(0);

rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
if(rc<0) {
printf("%s: cannot bind port\n", argv[0]);
exit(1);
}


flags = 0;

timeOut = 100; // ms


/* send data */
for(i=2;i<argc;i++) {
rc = sendto(sd, argv[i], strlen(argv[i])+1, flags,
(struct sockaddr *) &remoteServAddr,
sizeof(remoteServAddr));

if(rc<0) {
printf("%s: cannot send data %d \n",argv[0],i-1);
close(sd);
exit(1);
}


/* init buffer */
memset(msg,0x0,MAX_MSG);

while (!isReadable(sd,&error,timeOut)) printf(".");
printf("\n");

/* receive echoed message */
echoLen = sizeof(echoServAddr);
n = recvfrom(sd, msg, MAX_MSG, flags,
(struct sockaddr *) &echoServAddr, &echoLen);

if(n<0) {
printf("%s: cannot receive data \n",argv[0]);
continue;
}

/* print received message */
printf("%s: echo from %s:UDP%u : %s \n",
argv[0],inet_ntoa(echoServAddr.sin_addr),
ntohs(echoServAddr.sin_port),msg);



}

return 1;

}

TCP client/server to transfer the file

Posted on August 9, 2011 at 4:25 AM Comments comments (0)

/* TCP server to transfer the file */



#include "unp.h"

void
str_echo(int sockfd)
{
long arg1, arg2;
ssize_t n;
char line[MAXLINE];
char fname[100];
char ch;
FILE*f;

int i=0;
for ( ; ; ) {
if ( (n = Readline(sockfd, line, MAXLINE)) == 0)
return; /* connection closed by other end */

n = strlen(line);
printf("\nReq From Client for file : %s",line);

strcpy(fname,line);
f=fopen("myfile","r");
while((ch=getc(f))!=EOF)
{
line[i++]=ch;
}
printf("\n....%d",i);
fclose(f);
Writen(sockfd, line, n);
}
}

int
main(int argc, char **argv)
{
int listenfd, connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;

listenfd = Socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);

Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

Listen(listenfd, LISTENQ);

printf("Server Running on Port %d\n", SERV_PORT);
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);

if ( (childpid = Fork()) == 0) { /* child process */
Close(listenfd); /* close listening socket */
str_echo(connfd); /* process the request */
exit(0);
}
Close(connfd); /* parent closes connected socket */
}
}
/* TCP clent */
void
str_cli(FILE *fp, int sockfd)
{
char sendline[MAXLINE], recvline[MAXLINE];

while (Fgets(sendline, MAXLINE, fp) != NULL) {

Writen(sockfd, sendline, strlen(sendline));

if (Readline(sockfd, recvline, MAXLINE) == 0)
err_quit("str_cli: server terminated prematurely");

Fputs(recvline, stdout);
}
}
   
int
main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;

if (argc != 2)
");

sockfd = Socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));

str_cli(stdin, sockfd); /* do it all */

exit(0);
}


Semaphore /Shared memory simple example

Posted on August 3, 2011 at 7:24 AM Comments comments (0)

/*

Shared memory is perhaps the most powerful of the SysV IPC methods, and it is the easiest to implement. As the name implies, a block of memory is shared between processes. Listing 7 shows a program that calls fork(2) to split itself into a parent process and a child process, communicating between the two using a shared memory segment.
A program illustrating the use of shared memory
The following program shows the contents of Filename : sema_simple.c

*/








int main(void) {
pid_t pid;
int *shared; /* pointer to the shm */
int shmid;
shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
if (fork() == 0) { /* Child */
/* Attach to shared memory and print the pointer */
shared = shmat(shmid, (void *) 0, 0);
printf("Child pointer %u\n", shared);
*shared=1;
printf("Child value=%d\n", *shared);
sleep(2);
printf("Child value=%d\n", *shared);
} else { /* Parent */
/* Attach to shared memory and print the pointer */
shared = shmat(shmid, (void *) 0, 0);
printf("Parent pointer %u\n", shared);
printf("Parent value=%d\n", *shared);
sleep(1);
*shared=42;
printf("Parent value=%d\n", *shared);
sleep(5);
shmctl(shmid, IPC_RMID, 0);
}
}

 




Rss_feed