Sie sind auf Seite 1von 12
February 2010 Master of Computer Application (MCA) – Semester 1 MC0061 – Computer Programming “C Language”

February 2010

Master of Computer Application (MCA) – Semester 1 MC0061 – Computer Programming “C Language” – 4 Credits (Book ID: B0678 & B0679) Assignment Set – 1

February 2010 Master of Computer Application (MCA) – Semester 1 MC0061 – Computer Programming “C Language”

Book ID: B0678

  • 1. With the help of a suitable example, explain the basic structure of a C program.

Ans: Basic structure of a C program is /* Documentation section */ /* Link section */ /* Definition section */ /* Global declaretion section */ /* Function section */ (return type) (function n`ame) (arguments ) ... void main() { Declaration part Executable part (statements) } /* Subprogram section */

(return type) (function name 1) (arguments (return type) (function name 2) (arguments . . (return type) (function name n) (arguments Basic structure of a C program is /* Documentation section */ /* Link section */ /* Definition section */ /* Global declaretion section */ /* Function section */ (return type) (function name) (arguments ) ... void main() { Declaration part Executable part (statements)

) ...

) ...

) ...

} /* Sub ‐ program section */ (return type) (function name 1) (arguments ) ... (return

} /* Subprogram section */ (return type) (function name 1) (arguments

) ...

(return type) (function name 2) (arguments . .

) ...

(return type) (function name n) (arguments

) ...

  • 2. Write a program in C to find largest of three numbers using the conditional operator.

Ans: #include <stdio.h> int main() {

int a,b,c; int max; printf("\nEnter the values for a,b,c "); scanf("%d%d%d",&a,&b,&c);

max = ( (a > b) && ( a > c)? a : (b >c) ? b : c ); printf("Max = %d",max); getch();

}

  • 3. With the help of suitable examples, explain type conversions using various data types.

Ans: In computer science, type conversion or typecasting refers to changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies. For instance, values from a more limited set, such as integers, can be stored in a more compact format and later converted to a different format enabling operations not previously possible, such as division with several decimal places' worth of accuracy. In objectoriented programming languages, type conversion allows programs to treat objects of one type as one of their ancestor types to simplify interacting with them.

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. The most common form of explicit type conversion is known as casting. Explicit type conversion can also be achieved with separately defined conversion routines such as an overloaded object constructor.

Each programming language has its own rules on how types can be converted. In general, both objects and fundamental data types can be converted.

I MPLICIT TYPE CONVERSION

Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. Some languages allow, or even require, compilers to provide coercion.

In a mixed ‐ type expression, data of one or more subtypes can be converted to

In a mixedtype expression, data of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly. For example, the following is legal C language code:

double d;

long l;

int i;

if (d > i) d = i;

if (i > l) if (d == l)

l = i; d *= 2;

Although d, l and i belong to different data types, they will be automatically converted to equal data types each time a comparison or assignment is executed. This behavior should be used with caution, as unintended consequences can arise. Data can be lost when floatingpoint representations are converted to integral representations as the fractional components of the floatingpoint values will be truncated (rounded towards zero). Conversely, converting from an integral representation to a floatingpoint one can also lose precision, since the floatingpoint type may be unable to represent the integer exactly (for example, float might be an IEEE 754 single precision type, which cannot represent the integer 16777217 exactly, while a 32bit integer type can). This can lead to situations such as storing the same integer value into two variables of type integer and type float which return false if compared for equality.

E XPLICIT TYPE CONVERSION

Explicit type conversion is a type conversion which is explicitly defined within a program (instead of being done by a compiler for implicit type conversion).

U SING CASTING

double da = 5.5; double db = 5.5; int result = static_cast<int>(da) + static_cast<int>(db); //Result would be equal to 10 instead of 11. There are several kinds of explicit conversion.

CHECKED

Before the conversion is performed, a runtime check is done to see if the destination type can hold the source value. If not, an error condition is raised.

UNCHECKED

No check is performed. If the destination type cannot hold the source value, the result is undefined.

BIT PATTERN

The raw bit representation of the source is copied verbatim, and it is reinterpreted according to the destination type. This can also be achieved via aliasing.

In objectoriented programming languages, objects can also be downcasted : a reference of a base class is casted to one of its derived classes.

U SING OVERLOADED OBJECT CONSTRUCTOR

class Myclass { public: double myD; Myclass(double d) : myD(d) {}; }; int main(int argc, char

class Myclass { public:

double myD; Myclass(double d) : myD(d) {};

};

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

Myclass obj = 5.2; // here is the type conversion return 0;

}

  • 4. Using input and output functions in C, write a program to accept a string of characters

Ans: There is an example which will help to understand about Initializing Strings, Reading Strings from the terminal, Writing strings to screen, Arithmetic operations on characters.

A string is a sequence of characters. Any sequence or set of characters defined within double quotation symbols is a constant string. In c it is required to do some meaningful operations on strings they are:

Reading string displaying strings Combining or concatenating strings Copying one string to another. Comparing string & checking whether they are equal Extraction of a portion of a string

Strings are stored in memory as ASCII codes of characters that make up the string appended with ‘\0’(ASCII value of null). Normally each character is stored in one byte, successive characters are stored in successive bytes.

Character

m

y

a

g

e

i

s

ASCII Code

77

121

32

97

103

10

32

105

115

 

Character

2

(

T

W

O

)

\0

ASCII Code

32

50

32

40

116

119

41

0

0

/* Example program to use string functions*/ #include < stdio.h > #include < string.h > void

/* Example program to use string functions*/ #include < stdio.h > #include < string.h > void main() {

char s1[20],s2[20],s3[20]; int x,l1,l2,l3; printf(“Enter the strings”);

scanf(“%s%s”,s1,s2);

x=strcmp(s1,s2);

if(x!=0)

{printf(“\nStrings are not equal\n”);

strcat(s1,s2);

} else printf(“\nStrings are equal”);

strcpy(s3,s1);

11=strlen(s1);

12=strlen(s2);

13=strlen(s3);

printf(“\ns1=%s\t length=%d characters\n”,s1,11); printf(“\ns2=%s\t length=%d characters\n”,s2,12); printf(“\ns3=%s\t length=%d characters\n”,s3,13); }

  • 5. Explain the following giving suitable examples for each:

Mixedmode Expressions

Ans: An expression that contains variables and constants of different data types is called as a mixed mode expression

In a mixed mode expression, there are two types of conversions that can take place.

  • a) Implicit data conversion (IDC)

  • b) Explicit data conversion(EDC

I MPLICIT DATA CONVERSION :

In this type of conversion, the complier will automatically convert the values of lower data types to the values of their corresponding higher data types.

Example: IDC between int and float.

main(){ double res; float r1 = 3.1, r2 = 3.3, r3; int x = 5, y

main(){ double res; float r1 = 3.1, r2 = 3.3, r3; int x = 5, y = 4, z; res = (x+r1) * (y+r2) + 10; printf("\n res = %f ",res); }

*The right side value before being assigned to the left side variable it will be converted to the data type of the left side variable.

R ULES OF IDC:

When a real value is assigned to an integer variable, the fractional part is truncated and only integer part is assigned to the variable.

When integer value says 'x' is assigned to a float variable, it is stored as x.000

When a character is assigned to an integer variable, the ASCI value of the character is assigned to the integer variable.

When a valid integer value (0 to 255) is assigned to a character variable, the characterequalant of the integer value is assigned to the character variable.

E XPLICIT DATA CONVERSION :

In this type of conversion, the output of an expression can be converted to the desired data type by placing the data type within the brackets before the expression. The process of placing data type within the brackers is also called as type casting.

Example:

main(){ /*Without conversion */ int x = 5, y = 2; float r; r = x/y; printf("\n r = %f",r);

} main(){ /*With EDC*/ int x = 5, y = 2; float r; r = (float)x/y; /*EDC*/ printf("\n r = %f",r);

} Run the above two program and observe the difference. The result of the first program,

}

Run the above two program and observe the difference. The result of the first program, without EDC will display the result as 2 and the second program with EDC will display the result as 2.500;

The type cast Operator

An operator is a symbol or string of C characters used as a function. One very valuable operator in C is the cast operator, which converts one type into another. Its general form is as follows:

( TYPE ) VARIABLE

For example, floating point and integer types can be interconverted:

float exact_length; int rough_length;

exact_length = 3.37; rough_length = (int) exact_length;

In the example above, the cast operator rounds the number down when converting it from a float to an integer, because an integer number cannot represent the fractional part after the decimal point. Note that C always truncates, or rounds down, a number when converting it to an integer. For example, both 3.1 and 3.9 are truncated to 3 when C is converting them to integer values.

The cast operator works the other way around, too:

float exact_length; int rough_length;

rough_length = 12; exact_length = (float) rough_length;

In converting large integers to floating point numbers, you may lose some precision, since the float type guarantees only 6 significant digits, and the double type guarantees only 10.

The following is an example of how to use the cast operator in C code. It also shows how to use an integer variable to store a character value.

#include <stdio.h>

int main()

/* Use int float and int */

{

float my_float; int my_int; int my_ch; my_float = 75.345; my_int = (int) my_float; my_ch = (int)

float my_float;

int my_int;

int my_ch;

my_float = 75.345; my_int = (int) my_float; my_ch = (int) my_float; printf ("Convert from float my_float=%f to my_int=%d and my_ch=%c\n", my_float, my_int, my_ch);

my_int = 69; my_float = (float) my_int; my_ch = my_int; printf ("Convert from int my_int=%d to my_float=%f and my_ch=%c\n", my_int, my_float, my_ch);

my_ch = '*'; my_int = my_ch; my_float = (float) my_ch; printf ("Convert from int my_ch=%c to my_int=%d and my_float=%f\n", my_ch, my_int, my_float);

exit(0);

} Here is the sort of output you should expect (floating point values may differ slightly):

Convert from float my_float=75.345001 to my_int=75 and my_ch=K Convert from int my_int=69 to my_float=69.000000 and my_ch=E Convert from int my_ch=* to my_int=42 and my_float=42.000000 The type char

char is a numerical type, but its main use is to represent characters, not numerical work. C provides a wide range of character literals which return the numerical value of a character (usually the ASCII code). Character literals are enclosed in apostrophes, for example:

char c = 'H';

will assign to c the numerical value of the character H. Since char is an integer type and C will convert between numerical types quite readily, the following are perfectly legal

int i = 'H'; double f = 'c'; i = 'K' * 67.57; but probably not

int i = 'H';

double f = 'c';

i = 'K' * 67.57;

but probably not very useful. C also defines character literals for less convenient characters,

such as newline and the tab character (these actually give an int rather than a char, but this

difference is not normally important). The newline, horizontal and vertical tab and formfeed

characters, together with the space character are known collectively as whitespace.

literal

meaning

\a

alert (bell)

\b

backspace

\f

pagebreak (formfeed)

\n

newline (linefeed)

\r

carriagereturn

\t

horizontal tab

\v

vertical tab

\"

doublequote

\'

apostrophe

\\

backslash

\ooo

the character with numerical value ooo in octal

\xhh ...

the character with numerical value hh in hexadecimal

...

Book ID: B0679 6. Write a program in C to explain pointer arithmetic. Ans: In c

Book ID: B0679

  • 6. Write a program in C to explain pointer arithmetic.

Ans: In c a pointer is a variable that points to or references a memory location in which data is stored. Each

memory cell in the computer has an address that can be used to access that location so a pointer

variable points to a memory location we can access and change the contents of this memory location

via the pointer

A pointer is a variable that contains the memory location of another variable. The syntax is as shown

below. You start by specifying the type of data stored in the location identified by the pointer. The

asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the

variable.

type * variable name

Example:

int *ptr;

float *string;

Address operator:

Once we declare a pointer variable we must point it to something we can do this by assigning to the

pointer the address of the variable you want to point as in the following example:

ptr=&num;

This places the address where num is stores into the variable ptr. If num is stored in memory 21260

address then the variable ptr has the value 21260.

/* A program to illustrate pointer declaration*/

main()

{

int *ptr;

int sum;

sum=45;

ptr=

printf (“\n Sum is %d\n”, sum);

printf (“\n The sum pointer is %d”, ptr);

}

  • 7. Write a program to print the details of MCA program with the entities program name, number of semesters, subjects in each semester, number of credits per subject using structures and print the required output.

Ans: this is a complete program to reverse a linkked list in C. first node is

Ans: this is a complete program to reverse a linkked list in C. first node is allocated memory but dosent

contain any data.

#include<stdio.h>

#include<stdlib.h>

struct list

{

int month;

struct list *next;

};

typedef struct list node;

void init(node* record)

{

record>next=NULL;

}

void addnode(node* record,int d)

{

node* fresh;

fresh=(node *)malloc(sizeof(node));

fresh>month=d;

fresh>next=record>next;

record>next=fresh;

}

void print(node *record)

{

node* temp;

temp=(node *)malloc(sizeof(node));

for(temp=record>next;temp;temp=temp>next)

printf(" %d",temp>month);

}

void reverse(node* record)

{

node* temp;node* temp1;node* temp2;

temp=(node *)malloc(sizeof(node));

temp1=(node *)malloc(sizeof(node));

temp2=(node *)malloc(sizeof(node));

temp=record;temp1=temp>next;temp2=temp1>next;

temp ‐ >next ‐ >next=NULL; while(temp2!=NULL) { temp=temp1; temp1=temp2; temp2=temp1 ‐ >next; temp1 ‐ >next=temp; }

temp>next>next=NULL;

while(temp2!=NULL)

{

 

temp=temp1;

temp1=temp2;

temp2=temp1>next;

temp1>next=temp;

}

record>next=temp1;

}

int main(void)

{

node* start;

node* start1;

start=(node *) malloc(sizeof(node));

init(start);

int i=0;

for(i=10;i>=0;i‐‐)

addnode(start,i);

print(start);

reverse(start);

printf("n");

print(start);

return 0;

}