You are on page 1of 25

1

Programming in C
History of C Programming Language C language is the middle level programming language. The C language was developed at AT&T Bell Laboratories, USA by Denis Ritchie in 1972. This is general-purpose language. Before the development of C language there were many languages that were developed, but these languages served some specific purpose. For example, for commercial applications, where lot of data are needed to be stored and retrieved, COBOL is used; for Engineering and Scientific applications, which needs more calculating power than data storage and retrieval facilities, FORTRAN is used, etc. There was a need for a common language for all these purposes. C came into existence, after the development of many languages like ALGOL 60, CPL, BCPL, B, and many others, which didnt actually serve the purpose and were a specific purpose language. C as a programming language is sometimes referred to as a middle-level language. This is because it provides much flexibility and ease for the programmer as provided by any high-level language and the same time it provides and supports certain features and concepts that are necessary for good system (lowlevel) programming. Explain the use of the following: printf Function The printf function is used to print out a message either on screen or paper. The syntax of printf function is as follows: printf(text to be printed); When printf is used, it means that printing function is to be called for action. The statement or texts used in quotes are called the control strings. newline Character \n The newline symbol instructs the computer to advance to the next new line before printing subsequent information. The printf function does not do this automatically. Semicolon ; - The end of any statement in C Programming is denoted by a semicolon. In C, all statements are terminated with a semicolon. Braces Braces are used at the start as well as at the end of the program. The open brace { is used to begin a program, just below main() function. The alignment of the braces on either side is not strictly necessary but it makes the program more readable. The closed brace } is used to denoted end of a program. Comments The comment demonstrates the method used in C to add a comment or remark to a program. This is done by beginning the comment with the two characters /* and ending it with the characters */. No space can be included between the two characters. Between these pairs of characters (delimiters), any characters may be included either in upper or lowercase. In other words, a comment appears as follows: /* Whatever you want using any characters at all */ The only restriction is that a comment nay not contain the closing delimiter */ as a part of the comments text. All such comments are ignored by the compiler ad have no effect on the way the program runs. They included because they serve as an excellent way of internally documenting the programs. When a program is printed out, those comments appear along with the instructions. Comments may start on the same line as another statement or on a line of its own. It may also extend over any number of lines if the terminating delimiter is placed at the appropriate point. What are Constants? Give types and rules for each one of them. Constant is a quantity that doesnt change and can be stored at any location in the memory of the computer. These quantities may be combinations of alphabets, numbers or special symbols in C. eg: 2y=30, where 2 and 30 are constants i.e., their value cannot be changed. C Constants can be divided into two categories: Primary constants

1.

2 2. Secondary constants Primary constants are as follows: i. Integer Constants An integer constant refers only to numbers. It may be a single digit or combination of digits. Generally, integer constants are written in decimal number system, which consist of combination of digits from 0-9. Rules for constructing Integer constants. An integer constant must contain of at least one digit. It should not contain decimal values. The numbers could either be positive or negative. It does not allow commas or blank space. The range of integer constant is 32768 to +32767 ii. Float Constants A float constant refers to numbers that contains a decimal point or an exponent or both. The float constants are often known as real constants that could be written in two forms: fractional or exponential. Rules for constructing Float constants a) A float constant must consist of at least one digit. b) It should have decimal values c) The numbers could either be positive or negative d) It does not allow commas or blank spaces e) A letter e should separate the mantissa part and the exponent part. For example, 301224x10-17 would be represented as 301224 e 17 in float constants. f) The range of real constants is much greater than integer constants, which is expressed as 3.4e38 to 3.4e38. iii. Character Constants A character constant is defined as a single alphabet, a single digit or a special symbol enclosed within single quotes (r). Rules for constructing Character constants a) The maximum length of character constant can be 1 character. b) The quotes within the character is enclosed must point to the left as a. c) The characters constant have integer values determined by computers ASCII character set. d) The range of character constant is 128 to +127. Secondary Constants are as follows: Logical Constants A logical constant refers to either of two values zero or non-zero. Zero is treated as false whereas non-zero value is treated as true. eg: 12, -24, 1.7, are logical constants with true value whereas 0 is a logical constant with false value. These constants help solving logical expression and complex conditions easily. ii. String Constant A string constant is a combination of characters enclosed within double quotes (India). Some special characters like backslash are included as a part of string constant. Each of the string constant is ended with special character called null character represented as \0 that acts as a string terminator but it is not displayed on the screen. iii. Pointer Constants These include the name of an array without subscripts and the name of a function without parentheses. A string literal actually is an instance of a constant pointer, since its value is a pointer to the string. i.

a) b) c) d) e)

What are Variables? Explain Variables are quantities that can be changed. Variable names are the names given to the locations in memory of a computer where different values are stored. The locations may however contain an integer, character, real or any constant but if a variable has been declared with int data type, it must be contain an integer value and so on. While declaring a variable the first character in the variable name must be an

3 alphabet. The name of the variable should not have any commas, blank spaces or special symbols except the underscore (_). We cannot give name of the variable similar to any reserved word of the C programming language. Examples of declarations: int i; char var; float floating-point; int year, month; While declaring the variables you can also assign some initial values to them as shown below: int i = 10; char c = A; int j = i; Rules for naming variables: 1) Variables names must begin with a letter of the alphabet. In C, the underscore character is considered a letter. It is legal to start a variable name with the underscore character, but this practice is discouraged to prevent possible conflict with some special system names that begin with the underscore. 2) The first character may be followed by a sequence of letters and/or digits (0 through 9). 3) On most microcomputers, the first seven or eight characters (depending upon the version upon the version of C) of the name must be unique. That is, no other variable used in the program may begin with the same seven or eight characters. If it does, it will be treated as the same name and the program may produce questionable result. 4) The compiler regards uppercase and lowercase letters as different, although both may be used in constructing variable names. Therefore, the variable names NET, net and Net are regarded as different variable names in C. Usually, variable names are entirely entered in lowercase. 5) No variable name may be a keyboard. This rule means we cannot give a variable a reserved name such as int. 6) No special characters, such as a blank space, period, semicolon, commas or slash are permitted in variable names. What are operators? Classify them. Operators refer to symbol that represents a particular operations to be performed on data. The data, on which the operation is to be performed, is called operand and the term, which performs the function, s called the operator. For example, in the expression, 12 + 24, 12 and 24 are operands whereas + is an operator. An operator needs two or one operand to perform any action. 1) Assignment Operator Assignment operator is used to assign the value to a variable. This is done by the assignment operator =. The syntax of assignment operator is identifier = expression, where identifier generally represents a variable and expression represents a constant, a variable or a more complex expression. For example, a=30; /* here variable a is given a value from constant 30 */ 2) Arithmetic Operators Arithmetic operators are used in mathematical expressions. There are basically four arithmetic operators in C. They are (a) + (Addition) This operator is used to add two numbers. Eg: i=3+j; (b) (Subtraction) This operator is used to subtract two numbers. Eg: i=3-j; (c) * (Multiplication) This operator is used to multiply two numbers. Eg: i = j*k; (d) / (Division) This operator is used to divide two numbers. Eg: i = j/2; 3) Modulus Operator This operator can also be considered a part of arithmetic operator because this is also used for mathematical operations. This is generally represented as %. This operator returns remainder after integer division and is a supplement to the division operator as the division operator returns the quotient. It can only be applied to integer data type. For example, 24 % 7, will give the output 3 as it is the remainder. If the numerator is smaller than the denominator, then the operator will return the numerator itself. Eg: j = 2 % 4; /* this will store value 2 in j */ 4) Relational Operators These operators are used to compare to check whether they are equal, unequal, greater or lesser than the other. The operands can be variables, constants or expressions that ultimately

4 give a numeric value. the relational operators also need two operands for their operation. There are six operators used in C: (a) < (less than) This operator evaluates whether a given value is less than the other or not. E.g.: 4 < 3 would return false. (b) > (greater than) This operator evaluates whether a given number is greater or not. E.g.: 4 > 43 would return true. (c) <= (less than or equal to) This operator evaluates whether a given value is less than or equal to the other or not. (d) >= (greater than or equal to) This operator evaluates whether a given value is greater than or equal to the other or not. (e) = = (equal to) This operator evaluates whether a given value is equal to the other value or not. (f) != (not equal to) This operator evaluates whether a given value is not equal to the other. 5) Logical Operators- Logical operators combine the result of evaluate of expression and produce the result in terms of either true or false value. There are three types of logical operators in C. They are: (a) && (And) This operator is used to combine two expressions or values and produce result as true only if both are true. If one of the expression is false, the && operator will return false. E.g.: (2>4) && (4>3) would return false but if the same expression is written as (2<4) && (4>3) would return true as both the expressions are true. (b) || (Or) This operator gives the result as true even if one of the expressions is true. For example, (2>4) || (4>3), in this statement though the first expression is false but the second expression is true therefore it would return true. (c) ! (Not) This operator returns the reverse of what is evaluated i.e. it makes a true expression false and a false expression true. For example,! (2<4) would return false in spite of expression itself being true. Increment and Decrement Operators (a) + + (Increment operator) This operator increments the value of the operand by one. E.g.: if a = 23, the expression a+ + will increase the value of a by 1 that means now the value of a will become 24. (b) - - (Decrement operator) This operator decrements the value of the operand by one. For example, if a = 23, the expression a- - would return 22. These operators can be used either before i.e., prefix or after i.e., postfix to the operand. In both the cases the value of the operand is incremented by one. But if the increment or decrement operator is used in an expression that has to assign a value to some other variable, there is a difference between postfix and prefix notation. In the prefix form, the operand is incremented or decremented before the value is obtained expression. In the postfix, the original value is used in the expression and then the operand is modified. For example, consider the following expression int a = 10; int b; b = ++a; Here, there are two things to be done. One job is to assign the value of a and b and secondly, the value of a is to be incremented. This example is using the prefix notation that means the increment operator is written before the operand a. In prefix form the value of a will be incremented first and then the value of a will be assigned to b. This means b will get the value 11. a however, is incremented so after the expression the value of a will become 11 and that of b will also come out to be 11. Now let us consider the postfix notation. In this notation, the same example can be written as : int a = 10; int b; b=a++; Here also two jobs are to be done, assignment and increment. But since, it is a postfix notation the value of a will be assigned to b first and then the value of a will be incremented. Hence in this type of expression the value of b will be 10 and that of a will become 11. Note that it is the value of b that is affected due to prefix and postfix notations, the value of a will always be incremented.

6)

5 Classify the I/O functions and define them. Input/Output (I/O) refers to receiving data from any input devices example, keyboard and sending data to the output devices example, VDU (Visual Display Unit). C does not have any provision for input or output of data. Linking the C compiler with the I/O facilities of a particular library defined function does it. The standard I/O functions are put into libraries and are called while writing a C program. Thus, though C is not having I/O statement calls, library defined functions can be used for this task. A C function is a set of statements, which are executed, every time the function is invoked by calling its name. These functions can be accessed from anywhere within a program. I/O function can be classified into two types: a) Console I/O functions These are the functions that receive input from keyboard and write output to screen. b) Disk I/O functions These are the functions that perform I/O operations on secondary storage device like floppy, hard disk etc. Classify Console I/O functions and define them (a) Unformatted I/O functions The unformatted I/O functions are the standard library functions called in C programs. They are used for single character or a string of characters. These are as follows: (1) getch( ) This function returns the character that has been typed most recently. This character would not be echoed on the screen but is assigned to a variable immediately. E.g.: char a; a = getch( ); This will assign the character pressed to a but will not display it on the screen. Further it will not wait for the user to press the enter key. As soon as the user presses any key the control will be passed further in the program. (2) getche( ) This function echoes or displays the character type on the screen. Adding e to the getch( ) is for echo. As in getch( ) function the character is assigned to a variable immediately, similarly is done in this function also but the only difference between the two is that this character assigned to a variable is also displayed on the screen. For example, char a; a = getche( ); This will assign the character pressed to a and will also display it on the screen. Similarly to getch( ), it will also not wait for the user to press the enter key. (3) getchar( ) This function is same as getche( ) but the only difference between the two is that in getche( ) and getchar( ) there is a need of a carriage return (enter key) then only it is assigned to the variable and gets displayed. (4) putch( ) and putchar( ) Both these functions are exactly the same. They transmit a single character to an output device. Both these functions are used to display the character on the screen. For example, char a = A; putch(c); putchar(A); The output will be A. (5) gets( ) - scanf( ) function has a limitation when we enter a multi-word string in a string variable because when space is entered in-between the two words, it is assumed that the word is ended so it displays only one word when we use printf( ) function. For example: printf(enter your name:); scanf(%s,name); printf(my name is %s, name); The execution of the above code will be: enter your name: ABC my name is ABC So, as there was a space after ABC it is assumed end of the word.

6 To remove this limitation, there was a function named gets( ) function. This function is terminated only and only if a key is pressed. It accepts spaces, tabs etc. as its input. gets( ), gets a newline(\n) terminated string of characters from with the keyboard and replaces the \n with \0 i.e. the null character. For example, gets(a) will accept the input until the enter key is pressed. (6) puts( ) This function is complementary to gets( ) function. It is for output to the screen for a string. This function also prints the spaces between the two words. It is just opposite to gets( ) function used for input as this is used for output. For example, gets(a); puts(happy birthday); puts(a); The output will be by assigning a value to a. Suppose, we write ABC, then the output on the screen will be happy birthday ABC (b) Formatted I/O functions These functions are used to format the input or output of data as per the user requirements. The major difference between unformatted and the formatted I/O functions is that in the latter user can format the input or the output displayed according to his own requirement. For example, to display the output on which part of screen, how many spaces to be present between two values or any other thing that you require to be displayed can be controlled by using the formatted I/O functions. (1) The input function - scanf( ) This function allows you to read data from keyboard that can be formatted accordingly. This input data can be arranged in a particular format. Each scanf( ) statement is ended with a semicolon. This function generally is written as: scanf(format string, &a1, &a2, &a3, &an); where control string refers to the field format in which data is to be entered and a1, a2, .,an are the arguments that represent the individual input data items. scanf( ) function is used for input of the data. (2) The output function printf( ) This function is used to display plain messages to the user. The same function can be used to display the value of the variables you are using in your program. The syntax of printf( ) function is: printf(format string, variable list); If you want to display a simple message to the use, you can use the function like: printf(your message); Everything that is enclosed in the double quotes will be displayed to the user on the screen as it is. What are Conditional Statements? Conditional statement refers to determination of flow of control in a program. As it is Important to know the precedence of operators to get the problems executed,similarly It is required to know the order in which the instructions are to be executed in a Program by the computer. Generally, in most of the C programs the instructions were Executed in the same order as they appeared. Each of these instructions was executed Only once. So, there was a need of group of statements, which would help, in repeated executions or determining whether a condition is true or false.Control statement are classified into following categories: (a) Decision Control Instructions (b) Loop Control or Iteration Instructions (c) Case Control Instructions (d) Branching Statements What are Decision Control Instructions? The decision control instructions enable us to change the flow of a program based on some conditions. These statement are required to take actions on statement based on the condition. These instructions allow the computer to take decision as to which statement is to be executed next. The various decision control instructions are as follows:

7 1. The if statement 2. The if-else statement 3. Nested if The if Statement The instructions in a program are executed sequentially. If we want to alter the sequence we can do it with the use of decision control statement in C. The if statement allows decision to be made by evaluating a given condition is true or false. These conditions involve both the comparison and operators. The keyword if is followed with the involve both the comparison and logical operators. The keyword if is followed with the conditions and statement next to it are executed only and only if the condition is true. If the condition is not true, the statement next to it are skipped. The syntax of if statement is: if (condition) statement; If there is more than one statement to be executed in case the condition is true, than You would be required to include all such statement in a pair of curly braces as Shown below: If (condition) { Statement } Failure of doing so will result in the execution of just the immediate statement after the if condition. Rest of the statement will become ineffective form the if claus. For example, to check the identity of a person named Mahesh and display an Appropriate message, we use the if condition as follow: If (identity = = 1024) { printf(Found Mahesh); } The if-else statement The statement enclosed within the curly after the condition of the if clause would be executed only if the condition of is true. If you want to execute some statement if the condition is false, you can do this using else i.e., if condition is false the control moves to statement following else. The if-else statement helps reduce the complexity of a program to some extent and also improves its readability. The syntax of if-else statement is: if (condition) { statement; } else { statement; } For example, to find whether the number is odd or even if (number%2 = = 0) { printf(the number is even); } else { printf(the number is odd);

8 } The if-else statements can also use the following syntax: (condition)? Statement1: Statement2 in this declaration, if the condition is true statement1 will be performed and if it is false the else part which is separated with a colon : will be performed. Thus the above example will be done in this way: (number % 2 = = 0)? printf(the number is even ): printf(the number is odd); ? and : are together known as conditional operator. They are also referred to as ternary operator. Nested if - When we combine several if statements, it is referred to as nested if statement. This improves the flexibility in programming. In these statements the control is moved to the next if statement only if the condition is true and after performing the first statement the next if condition is checked and if this is also true, then the second statement is performed. In case, the first condition is false, the control skips the following statements of both if conditions and moves to the else part, if specified. The syntax of Nested-if statement is: if (condition 1) { statement 1; if (condition 2) { statement 2; } } For example, to check if the identity of the person is 1024, display an appropriate message and then check if this age is greater than 25 and then display another message. If you make the program as shown below: if (identity = = 1024) { printf(found match); } if (age> 25) { printf (age matched); } here condition for age is checked separately from that of identity. In this case, if the age greater than 25 and the identity is not equal to 1024, then also the message is displayed. But actually it is required that the age verification should be checked only if the identity verification is true. The solution to this problem can be done through nested if as shown below: The syntax of the nested if-else statement is: If (condition 1) { statement 1; if (condition 2) { statement 2; else statement 3; } else statement 4; } Define Loop control or Iteration Instructions.

9 Loop is basically the execution of a sequence of statements repeatedly until a particular condition is true. A computer program is a set of statements, which is normally executed sequentially. But, most of the times it is necessary to repeat certain steps to meet a specified condition. Loops enable programmers to write a simple statement or group of statements instead of writing a large number of statements again and again. Loops help in the ability to perform a set of instructions repeatedly. This repeated operation is done through a loop control statement. The loop statements supported in C programming are : 1. while loop 2. do-while loop 3. for loop While Loop When you know the number of times an action is to be performed, you can use the while loop. This loop repeats a statement or a number of statements till a certain condition is true. These statements form the body of the loop. First, the loop is initialized then the condition is mentioned after the keyword while, then start within the curly braces, write the body of the loop i.e. the statements to be performed and then increment the value of the variable that is taken while initializing the condition. The syntax of the while loop is as follows: while (test loop variable by a condition) { statements } for example, to display the numbers from 1 to 10 main( ) { int a = 1; /* initialize the variable */ while (a <= 10) { printf (\n%d,a); a+ +;} /*increment the value of the variable*/ } In this program , first the condition is checked if it is true, then the value of a is displayed as 1, then the value of a is incremented and again the condition is checked. The process continues till the value of a is less than and equal to 10. Do-while loop If the condition in the while loop is initially false, then the body of the loop is not executed at all i.e. it first checks the condition and then performs the statement, but in the do-while loop the statement within the loop is performed atleast once irrespective of the condition. In do-while loop the condition is given at the end i.e. after the body of the loop. The syntax of the do-while loop is: do { statements } while (condition); For example, to display the nos. from 1 to 10, using do-while loop, the program will be as: main ( ) { int a = 1; do { printf(\n%d,a); a + +; while (a<=10); } } In this program, first the value of a is displayed as 1, then the value of a is incremented and the condition is checked for whether the value of a is less than or equal to 10. If it is true the body of the loop is performed

10 otherwise the statements within the body of the loop are skipped and control is transferred to the statements written immediately following the condition. Thus, we see that a would have been displayed even if the condition were false for the first time. For loop In while and do-while loops the variable whose value is checked in the condition is initialized outside the body of the loop. Inside the body of the loop the variable is incremented or decremented as required. For loops with smaller body these are quite satisfactory but for bigger loops having larger number of statements it could become quite difficult to check for what is the initialization statement and to search the increment or decrement statement inside the body of the loop. for provides a better solution for this problem. In for loop the initialization, condition and increment or decrement can be done at one place, in the starting of the loop. The syntax of the for loop is: for (initialize variable; condition; increment or decrement variable) { statement } Here, the variable is initialized first, then the condition is checked. If the condition is true, only then the statements forming the body of the loop will be executed. After the execution of the statements the increment or decrement operation is performed and after that the condition is checked again. If it is still found to be true, the statements are executed once more, then the increment or decrement operation is performed and thus the process goes on till the condition does not become false. For example, to display the nos. from 1 to 10 the program can be written as: main () { int a; /* no need to initialize here */ for (a = 1; a<= ; a + +) { printf (\n%d,a);} } In this program, the first condition is checked, if it is true, then the value of a is displayed as 1, then the value of a is incremented and again the condition is checked for whether a is less than or equal to 10. If it is true, the body of the loop is performed otherwise the control comes out of the loop. the for loop is special for the following reasons: 1. You can declare variable inside the initialization stub 2. You can declare and initialize more than one variable in the initialization stub, all separated by comma. Similarly, more than one variables value can be modified in the increment or decrement stub. Explain the following: Switch statement Switch statement provides better alternative than a large series of if-else statements because any part of the code can be executed on the value of an expression. In this, a particular group of statement can be chosen from several available groups. This selection is based upon the current value of a expression, which is included within the switch statement. The syntax of the switch statement is : switch (expression) { case 1: statement 1 case 2: statement 2 case 3: statement 3 -----------case n: statement n

11 default: statement } Continue statement The break statement, when executed, causes the immediate termination of the loop containing it. C also provides a statement called Continue which terminates only the current iteration of the loop that immediate encloses it, thus causing execution to resume with the next iteration. For example the following function prints out all nos. in the range 1 through 100 which are not multiples of 7: non_7 ( ) { int 1; for (i = 1 ; i <= 100; i + + ) { if (I % 7 = = 0) continue; printf(%d\n,i); } The continue statement can easily be replaced by an if statement, but in a loop with a more complex body sometime sit is easier to use continue. Many proponents of structured programming criticize the use of continue because it can always be replaced by an if statement, other approve of is use for the same reason. Many programmers believe that both break and continue are acceptable in a structure programs since they permit control to be transferred only locally. Unlike the break statement, continue has no meaning in the context of a switch statement. If it is used inside one, it causes termination of the iteration of a loop enclosing the switch. If a continue statement is not enclosed within a loop a syntax error is indicated by the compiler. Break statement The Break statement is used to terminate a loop or a sequence of statement in a switch statement. A break statement enforces immediate termination. In a loop when a break statement is encountered, the loop is terminated and the program control moves to the next statement following the loop. It is simply written as break; For example, main ( ) { int i; for (i = 1; i <= 100; i + +) { if (i = = 10) break; printf(\n%d,i); } printf(\nOut of the loop); } Goto statement The goto statement is used to alter the normal sequence of program execution by transferring the control to some other part of the program. The control may be transferred to any part of the program. The goto statement is written as goto label; where label is the identifier used as the target where the control is to be transferred. For example, main ( ) { int i; printf(enter the no. of times Pakistan has won against India:); scanf(%d,&i) if (i<10) goto change; printf(India is the best team in Asia); goto end; change:

12 printf(change the Indian Team); end: } In this program change is the identifier that is used to target at the other statement where the control is transferred. After the first printf statement is written again a goto statement is used to make the control jump after the second printf function call. If this had not been done after executing first printf statement the control would come to next printf statement and the message, Change the Indian Team would also be printed. What is an array? Or What is a Single-dimension array? In C, as in other computer language it is possible to assign a single name to a whole group of similar data. For example, if we are interested in a large no. of recorded Celsius temperatures we can assign a common name such as C_temp to all of the data. Then we can refer to each element in a terms of its position within the list of items. This is done in mathematics as well as in computer programming using an entity called an array. An array is a group of elements that share a common name and that are differentiated from one another by their positions within the array. For example, if we have file nos. all of which are named x, they maybe listed as: x 58 63 49 18 7 The position of each of these elements can be indicated by means of a subscripts: x1 = 58 x2 = 63 x3 = 49 x4 = 18 x5 = 7 In mathematics, a subscript is no. written to the right of the variable name slightly below the line and usually in small type. The subscript indicates the position of the particular element with respect to the rest of the elements. Since it is impossible to display subscripted nos. on the standard computer terminal the user recourse is to enclose the subscript in parenthesis or brackets. In C, square brackets are used. The following five statements are valid in C: x[1] = 58; x[2] = 63; x[3] = 49; x[4] = 18; x[5] = 7; What is Array Index? Array Index indicates which of the array elements we want to access. It is written as: Array-name[index] Array index should be a numeric value and starts at 0. Thus, num[0] is the first element, num[1] the second and so on.. How do you declare an array? Arrays are declared in the sane way as we declare variables. Any name can be given to the array as in the case for variables names. For example, int num[5] is the array declaration of array num, which contains 5 elements of integer type.

13 How do you assign values to array elements? As you assign values to variables, similarly you can do for array elements. The only difference is that instead of writing, e.g. a=5 is assigning value to a variable, we need to write the array name with the (element number -1) in square brackets. It should be mentioned (element number -1) because the array starts with 0. So, if you want to call the third element we need to write array name[2] as : [0] 1st element [1] 2nd element [3] 3rd element So, assigning values will be num[2] = 10 How can values be retrieved from an array? As you assign a value to an array element, similarly you an retrieve a value from an array element. A value is retrieved from an array element in the following way: a = num[4]; The above statement will retrieve the value from the fifth element of the array num and store in the variable a. How are single-dimension arrays passed to functions? You can pass an entire array to a function. Though this passing of an array differs from that of an ordinary variable. A function is declared in the same way and instead of variable name in the arguments we write the array name without enclosing any element number in square brackets. But in actual arguments i.e. when the function is called only the array name without any square brackets is passed. This is generally written as: Function-name (variable name, array name); In formal arguments i.e. while defining the function it is done in the same manner as done while declaring the function. For example, float average (int a, float x[]); /*function declaration */ main ( ) { int n; float avg; float list[100]; avg = average(n, list); /*calling a function */ } float average(int a, float x[]) /*defining function */ { statements; } Thus, it can be observed that declaring and defining function by passing array is done in the same way. But when, you call the function average, arguments passed seem to be ordinary variables whereas list is an array. When array is passed to a function, the values of the array elements are not passed to the function. Rather, the array name is interpreted as the address of the first array element. This address is assigned to the corresponding formal arguments within the function called. What are two-dimensional array? How do you declare a two-dimensional array? Unlike, single-dimensional array that has only the column element, two dimensional arrays consists of both the rows and columns of elements. The number of square brackets determines the dimension of an array i.e. as single dimensional array has only one pair of square bracket, two-dimensional array has two pairs of square brackets, array name[] [].

14 The first square brackets represents row and the second represents columns. The two-dimensional array has two is also called a matrix. To represent a 3x3 matrix in two-dimensional array, we write as array name[3] [3]. These are represented as follows: Column 0 Column 1 Column 2 Row 1 2 11 12 Row 2 10 24 78 Row 3 78 19 1 Thus, first square brackets represent 3 rows and second brackets represents 3 columns. As the feature of single dimensional array, a two-dimensional array also starts with 0. may it be for rows or columns. Declaring a two-dimensional array The declaration of two-dimensional array is done generally in the form: data-type array-name[row size] [column size] Initializing value to two-dimensional array A two-dimensional array is initialized at the time of declaration as done in the single-dimensional array. When we initialize an array it is necessary to mention the second dimension i.e. the column, for example int arr[2] [3] or int arr[ ] [3]

What are Multi-dimensional Arrays? Multi-dimensional arrays are defined in the same manner as single-dimensional arrays, except that the pair of square brackets is required. If there is single squre bracket, it is single-dimensional; if there are two brackets then two-dimensional and if there are three brackets then three-dimensional and so on. The multi-dimensional array is written as: data-type array-name [dim 1] [dim 2] [dim 3].[dim n]; Where data type defines the type of array, array name is given to the array and dim 1, dim 2, dim n are the number of elements represented by each square brackets and square brackets the dimension of the array. What are String Library Functions? Discuss few of them. When we store a large number in one group, it is named as array, if we want to group a number of characters, they arte stored in a character array. These character arrays are also termed strings. Strings are single-dimensional character array terminated by a null character (\0) which determines the end of the string. Each character in the array occupies one byte of memory. Example, char name[10]; scanf(%s,name); Input- John Memory representation of the above example is J 1001 o 1002 h 1003 n 1004 \0 1005

Initializing a String char name[] = John; \0 is not input by the user as C inserts the null character automatically. This indicates one thing that a string always takes one character more and hence one more byte in the memory. The null character helps in this way: main ( ) {

15 char name[] = John; for (i = 0; i <= 3; i + +) { printf(%c, name[i]); } String library functions are the functions which are used regularly and stored in a library file and whenever these functions are needed, you need to include the required header file (string.h) in your program to be able to use these functions. Some of the string library functions are: Strlen( ) function This function is used to count the number of characters present in a string. It calculates the length of the string. The syntax of this function is: strlen(array-name) This function does not perform when the parenthesis are enclosed with some string but calculates the length if the base address is passed within it. Strcpy( ) function This function copies the contents of one string into another. The syntax of this function is: strcpy(target, source) This function performs only when it supplies the base address of the source and target string. Strcat( ) function This function concatenates (to link together) the source string at the end of the target string. It appends one string to another. The syntax of this function is strcat(destination, source) Strcmp( ) function This function compares two strings to find out whether they are same or not. The two strings are compared character by character until there is a mismatch or end of the string, which indicates similar strings. This function returns a value zero if both strings are identical. The syntax of this function is : strcmp( string 1, string 2) What is a Function? Give the types of function. A function is a self-contained program segment that carries out some specific, well-defined task. Functions are basically used when there are tasks that are to be performed in exactly the same way again and again. A function contains within it some statements to be performed. These intended action can be accessed anywhere at anytime of the program by just calling the function name. In C, each program contains atleast one function named main function. This function is necessary in any of the C program because the execution of the program begins with it. It is not defined that what number of functions can be included in a C program, it could be any number. A pair of parenthesis follows function names. Functions can be classified as: Library functions These are the functions which are required regularly in each program. These functions are stored in a library. These are the standard functions. Library functions, that are functionally similar, are usually grouped together in separate files called header files. Like library functions printf( ), scanf( ) are included in header file stdio.h, where the suffix h is for header file which indicates that it is to be included at the beginning of the program using pre-processor directive #include. Similarly mathematical functions are in file named math.h etc. User-defined functions All your requirements for developing a program cannot be forseen by the manufacturer of your C development kit. Only the commonly used functions are provided with the libraries in the form of pre-defined functions. If you have any typical requirement and dont find any library function for the same, you can also make your own function and use it. You can also store it into separate file for others or for your own later use. How do you declare a function? Before, making use of function it is necessary to declare a function. Function includes the name of the function, the list of arguments the function may need and type of data the function is expected to return. Every function is made for specific task to perform. To carry out the task it may need some inputs from you, these inputs are fed to the function through what is known as arguments. If a function does not need any such information and is capable of meeting its requirements on its own, then the argument list may be

16 omitted. Since the function is required to do some task and many time it is required that the function return the result or output of the task performed. The type of data the function is returning is also specified. Return type can be any inbuilt data type like int, char, float etc. or it can be user defined types as structures. Syntax for declaring a function is as follows: Return type function name (argument list); For example, the declaration of the function that is required to add two integers and to return the result of addition can be written as: int add (int, int); The declaration starts with the return type. Here the result returned will be obviously of type int that is why the return type of the function is given int. next comes the function name (here add). Name of the function should be given with care. It should reflect the task it is going to perform. Here since the function is required to perform addition of two integers, the name of the function is given add. Next in parenthesis are given two declarations. As you see, you can skip the name of the variables while giving the prototype of the function if you wish you specify the names also. If you specify they are not necessarily same as that was used in call function. All declarations of variables should be separated by comma even if they are so same type. Here as the function requires integers to operate on its own you can leave the parenthesis blank. For functions, you are making your own; you have to specify this type prototype for that particular function. If you are using any library define function, like printf, scanf, etc., then you have to include relate header file to your source code, using #include (e.g. #include<stdio.h>). Header file contains the declarations for library-defined functions. How do you call a function? When you wan to name a particular function you need to call that particular function through its name. While calling you have to supply required arguments (also known as parameters) to the function. If the function is expected to return something, you should provide a variable for storing the result returned by the function. However it is not mandatory to store the value return from the function. You call a function from inside another function only and not from outside any function. Example for calling a function is as below: int add (int, int); /* function declaration*/ int a, b, res; scanf(%d %d, &a, &b); res = add (a, b); /* function call */ How do you define a function? Once you have declared the function and called it in another function, this much activity is enough for the compiler. Your program will be compiled without any error. But when the linker (a program that makes necessary changes in your object code to be able to link with the actual function) starts its works, it needs the actual program or the instruction that forms the body of the function. For library defined or pre-defined functions, the definition are contained in special. Library files, which the linker automatically finds and binds with your object code. For user-defined functions, the functions definition has to be supplied by you. Definition of such functions can be given as you have been giving for the main function. There are their main parts of the functions, viz. return type, name of the function and the argument list. For example, the following example shows all stages you must follow to work with functions: int input( ); /* declaration of the function */ main( ) { int i; i = input( ); /* a function call */ printf(\n%d, i); } int input( ); /* function definition */ { int x;

17 scanf(%d,&x); return x; } As you can see the definition of the function input begins with the return type that means the type of data to be returned from the function. In this case it is an integer so the return specified is int. Next comes the name of the function, input. In the last number of arguments are given in the function brackets. In the particular case, the function inputs do not require any data from the caller function (main). So the brackets are left empty. Note that the data returned by the function is done with the help of statement called return. Why do we use functions? The major advantages of using functions are as follows: 1) Efficiency of maintenance of code The code written as the body of function makes the task simpler. As it makes program writing easier by dividing the operation of a program into subprogram called functions. Separating the code into modular functions makes the program easier to design. 2) Ease to understanding The use of functions makes the program understood as each operation performed is placed in a different functions. So, it can also be written or checked independently 3) Elimination of redundancy of code This is the major advantage of functions , as we do not have to rewrite the code again and again to perform same type of task. For e.g., if we have to calculate the net salary of employees the process of calculation is same so we write the code only once. This process in our function and the problem of writing the code again and again will be eliminated. 4) Reusability of code Function once defined can be used any number of times just by calling them by their name. Thus reusing the code once written is another major advantage of function .

How do you pass value between functions? While declaring functions you can pass some arguments to it. These arguments are also Called parameters . Arguments represent information being passed between the functions. Any number of arguments can be passed to a function. Arguments passed to function from the called function are just name of the variable that the calling function have. These are called actual arguments .To receive the values passed by the caller function, the called function must be declare same types of variable in the brackets just after the function name. In this context the variables are known as formals arguments. The variable names between the actual and the formal arguments may differ, but the type and /or order in which they are displayed and the number of actual and formal arguments must always be the same. If they differ, the program will display an error while compiled. For e.g. , to create an add function, that performs the addition operation the function could be written as below: void main (void) { int add(int a, int b); int a,b,res; printf(enter two integers:); scanf(%d %d,&a,&b); res=add(a,b); printf(the addition of %d and %d is %d,a,b,res); } add(int x,int y) { int sum; sum= x+y;

18 return(sum); } In the above example, you can see that function has declared as to return an integer value by mentioning its data type before its name while declaring. To parameters or arguments of data type integer with variable names a & b are passed. While defining the functions add, again the same data types as parameter are passed. In this a & b are actual arguments where x & y are formal arguments. The value of a gets assigned to x and the value of b to y. This also makes clears that the order of parameters does matter i.e., first variable while declaring, assigns the value to the first variable while defining. Thus, if we have written add (int y, int x) while defining, the value of a would had been assigned to y and not to x. It is also necessary that value being passed back must be of the same type as specified in the declaration. What are Storage Classes? Classify them. Both data type and storage class can classify variables. The storage class specifies the portion of the program within which the variables are recognized. Thus, storage class identifies the scope of the variable. All variables have certain default storage classes even though it is not mentioned. All the variables are stored basically in two location of the computer: memory and CPU registers. It is the storage class that determines in which of these two locations is the value of the variable to be stored. The functions of storage class are: 1) It identifies the place for storage of variable, whether it is local or global. 2) It identifies so to how long the variable would exist. This means when the called function returns, the variables declared in that function may or may not lose their values. 3) Whenever a variable is declared but not initialized it is the storage class that does the initialization of the variable i.e. it gives a default initial value to the variable. In C storage classes are classified into four types: (a) Automatic storage class The variables defined in automatic storage class are always declared within a function and have a local scope i.e. can be used only within that function where they are declared. Thus, variables defined as automatic storage class are independent of one another so they can be of same name within different functions. By default, any variable defined in a function is interpreted as an automatic storage class unless it is specified. The features of automatic storage class variables are as under: i. It is stored in memory. ii. Any value can be assigned to a variable when declared and this value is called a garbage value. This is done only when the user does not initialize the variable with some specific value. iii. The scope of these variables is local to the block in which they are defined. iv. The life of a variable is till the control is in the block. As soon as the control is out of the block, the value of the variable is lost. (b) Static storage class The variables defined in static storage class have the same scope as that of automatic storage class i.e. they are local to the function in which it is defined. They cannot be accessed outside the function where they arte declared. These variables are defined in the same manner as automatic except that the variable declaration must begin within the key word static. The features of static storage class variables are as under: i. These variables are stored in memory. ii. The variable declared is initialized by a default value 0, if not initialized by the user. iii. The scope of the variable is local to the block in which it is defined. iv. Unlike automatic variables, static variables retain their value throughout the life of their program. Thus, if a function is existed and reentered later, static variable retain their value. (c) Register storage class The variables defined in register storage class are also local to the function in which they are declared i.e. they have local scope. These cannot be used in another function if declared in

19 some specific function. These are also declared in the same way as automatic or static but are declared by using the keyword register. The feature of register storage class variables are as: i. These variables are stored in CPU registers. A value stored in CPU registers can be accesses faster than that stored in memory. ii. These variables are assigned any garbage value when declared. iii. These variables cannot be accessed out of the function in which they arte defined. This means that they have local scope. iv. These variables persist the value until the control remains in the block where they are defined. As soon as the control is out, life of the value is ended. Loop variables are the most frequently used as register storage class variables. When we declare a variable as register, this means that these are stored directly into the register, which performs operations. Unlike, memory there is no need to fetch the variables from register, as they are stored there it self. In spite of this advantage a limit of storing variables as register is that if the CPU register are busy performing some other operations, then the variable stored in the register would not get priority but will be treated as an automatic storage class variable. Another disadvantage is that it does not support all types of variables like float, double etc. As they require a large storing capacity. (d) External storage class The variables defined in external storage class do not have a local scope but a global scope. These variables persist the same value from functions to functions. They can be accessed in any of the function. These variables are declared outside of all functions, and can be made available to all functions that need to use them. The features of external storage class are as follows: i. These variables are stored in the memory of computer. ii. By default, the initial value of the variable is set to zero when declared, if the user does not initialize it. iii. The scope of the variable is global. These variables are also called External variables as they can be accessed in any of the function. a variable declared globally as an advantage as if a value is assigned to it in one function, this value can be used within another function that access it. iv. These are available, till the programs execution does not end. What are Unions? Unions, like structures store within them different data types. The only difference between the two is that members within a union share the same storage area within the computers memory, whereas each member within the structure has its own unique storage area. Thus, unions conserve memory. The syntax for unions is identical to that for structures, except that the keyword struct is replaced with keyword union. The general format of defining Unions is : Union Unions-name { member 1; member 2; member n; }; where union is the keyword, union-name is the name that identifies the union and members are the variables that may be of different data types. A union can contain as many members as desired, of any type, but it allocates only enough memory to hold the largest member. The difference between the structure and union is viewed in the memory allocation. Differentiate between arrays and structures. There are two important distinctions between arrays and structures. To start with, the elements of an array must all have the same type. In the structure, the components or fields may have different data types. Next, a component of an array is referred to by its position in the array whereas each component of a structure

20 has a unique name. Structure and arrays are similar in that both must be defined with a finite number of components. Explain the declaration of Structures. In C, collection of different types of data can be grouped to form a structure. When this is done, the entire collection can be referred to by a structure name. In addition, the individual components which are called fields or members can be accessed and processed separately. A structure is declared in the following way: struct < structure-name> { structure element 1; structure element 2; structure element 3; .. .. }; Memory allocated is according to the structure elements, like, if you have one structure element as int, other as char and third as float, 7 bytes would be fixed in memory for such structure i.e. 2 for int, 1 for char, and 4 for float, which equals 7 bytes. These bytes are always in adjacent memory locations. For example, we can make a structure of employee, which consists of name, address, and salary of the employee in one group. main( ) { struct employee { char name[10]; char address[25]; float salary; }; } We define structure by starting with keyword struct, then giving the structure-name. This is followed by the body of the structure within, which we define the members of the structure. Each member of its structure though must have its own unique name. Accessing structure elements: The members of the structure are not assigned any place in memory. On declaring a variable, the members of the structure represent locations in the memory. Thus, you need to declare a variable after you complete your structure declaration. Thus, the above program can be rewritten as: struct employee { char name[10]; char address[25]; float salary; }e1; Else, we can declare a variable like we did with inbuilt data types as: Struct employee e1; As arrays are accessed by their index number, the dot operator accesses the members of the structures i.e. Structure-variable.member-varaible Thus, to access the three members of structure employee, we say: e1.name e1.address e1.salary To assign value we write as follows: Strcpy(e1.name,Tom);

21 Strcpy(e1.address,12/2 New York); e1.salary = 500215; How can an entire structure be passed to a function? We can pass an individual structure element or the entire structure to function by illustrating the following example: main( ) { struct employee { char name[10]; char address[25]; float salary; }; void emp(char s, char *, float); struct employee e1 = {Tom,15/2 New York, 500215}; emp(e1.name, e1.salary); } void emp(char s, char *, float u) { printf(%s%s%f, s,t,u); } The output of the above program would be Tom 15/2 New York 500215 In the above program, we have declared name and address as arrys in the structure employee. Therefore, we call the function emp( ) by the statement : emp(e1.name, e1.address, e1.salary) The example is passing the address of the variable name and address but not passing the value of salary. Thus, there is a mixed call i.e. call by reference as well as a call by value. To pass an individual element would become a tedious task as the number of variables in a structure is increased. So the method to pass the whole structure in a function would be the best way to solve this problem. But before you pass structure in a function it is necessary to declare the structure before main as the function emp( ) would not know the structure. Thus, the structure is declared before the main function. for example, the above program can be done in this way: Struct employee { char name[10]; char address[25]; float salary; }; main( ) { void emp(struct employee); struct employee e1 = {Tom, 15/2 New York, 500215}; emp(e1); } void emp(struct employee e1) { printf(%s%s%f, e1.name, e1.address, e1.salary); } In other words, structure is declared global so that it becomes known to all functions in the program.

22 What do you understand by pointers? A pointer is a variable which holds the memory address of another variable. Sometimes, only with the pointer the complex data type can be declared and accessed in an easy way. The pointer has the following advantages: i. It provides functions which can be modify their calling arguments. ii. It supports dynamic allocation routines. iii. It improves the efficiency by certain routines. A pointer contains a memory address. Most commonly, this address is the location of another variable where it has been stored in memory. If one variable contains the address of another variable, then the first variable is said to point to the second. Sometimes, the pointer is the only technique to represent and to access the complex data structure in an easy way. In C, the pointers are distinct such as integer pointer, floating point number pointer, character pointer etc. The pointer variable consists of two parts such as pointer operator and address operator. The main reasons to use pointers are: i. To return more than value from a function. ii. To pass arrays and strings more conveniently from one function to another. iii. To manipulate arrays more easily by moving pointers to them, instead of moving the arrays themselves. iv. To create complex data structures. v. To communicate information about the memory.

How do you declare a pointer variable? A variable is declared as a pointer by accomplishing it with an asterisk (*). For example, int *a; This indicates that a variable a has been declared as a pointer, which will hold the address of an integer type of data. Pointer variables are named in the same way as any other variable. When a variable is declared as a pointer, it does not contain any value. Explain the working of dereferencing operators (& and *). The operator & is used to specify address of the variable. The operator * is used for retrieving the value stored at a particular address. Whenever you declare a variable int a = 10; the computer automatically assigns memory for this data item. This data item can be accessed if you know the address of the memory cell where the value of this data item is stored. Therefore, when you say &a this would return the address of the variable a and if we simply say a this would return the value of the variable a. Now, when we want to access the value of a particular variable by calling its address, we write the expression *(&a), this means the value of a variable a. For example, main( ) { int a = 10; printf(Address of a = %d, &a); printf(Value of a = %d, *(&a)); printf(Value of a = %d, a); The output of the above program would be: Address of a = 4002 Value of a = 10 Value of a = 10

23 How can one assign value to pointers? The & operator when used as a prefix returns the address of the variable. When you need to assign this address to some other variable you need to write variable name = &(another variable name) i.e., b = &a; This expression assigns address of a variable a to variable b. This variable b would be kept at some other memory location example and should be defined as a pointer like : int *b; Variable name Values Memory location a 10 4002 b 4002 6008

Thus, you can see that the address of a is stored in b which itself is stored at another location i.e. 6008. You need to declare the variable b before you use it. But, as this would not be an ordinary variable but a variable containing the address of some other variable so this would be declared as a pointer, which points to some others variable address. As, int *b; Thus, this expression means that if printed, it would display the value of the address of the variable it points i.e., 4002 because it points to location 4002 which consists of value 10. Show how pointers are related to arrays. Arrays are internally stored as pointers. The elements of an array can be accessed efficiently by using a pointer. For example, main( ) { int arr[5] = {10,20,30,40,50}; int i, *p; p = &arr[0]; for(i = 0; i < 5; i + +) { printf(%d - %d, p,*p); p+ +; } } The output of the above program will be: 4000 10 4002 20 4004 30 4006 40 4008 50 Thus, the address of the first array element can be expressed as either &arr[0] or simply arr. Explain how pointers are passed to functions. Pointers are often passed to a function as arguments. This allows data item within the calling portion of the program to be accessed by the information. It can be altered within the function and returned in the altered form to the calling program. The process used for printing the address of a variable can also be used to access the address of a function. For example, main( ) { int message( ); printf(Address of the function message is %d, message); message( ) {

24 printf(how are you); } This program would display the address where the function is stored. If we want this address to be pointed, we could have declared a pointer. Suppose int(*a)( ); and then by writing a = &display or a =display where display is a function name, we can make a pointer to point it to a function. Therefore, instead of calling a function by its name you can call the function through this function also as: (*a)( ); Call by reference When we pass pointers to functions we say that functions are called by reference rather than value. in call by reference, addresses of the arguments are supplied rather than their value. these addresses are then used by the called function to access the argument variable. Steps involved for using pointers in a function are: 1. Pass address of the variable using the ampersand (&). 2. Declare the variables as pointer within function. 3. Refer to the values contained in memory location by asterisk (*). For example, void fun(int *); main( ) { int i = 10; printf(\n%d,i); /* i will be 10 here */ fun(&i); printf(\n%d,i); /* i will be 30 here */ } void fun(int *p) { *p = 30; } Here, we can see the address of variable i is passed to the function named fun using ampersand. While receiving the variable, p is declared as pointer to int in fun. In fun, the value of i is accessed using asterisk(*). Thus, after function call the value of i printed will be 30. Functions returning pointers The way functions return data type, similarly, a function can return a pointer. To make this possible we had to declare the function as a pointer, example, Int display( ); /* function declaration as returning pointer */ For example, to find the greater of 2 nos. main( ) { int a,b, *c; int *greater(int, int); printf(enter two nos); scanf(%d%d, &a,&b); c = greater(a,b); printf(greater number is %d, *c); } int *greater(int i, int j) { int *p,*q; p = &i; q = &j; if(*p >= *q) return (p); else return(q);

25 } In the above program, when you pass the values of a and b to i and j, we assign their address to p and q and then check for the greater by using pointers. The function returns the pointer i.e., the address of the greater number and then display its value. Explain how pointers can function with another pointer. A pointer contains the address of the data item pointed to, by it. This data item that is pointed to may be a pointer itself i.e., it can contain the address of another data item. Thus, a pointer can point to another pointer, which in turn points to a data item. Accessing data item from the given pointer requires two levels of indirection i.e.(* *). For example, int *b; int **c; a b c 10 4002 7024 What happens is that b stores the address of a. Thus, if we print *b it would give the value of a i.e. 10, whereas c contains the address of b which itself is a pointer to a. This is what is called pointer to pointer. Thus we say printf(%d, **c); Output will again be 10. 4002 6008 6008

You might also like