Vous êtes sur la page 1sur 28

Fall 2011 Bachelor of Computer Application (BCA) Semester 1 BC0034 Computer Concepts & C Programming (Book ID: B0678)

8) Assignment Set 1

1. Explain the basic structure of a C program with an example. Answer: A C program can be viewed as a group of building blocks called functions. A function is a subroutine that may include one or more statements designed to perform a specific task. To write a C program we first create functions and then put them together. A C program may contain one or more sections shown in Fig. 1.1.

The documentation section consists of a set of comment(remarks) lines giving the name of the program, the author and other details which the programmer would

like to use later. Comments may appear anywhere within a program, as long as they are placed within the delimiters /* and */ (e.g., /*this is a comment*/). Such comments are helpful in identifying the programs principal features or in explaining the underlying logic of various program features. The link section provides instructions to the compiler to link functions from the system library. The definition section defines all symbolic constants. There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. Every C program must have one main function section. This section contains two parts, declaration part and executable part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between opening and closing braces({ and }). The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function section is the logical end of the program. All statements in the declaration and executable parts end with a semicolon(;). The subprogram section contains all the user-defined functions that are called in the main function. User-defined functions are generally placed immediately after the main function, although they may appear in any order. All sections, except the main function section may be absent when they are not required.

2. State the rules for naming a variable in C.

Answer: Informally, a variable (also called an object) is a place where you can store a value so that you can refer to it unambiguously. A variable needs a name. You can think of the variables in your program as a set of boxes, each with a label giving its name; you might imagine that storing a value in a variable consists of writing the value on a slip of paper and placing it in the box. The rules for naming Variables Within limits, you can give your variables and functions any names you want. These names (the formal term is identifiers) consist of letters, numbers, and underscores. For our purposes, names must begin with a letter. Theoretically, names can be as long as you want, but extremely long ones get tedious to type after a while, and the compiler is not required to keep track of extremely long ones perfectly. (What this means is that if you were to name a variable, say, supercalafragalisticespialidocious, the compiler might get lazy and pretend that youd named it super- calafragalisticespialidocio, such that if you later misspelled it super-calafragalisticespialidociouz, the compiler wouldnt catch your mistake. Nor would the compiler necessarily be able to tell the difference if for some perverse reason you deliberately declared a second variable named supercalafragalisticespialidociouz.) The capitalization of names in C is significant: the variable names variable, Variable, and VARIABLE (as well as silly combinations like variAble) are all distinct. A final restriction on names is that you may not use keywords (the words such as int and for which are part of the syntax of the language) as the names of variables or functions (or as identifiers of any kind).

3. Write a program to read four floating point numbers and find their sum and average.

Answer: #include<studio.h> #include<conio.h> main() { float a[4],sum=0,avg=0; int i; printf("Enter the four numbers to find their sum and average); for(i=0;i<=3;i++) { scanf(%d,a[i]); } for(i=0;i<=3;i++) { sum=sum+a[i]; } printf("The Sum of numbers is:",sum); avg=sum/4; printf("\nThe average of numbers is:",avg); gettch(); }

4. What are the commonly used input/output functions in C? How are they accessed? Answer: The most basic way of reading input is by calling the function getchar(). getchar() reads one character from the standard input, which is usually the users keyboard. getchar() returns (rather obviously) the character it reads, or, if there are no more characters available, the special value EOF (end of file). This value will be assigned within the stdio.h file. Typically, EOF will be assigned the value -1, but this may vary from one compiler to another. The syntax of the getchar() function is written as character variable= getchar() where character variable refers to some previously declared character variable.

A companion function is putchar(), which writes one character to the standard output. (The standard output is usually the users screen). The syntax of the putchar() function is written as putchar(character variable) where character variable refers to some previously declared character variable. Input data can be entered into the computer from a standard input device by means of the standard C library function scanf(). This function can be used to enter any combination of numerical values, single character and strings.

The function returns the number of data items that have been entered successfully. The syntax of scanf function is as follows: scanf(control string, arg1, arg2, argn) where control string refers to a string containing certain required formatting information, and arg1, arg2,, argn are arguments that represent the individual input data items. The arguments represent pointers that indicate addresses of the data items within the computers memory. Output data can be written from the computer onto a standard output device using the library function printf(). This function can be used to output any combination of numerical values, single characters and strings. It is similar to the input function scanf(), except that its purpose is to display data rather than enter into the computer. The syntax of the printf function can be written as follows: printf(control string, arg1, arg2, , argn) where control string refers to a string that contains formatting information, and arg1, arg2, , argn are arguments that represent the individual output data items. The arguments can be written as constants, single variable or array names, or more complex expressions. gets() and puts() functions facilitate the transfer of strings between the computer and the standard input/output devices. Each of these functions accepts a single argument. The argument must be a data item that represents a string( an array of characters). The string may include whitespace characters. In the case of gets(), the string will be entered from the keyboard, and will terminate with a newline character(i.e. a string will end when the user presses the RETURN key).

Example: Reading and writing a line of text. #include<stdio.h> main() { char line[80]; gets(line); puts(line); } This program uses gets() and puts() functions rather than scanf() and printf(), to transfer the line of text into and out of the computer.

5. Differentiate string constants and character constants with one example each. Answer: There are some non-numerical constants, like: 1 'z' 2 'p' 3 "Hello world" 4 "How do you do?"

The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a

string (which generally consists of more than one character) we enclose it between double quotes ("). When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions: 1x 2 'x'

x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'. Character and string literals have certain peculiarities, like the escape codes. These are special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of some of such escape codes: \n newline \r carriage return \t tab \v vertical tab \b backspace \f form feed (page feed) \a alert (beep) \' single quote (') \" double quote (") \? question mark (?) \\ backslash (\) For example:

1 '\n' 2 '\t' 3 "Left \t Right" 4 "one\ntwo\nthree"

Additionally, you can express any character by its numerical ASCII code by writing a backslash character (\) followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16) number. In the first case (octal) the digits must immediately follow the backslash (for example \23 or \40), in the second case (hexadecimal), an x character must be written before the digits themselves (for example \x20 or \x4A). String literals can extend to more than a single line of code by putting a backslash sign (\) at the end of each unfinished line. 1 "string expressed in \ 2 two lines"

You can also concatenate several string constants separating them by one or several blank spaces, tabulators, newline or any other valid blank character: "this forms" "a single" "string" "of characters"

Finally, if we want the string literal to be explicitly made of wide characters (wchar_t type), instead of narrow characters (char type), we can precede the constant with the L prefix: L"This is a wide character string"

Wide characters are used mainly to represent non-English or exotic character sets. 6. What are precedence of operators? How expressions are evaluated using precedence? Answer: The precedence of C operators dictates the order of evaluation within an expression. The precedence of the operators introduced here is summarized in the Table. The highest precedence operators are given first.

The table above shows that the same operator appears twice (for example *) the first one is the unary version.

A program to illustrate evaluation of expressions #include<stdio.h> main() /* Evaluation of expressions */ { float a, b, c, x, y, z; a=20; b=2; c=-23; x = a + b / ( 3 + c * 4 - 1); y = a b / (3 + c) * ( 4 1); z= a ( b / ( 3 + c ) * 2 ) 1; printf( x=%f\n, x); printf(y=%f\n, y); printf(z=%f\n, z); }

7. Explain pre increment and post increment operator with an example. Answer: When we want to add or subtract constant 1 to a variable, C provides a set of shortcuts: the autoincrement and autodecrement operators. In their simplest forms, they look like this: ++i add 1 to i j subtract 1 from j The ++ and operators apply to one operand (theyre unary operators). The expression ++i adds 1 to i, and stores the incremented result back in i. This means that these operators dont just compute new values; they also modify the value of some variable. (They share this propertymodifying some variablewith the assignment operators; we can say that these operators all have side effects. That is, they have some effect, on the side, other than just computing a new value.) The incremented (or decremented) result is also made available to the rest of the expression, so an expression like k = 2 * ++i means add one to i, store the result back in i, multiply it by 2, and store that result in k. (This is a pretty meaningless expression; our actual uses of ++ later will make more sense.) Both the ++ and operators have an unusual property: they can be used in two ways, depending on whether they are written to the left or the right of the variable theyre operating on. In either case, they increment or decrement the variable theyre operating on; the difference concerns whether its the old or the new value thats returned to the surrounding expression. The prefix form ++i increments i and returns the incremented value. The postfix form i++ increments i, but returns

the prior, non-incremented value. Rewriting our previous example slightly, the expression k = 2 * i++ means take is old value and multiply it by 2, increment i, store the result of the multiplication in k. The distinction between the prefix and postfix forms of ++ and will probably seem strained at first, but it will make more sense once we begin using these operators in more realistic situations. For example, a[i] = c; i = i + 1; using the ++ operator, we could simply write this as a[i++] = c; We wanted to increment i after deciding which element of the array to store into, so the postfix form i++ is appropriate. Notice that it only makes sense to apply the ++ and operators to variables (or to other containers, such as a[i]). It would be meaningless to say something like 1++ or (2+3)++

The ++ operator doesnt just mean add one; it means add one to a variable or make a variables value one more than it was before. But (1+2) is not a variable, its an expression; so theres no place for ++ to store the incremented result.

8. Explain type cast operator with one example. Answer: C performs type conversions automatically. However, there are instances when we want to force a type conversion in a way that is different from the automatic conversion. Consider, for example, the calculation of ratio of doctors to engineers in a town. Ratio = doctor_number / engineer _number Since doctor _number and engineer_number are declared as integers in the program, the decimal part of the result of the division would be lost and Ratio would represent a wrong figure. This problem can be solved by converting locally one of the variables to the floating point as shown below: Ratio = (float) doctor_number / engineer _number The operator (float) converts the doctor_number to floating point for the purpose of evaluation of the expression. Then using the rule of automatic conversion, the division is performed in floating point mode, thus retaining the fractional part of the result. Note that in no way does the operator (float) affect the value of the variable doctor_number. And also, the type of doctor_number remains as int in the other parts of the program. The process of such local conversion is known as casting a value. The general form of cast is: (type-name) expression

where type-name is one of the standard C data types. The expression may be a constant, variable or an expression. The Table shows some examples of casts and their actions: Example X=(int) 8.5 A=(int) 21.3 / (int) 4.5 B=(double) sum/n Y= (int) (a+b) Z= (int) a+b P=cos(( double)x) Action 8.5 is converted to integer by truncation. Evaluated as 21/4 and the result would be 5. Division is done in floating point mode. The result of a+b is converted to integer. a is converted to integer and then added to b. Converts x to double before using it.

1. What do you mean by formatted input and formatted output? Explain. Answer Formatted Input and Output: Formatted input reads characters from the input file and converts them to internal form. Formatted I/O can be either "Free" format or "Explicit" format, as described below.

Advantages and Disadvantages of Formatted I/O Formatted input/output is very portable. It is a simple process to move formatted data files to various computers, even computers running different operating systems, as long as they all use the ASCII character set. (ASCII is the American Standard Code for Information Interchange. It is the character set used by almost all current computers, with the notable exception of large IBM mainframes.) Formatted files are human readable and can be typed to the terminal screen or edited with a text editor. However, formatted input/output is more computationally expensive than unformatted input/output because of the need to convert between internal binary data and ASCII text. Formatted data requires more space than unformatted to represent the same information. Inaccuracies can result when converting data between text and the internal representation.

2. Explain about the gets () and puts () functions with one example. Answer:

gets() and puts() functions facilitate the transfer of strings between the computer and the standard input/output devices. Each of these functions accepts a single argument. The argument must be a data item that represents a string( an array of characters). The string may include whitespace characters. In the case of gets(), the string will be entered from the keyboard, and will terminate with a newline character(i.e. a string will end when the user presses the RETURN key).

Example: Reading and writing a line of text. #include<stdio.h> main() { char line[80]; gets(line); puts(line); }

3. Write a recursive program to solve Towers of Hanoi problem. Answer: #include "stdio.h"

void towers(int,char,char,char);

void towers(int n,char frompeg,char topeg,char auxpeg) { /* If only 1 disk, make the move and return */ if(n==1) { printf("\nMove disk 1 from peg %c to peg %c",frompeg,topeg); return; } /* Move top n-1 disks from A to B, using C as auxiliary */ towers(n-1,frompeg,auxpeg,topeg); /* Move remaining disks from A to C */ printf("\nMove disk %d from peg %c to peg %c",n,frompeg,topeg); /* Move n-1 disks from B to C using A as auxiliary */ towers(n-1,auxpeg,topeg,frompeg); } main() { int n; printf("Enter the number of disks : "); scanf("%d",&n);

printf("The Tower of Hanoi involves the moves :\n\n"); towers(n,'A','C','B'); return 0; }

4. Explain single dimensional and two dimensional array concepts. Answer. Array: An array in C language is a collection of similar data-type, means an array can hold value of a particular data type for which it has been declared. Arrays can be created from any of the C data-types int, float, and char. So an integer array can only hold integer values and cannot hold values other than integer. When we declare array, it allocates contiguous memory location for storing values whereas 2 or 3 variables of same data-type can have random locations. So this is the most important difference between a variable and an array.

Types of Arrays: One dimensional Array: Declaration of One Dimensional Arrays: Syntax: data_type array_name[width]; Example: int roll[8]; In our example, int specifies the type if the variable, roll specifies the name of the variable and the value in bracket [8] is new for newbie. The bracket ([ ]) tells compiler that it is an array and number mention in the bracket specifies that how many elements (values in any array is called elements) it can store. This number

is called dimension of array. So, with respect to our example we have declared an array of integer type and named it roll which can store roll numbers of 8 students.

Two dimensional Array: In C language it is possible to have more than one dimension in an array. In this tutorial we are going to learn how we can use two dimensional arrays (2D arrays) to store values. Because it is a 2D array so its structure will be different from one dimension array. The 2D array is also known as Matrix or Table, it is an array of array. See the below image, here each row is an array.

Declaration of 2D array: Syntax: data_type array_name[row_size][column_size]; Example: int arr[3][3]; So the above example declares a 2D array of integer type. This integer array has been named arr and it can hold up to 9 elements (3 rows x 3 columns). 2D Array

Memory Map of 2D Array

5. With an example, illustrate the concept of extern variable. Answer: All variables we have seen so far have had limited scope (the block in which they are declared) and limited lifetimes (as for automatic variables). However, in some applications it may be useful to have data which is accessible from within any block and/or which remains in existence for the entire execution of the program. Such variables are called global variables, and the C language provides storage classes which can meet these requirements; namely, the external and static classes.

External variables may be declared outside any function block in a source code file the same way any other variable is declared; by specifying its type and name. No storage class specifier is used - the position of the declaration within the file indicates external storage class. Memory for such variables is allocated when the program begins execution, and remains allocated until the program terminates. For most C implementations, 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 extern defines a global variable that is visible to ALL object modules. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.

Source 1 --------

Source 2 --------

extern int count; write() { printf("count is %d\n", count); }

int count=5; main() { write(); }

Count in 'source 1' will have a value of 5. If source 1 changes the value of count source 2 will see the new value 6. Write a program to add two 2x2 matrices Answer: #include<stdio.h> #include<conio.h> void main() { int a[2][2], b[2][2],c[2][2],i,j;

printf(Enter the value of matrix a and b\n); for(i=0;i<2;i++) { for(j=0;j<2;j++){ scanf(%d,&a[i][j]); } } for(i=0;i<2;i++) { for(j=0;j<2;j++){ scanf(%d,&b[i][j]); } } for(i=0;i<2;i++) { for(j=0;j<2;j++){ c[i][j]=a[i][j]+b[i][j]; } }

for(i=0;i<2;i++) { for(j=0;j<2;j++){ printf(%d,c[i][j]); } } getch(); }

7. What is the difference between pointer variable and simple variable? What are the advantages of pointer variable?

Answer: 1) A pointer can be re-assigned: int x = 5; int y = 6; int *p; p = &x; p = &y; *p = 10; assert(x == 5); assert(y == 10); A reference cannot, and must be assigned at initialization: int x = 5; int y = 6; int &r = x; 2) A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address but also takes up some space on the stack. Since a reference has the same address as the original variable itself, it is safe to think of a reference as another name for the same variable. Note: What a pointer points to can be on the stack or heap. Ditto a reference. My claim in this statement is not that a pointer must point to the stack. A pointer is just a variable that holds a memory address. This varia-

ble is on the stack. Since a reference has its own space on the stack, and since the address is the same as the variable it references. More on stack vs heap. This implies that there is a real address of a reference that the compiler will not tell you. int x = 0; int &r = x; int *p = &x; int *p2 = &r; assert(p == p2); 3) You can have pointers to pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection. int x = 0; int y = 0; int *p = &x; int *q = &y; int **pp = &p; pp = &q;//*pp = q **pp = 4; assert(y == 4); assert(x == 0); 4) Pointer can be assigned NULL directly, whereas reference cannot. If you try hard enough, and you know how, you can make the address of a reference NULL. Likewise, if you try hard enough you can have a reference to a pointer, and then that reference can contain NULL. int *p = NULL; int &r = NULL; <--- compiling error 5) Pointers can iterate over an array, you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to. 6) A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access it's members whereas a reference uses a .. 7) A pointer is a variable that holds a memory address. Regardless of how a reference is implemented, a reference has the same memory address as the item it references. 8) References cannot be stuffed into an array, whereas pointers can be. Advantage : 1: you can work with the address of the variable 2: you can reference the variables in more different easiest ways.... e.g int a[10],*b; b=&a;

if you want to refer a[5] you can refer it as a[5] or *(a+5) or *(5+a) this is a simple one....but in large programs it will make a difference. 3. if you want to access a variable quickly or efficiently without wasting c.p.u time you have only 2 ways.. one is declare it as a register variable... and other one is declare it with a pointer.... because a c.p.u has less registers in it ( approximately 6 i.e A,B,C,D,E,F,G,H), when no register are freely available then you CAN DO THAT TASK WITH ONLY POINTERS.... 4.by using pointers you can improve the c.p.u's throughput time (throughput time refers to no of jobs done by the c.p.u in unit amount of time).... these are the advantages that can be acquired from pointers.

8. Give the differences between Structures and Unions with one example. Answer:

Structure i. Access Members We can access all the members of structure at anytime.

Union

Only one member of union can be accessed at anytime.

ii. Memory Allocation Allocates memory for variable which variable require more memory.

Memory is allocated for all variables.

iii. Initialization All members of structure can be initialized Only the first member of a union can be initialized. iv. Keyword 'struct' keyword is used to declare structure.

'union' keyword is used to declare union.

v. Syntax

struct struct_name
{ structure element 1; structure element 2; ------------------structure element n; }struct_var_nm;

union union_name
{ union element 1; union element 2; ------------------union element n; }union_var_nm;

vi. Example

struct item_mst
{ int rno; char nm[50]; }it;

union item_mst
{ int rno; char nm[50]; }it;

Vous aimerez peut-être aussi