C BOOKnew
C BOOKnew
EMBEDDED C
CONTENTS Ch.No. Index Page No.
1 1 1 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 4 5 5 6 6 6 7 7 7 11 16 16 16 16 17 17
1. Constants, Variables Data Types 1.1 Introduction 1.2 Character Set 1.2.1 Letters 1.2.2 Digits 1.2.3 Special Characters 1.2.4 White Spaces 1.3 C Tokens 1.3.1 Keywords 1.3.2 Identifiers 1.3.3 Constants 1.3.3.1 Integer Constants 1.3.3.2 Real Constants 1.3.3.3 Single Character Constants 1.3.3.4 String Constants 1.3.3.5 Backslash Character Constants 1.4 Variables 1.4.1 Definition 1.4.2 Rules for Defining Variables 1.5 Data Types 1.5.1 Introduction 1.5.2 Integer Types 1.5.3 Floating Point Types 1.5.4 Character Types 1.6 Declaration of Variables 1.6.1 User-Defined Type Declaration 1.7 Storage Class Exercise Workshop 2. Operators 2.1 Introduction 2.2 Operators of C 2.2.1 Arithmetic Operators 2.2.1.1 Integer Arithmetic 2.2.1.2 Real Arithmetic
2.2.1.3 Mixed-Mode Arithmetic 2.2.2 Relational Operators 2.2.3 Logical Operators 2.2.4 Assignment Operators 2.2.5 Increment and Decrement Operators 2.2.6 Conditional Operator 2.2.7 Bitwise Operators 2.2.8 Special Operators 2.2.8.1 The Comma Operator 2.2.8.2 The Size of Operator 2.2.9 Hierarchy of Operations Exercise Workshop
17 18 18 19 19 20 20 22 23 23 23 24
3. Control Structure Introduction 3.2 Branching The If Statement 3.2.1 Simple If Statement 3.2.2 The If....Else Statement 3.2.3 Nested If...Else Statement 3.2.4 The Else If Ladder 3.3 Switch Case Statement 3.4 The Conditional Operator 3.5 Go to Statement Workshop 4. Looping 4.1 4.2 4.3 4.4 4.5 4.6 Exercise Workshop
27 27 28 28 30 31 32 34 37 37
Introduction The While Statement The Do...While Statement The For Loop The Break Statement The Continue Statement
41 41 41 42 43 44 45 48
5. Pointers and Functions 5.1 Introduction 5.2 Passing value between functions
53 53 56
5.3 Calling Convention 5.4 Advanced Features of Functions 5.5 An Introduction to Pointers Exercise workshop 6. Arrays 6.1 Introduction 6.2 One Dimensional Array 6.2.1 Declaration of Arrays 6.2.2 Initialization of Arrays 6.2.3 Function and Arrays 6.3 Two-Dimensional Arrays 6.4 Multidimensional Array Exercise Workshop 7. Strings 7.1 Introduction 7.2 Pointers and Strings 7.3 Standard Library functions and Strings 7.4 Two dimensional array of characters 7.5 Array of pointers to strings 7.6 Limitations of Array of pointers to strings Exercise Workshop 8. Structures 8.1 Introduction 8.2 Declaring with structures 8.3 Structure elements are stored 8.4 Array of structures 8.5 Uses of Structures Exercise
57 57 58 65
73 73 73 73 73 74 75 80 83
87 87 88 89 91 92 94 97
C Language
(Left parenthesis | Vertical Bar ) Right parentheses / Slash [Left bracket \ Back slash ] Right bracket ~ Tilde {Left brace _ Underscore } Right brace $ Dollar sign # Number sign % Percent sign
1
ADVETECH PVT LTD Diploma in Embedded system design
C Language
1.2.4 White Spaces Blank Space Horizontal Tab Carriage Return New Line Form Feed
1.3 C TOKENS
In C programs, the smallest individual words and punctuation marks are known as tokens. In c program the smallest individual units are known as C tokens and has six types of tokens and they are shown below
1.3.1 KEYWORDS
Every C word is classified as either a keyword or an identifier. All keywords have fixed meanings and these meanings cannot be changed. Only lower case is allowed in keywords. There are 32 keywords available in c, listed below
C Language
auto
float switch typedef short signed size of static
1.3.2 IDENTIFIERS
Identifiers refer to the names of variables, functions and arrays. They are user-defined names and consist of a sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted. The underscore character is also permitted in identifiers.
1.3.3 CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a Program. CONSTANTS
Numeric constants
Character constants
Integer Constants
character constants
String constants
C Language
Decimal Constant Decimal integer consist of set of digits, 0 through 9, preceded by an optional + or - sign E.g.: 123,-321 etc. Note: Embedded spaces, commas and non-digit characters are not permitted between digits. E.g.: 1) 15 750 2) $1000 Octal Constant An octal integer constant consists of any combination of digits from the set 0 through 7, with a leading 0. E.g.: 1) 037 2) 0435 Hexadecimal Constant A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They may also include alphabets A through F or a through f. E.g.: 1) 0X2 2) 0x9F 3) 0Xbcd
C Language
1.3.3.5 Backslash Character Constants C supports special backslash character constants that are used in output functions. These character combinations are known as escape sequences. Constant Meaning \a audible alert \b backspace \f form feed \n new line \0 null \v vertical tab \t horizontal tab \r carriage return \? Question mark \\ backslash
1.4 VARIABLES
1.4.1 Definition: A variable is a data name that may be used to store a data value. A variable may take different values at different times of execution and may be chosen by the programmer in a meaningful way. It may consist of letters, digits and underscore character. E.g.: int salary; ch67, time_12 1.4.2 Rules for defining variables: They must begin with a letter. Some systems permit underscore as the first character. ANSI standard recognizes a length of 31 characters. However, the length should not be normally more than eight characters. Uppercase and lowercase are significant. The variable name should not be a keyword. White space is not allowed.
C Language
INT
CHAR
FLOAT
C Language
E.g.: auto int x; auto int y; Following program shows how an automatic storage class variable is declared, and the fact that if the variable is not initialized it contains a garbage value. Example Code: void main( ) { auto int i, j ; printf ( "\n%d %d", i, j ) ; } The output of the above program could be... 1211 221 Where, 1211 and 221 are garbage values of i and j. When you run this program you may get different values, since garbage values are unpredictable Note: The keyword for this storage class is auto, and not automatic.
7
C Language
E.g.: static int x; static int y; Following program shows how a static storage class variable is declared, Example Code: void main( ) { static int i, j ; printf ( "\n%d %d", i, j ) ; } The output of the above program could be... 0 static variable gets automatically initialized to zero Note: The keyword for this storage class is static. Compare the two programs and their output given to understand the difference between the automatic and static storage classes.
C Language
main() { increment(); increment(); increment(); } increment(); { auto int i=0; printf(%d,i); i=i+1; } Output 1 1 1
main() { increment(); increment(); increment(); } increment(); { static int i=0; printf(%d,i); i=i+1; } Output 1 2 3
In the above example, when variable i is auto, each time increment ( ) is called it is reinitialized to one. When the function terminates, i vanishes and its new value of 2 is lost. The result i is initialized to 1 every time. On the other hand, if static, it is initialized to 1 only once. It is never initialized again. During the first call to increment ( ), i is incremented to 2. Because static, this value persists. The next time increment ( ) is called, i is not re-initialized to 1; on the contrary its old value 2 is still available. This current value of i (i.e. 2) gets printed and then i = i + 1 adds 1 to i to get a value of 3. When increment ( ) is called the third time, the current value of i (i.e. 3) gets printed and once again i is incremented.
Memory Zero Global As long as the program execution doesnt come to an end.
E.g.: int number; Float length = 7.5; Following program shows how an extern storage class variable is declared, Example Code:
9
C Language
int i ; main( ) { printf ( "\n i = %d", i ) ; increment( ) ; increment( ) ; decrement( ) ; decrement( ) ; } increment( ) { i=i+1; printf ( "\non incrementing i = %d", i ) ; } decrement( ) { i = i - 1; printf ( "\non decrementing i = %d", i ) ; } The output would be: i=0 on incrementing i = 1 on incrementing i = 2 on decrementing i = 1 on decrementing i = 0 As is obvious from the above output, the value of i is available to the functions increment ( ) and decrement ( ) since i has been declared outside all functions. Note: The keyword for this storage class is extern.
10
C Language
Scope Life
Local to the block in which the variable is defined. Till the control remains within the block which the variable is defined.
E.g. register int count; Following program shows how a register storage class variable is declared, main( ) { register int i ; for ( i = 1 ; i <= 10 ; i++ ) printf ( "\n%d", i ) ; } We have declared the storage class of i as register, we cannot say for sure that the value of i would be stored in a CPU register. This is because the numbers of CPU registers are limited, and the variable works as if its storage class is auto. The keyword for this storage class is reg, not as register.
EXERCISE:
1. Which of the following are invalid variable names and why? BASICSALARY _basic basic-hra #MEAN group. 422 Population in 2006 over time mindovermatter FLOAT hELLO queue. teamsvictory Plot # 3 2015_DDay
11
C Language
2. What would be the output of the following programs? (a) main( ) { printf ( "nn \n\n nn\n" ) ; printf ( "nn /n/n nn/n" ) ; } (b) main( ) { int a, b ; printf ( "Enter values of a and b" ) ; scanf ( " %d %d ", &a, &b ) ; printf ( "a = %d b = %d", a, b ) ; } main( ) { int p, q ; printf ( "Enter values of p and q" ) ; scanf ( " %d %d ", &p,&q ) ; printf ( "p = %d q =%d", p, q ) ; }
(c)
C INTERVIEW QUESTIONS:
1. What is the function of c? main() function is essential in c programming language. User defined function are those function written by the user. These functions are called user defined function. Inbuilt functions are predefined in the c-language itself main function has three parameters: 1.Environment vector 2.Argument counter 3.Argument vector Function those we write in c program performs one or more specific tasks. main function calls the function and given authority of execution. main function passes control to the userdefined function. Then execution gets started. After executing the function the control is transferred back to the main function.
12
C Language
2. Is C is platform dependent or independent? How and why? Major issue behind designing C language is that it is a small, portable programming language. It is used to implement an operating system. In past time C is a powerful tool for writing all types of program and has mechanism to achieve all most programming goals. So, we can say that C is platform dependent. 3. What are the uses of the keyword static? This simple question is rarely answered completely. Static has three distinct uses in C: A variable declared static within the body of a function maintains its value between function invocations. A variable declared static within a module, (but outside the body of a function) is accessible by all functions within that module. It is not accessible by functions within any other module. That is, it is a localized global Functions declared static within a module may only be called by other functions within that module. That is, the scope of the function is localized to the module within which it is declared 4. What are the different storage classes in C? C has three types of storage: automatic, static and allocated. Variable having block scope and without static specifier have automatic storage duration. Variables with block scope, and with static specifier have static scope. Global variables (i.e., file scope) with or without the static specifier also have static scope. Memory obtained from calls to malloc(), alloc() or realloc() belongs to allocated storage class. 5. What are advantages and disadvantages of external storage class? Advantages of external storage class 1) Persistent storage of a variable retains the latest value 2) The value is globally available Disadvantages of external storage class 1) The storage for an external variable exists even when the variable is not needed 2) The side effect may produce surprising output 3) Modification of the program is difficult 4) Generality of a program is affected.
6. Can static variables be declared in a header file? You cant declare a static variable without defining it as well (this is because the storage class modifiers static and extern are mutually exclusive). A static variable can be defined in a header
13
C Language
file, but this would cause each source file that included the header file to have its own private copy of the variable, which is probably not what was intended. 7. What is the difference between "printf (...)" and "sprintf (...)"? sprintf (...) writes data to the character array whereas printf (...) writes data to the standard output device. 8. What is the difference between declaring a variable and defining a variable? Declaring a variable means describing its type to the compiler but not allocating any space for it. Defining a variable means declaring it and also allocating space to hold the variable. You can also initialize a variable at the time it is defined. Here is a declaration of a variable and a structure, and two variable definitions, one with initialization: extern int decl1; /* this is a declaration */ struct decl2 { int member; }; /* this just declares the type--no variable mentioned */ int def1 = 8; /* this is a definition */ int def2; /* this is a definition */ 9. What is the difference between compile time error and run time error? Some main differences between compiler time error and run time error are given below: 1. Compile time error are semantic and syntax error. Where Run time errors are memory allocation error e.g. segmentation faults. 2. Compile time errors come because of improper Syntax. where in java Run time Errors are considered as exceptions. Run time errors are logical errors. 3. Compile time errors are handled by compiler. Where Run time errors are handled by programmers. 10. What are enumerations? Enumeration is a kind of type. It is used to hold the group of cost values that are given by programmer. After defining we can use it like integer type. E.g. enum off, on; here, off and on are 2 integer constants. These are called enumerators. By default value assign to enumerator are off. 11. How to differentiate local memory and global memory? Local and global memory allocation is applicable with Intel 80x86 CPUs. Some main difference between local and global variables are given below: 1. Using local memory allocation we can access the data of the default memory segment, where as with global memory allocation we can access the default data, located outside the segment, usually in its own segment.
14
C Language
2. If our program is a small or medium model program, the default memory pool is local, where as if our program uses the large or compact memory model, the default memory pool is global. WORKSHOP 1. 2. 3. 4. 5. 6. 7. Read a bill no : print its next 2 bill numbers. Read two nos : Swap them and print Read miles: Print in Kilometers (5 miles=8 kms) Given total months, find out the no of years and months. Given year and months, find out the months. Given opening stock, purchase qty and sales qty find out the stock of the item. Given annual premium and no of years, calculate the total amount paid.
15
C Language
2-Operators
2. OPERATORS
2.1 INTRODUCTION In this lesson, we are going to learn about the various operators of C language that include among others arithmetic, relational and logical operators. Arithmetic operators Relational operators Logical, assignment operators Increment, decrement, conditional operators Bitwise and special operators.
2.2 OPERATORS OF C
C supports a rich set of operators. Operators are used in programs to manipulate data and variables. They usually form a part of the mathematical of logical expressions. C operators are classified into a number of categories. They include: 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operators 5. Increment and Decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators
16
C Language
2-Operators
17
C Language
2-Operators
(c)
main( ) { int i = 2, j = 3, k, l ; float a, b ; k = i / j * j; l = j / i * i; a = i / j * j; b = j / i * i; printf ( "%d %d %f %f", k, l, a, b ) ; } The output is 0 2 0.000000 2.000000 (d) main( ) { int a = 5, b = 2 ; int c ; c=a%b; printf ( "%d", c ) ; } The output of c =1
C Language
2-Operators
|| (logical OR) ! (logical NOT) E.g.: o if (age>55 && salary<1000) o if (number<0 || number>100) This relational operator and logical operator are performed with control statements and they are discussed detailed in chapter 3.
Programs for assignment operation (a) main () { int i, king,issac,noteit ; i = i + 1; king = issac * 234 + noteit - 7689 ; 2.2.5 INCREMENT AND DECREMENT OPERATORS
C has two very useful operators that are not generally found in other languages. These are the increment and decrement operator: ++ and -The operator ++ adds 1 to the operands while subtracts 1.It takes the following form: ++m; or m++ --m; or m
19
C Language
2-Operators
Programs for increment/Decrement operation (a) main () { int a=1; clrscr(); printf(\n%d%d%d,a,++a,a++); getch(); }
The output is 3 3 1
(b)
main () { int a=10; y= --a + --a + --a printf (\n%d%d, y, a); getch(); }
Meaning Bitwise AND Bitwise OR Bitwise XOR Shift left Shift right Ones complement
C Language
2-Operators
(a)
main( ) { int j=0b00000111, k ; printf ( "\n Decimal %d is same as binary ", j ) ; showbits ( j ) ; k = ~j ; printf ( "\n Ones complement of %d is ", j ) ;
showbits ( k ) ;
} } And here is the output of the above program... Decimal 0 is same as binary 00001111 Ones complement of 0 is 11110000 (b) main( ) {
int i = 5225, k ; printf ( "\n Decimal %d is same as binary ", i ) ;
showbits ( i ) ; k = i >>1; printf ( "\n%d right shift %d gives ", i) ; showbits ( k ) ; } The output of the above program would be... Decimal 5225 is same as binary 0001010001101001 5225 right shift 1gives 0000101000110100, equivalent decimal value is 2614. (c) main( ) { int i = 5225, j, k ; printf ( "\nDecimal %d is same as ", i ) ; showbits ( i ) k = i <<1 ; printf ( "\n%d left shift %d gives ", i, j ) ; showbits ( k ) ; }
The output of the above program would be... Decimal 5225 are same as binary 0001010001101001 5225 left shift 1 gives 0010100011010010, equivalent decimal value is 10450.
21
C Language
2-Operators
main( ) { int i = 65, j ; printf ( "\nvalue of i = %d", i ) ; j = i & 32 ; if ( j == 0 ) printf ( "\n and its fifth bit is off" ) ; else printf ( "\n and its fifth bit is on" ) ; j = i & 64 ; if ( j == 0 ) printf ( "\n whereas its sixth bit is off" ) ; else printf ( "\n whereas its sixth bit is on" ) ; } And here is the output... Value of i = 65 and its fifth bit is off whereas its sixth bit is on main( ) { int b = 50 ; b = b ^ 12 ; printf ( "\n%d", b ) ; b = b ^ 12 ; printf ( "\n%d", b ) ; } And here is the output... Value of b=62, b=50 (e)
(d)
C Language
2-Operators
The comma operator can be used to link the related expressions together. A comma linked List of expressions is evaluated left to right and the value of right-most expression is the value of the combined expression. E.g.: value = (x = 10, y = 5, x + y); this statement first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15(i.e., 10+5) to value.
2nd
+-
Addition,subtraction
3rd
Equal to
Determine the hierarchy of operations and evaluate the following expression: i = 3 *2 4 + 4 / 4 + 8 - 2 + 5 / 8 Stepwise evaluation of this expression is shown below: i=2*3/4+4/4+8-2+5/8 i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: * i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: / i = 1 + 1+ 8 - 2 + 5 / 8 operation: / i = 1 + 1 + 8 - 2 + 0 operation: / i = 2 + 8 - 2 + 0 operation: + i = 10 - 2 + 0 operation: + i = 8 + 0 operation : i = 8 operation: +
23
C Language
2-Operators
Note that 6 / 4 give 1 and not 1.5. This so happens because 6 and 4 both are integers and therefore would evaluate to only an integer constant. Similarly 5 / 8 evaluates to zero, since 5 and 8 are integer constants and hence must return an integer value.
EXERCISE: 1. Point out the errors, if any, in the following C statements: (a) int = 314.562 * 150 ; (b) name = Ajay ; (c) varchar = 3 ; (d) 3.14 * r * r * h = vol_of_cyl ; (e) k = ( a * b ) ( c + ( 2.5a + b ) ( d + e ) ; (f) m_inst = rate of interest * amount in rs ; (g) si = principal * rateofinterest * numberofyears / 100 ; (h) area = 3.14 * r ** 2 ; (i) volume = 3.14 * r ^ 2 * h ; (j) k = ( (a * b ) + c ) ( 2.5 * a + b ) ; (k) a = b = 3 = 4 ; (l) date = '2 Mar 04' ; Programs: 1. Rajeshs basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary. 2. If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits. 3. If a five-digit number is input through the keyboard, write a program to reverse the number. 4. Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D. 5. Write a program to calculate simple interest (si=(pnr)/100). C interview questions:
1. Is left-to-right or right-to-left order guaranteed for operator precedence? Answer: The simple answer to this question is neither. The C language does not always evaluate left-to-right or right-to-left. Generally, function calls are evaluated first, followed by complex
24
C Language
2-Operators
expressions and then simple expressions. Additionally, most of todays popular C compilers often rearrange the order in which the expression is evaluated in order to get better optimized code. You therefore should always implicitly define your operator precedence by using parentheses. For example, consider the following expression: a = b + c/d / function_call() * 5 The way this expression is to be evaluated is totally ambiguous, and you probably will not get the results you want. Instead, try writing it by using implicit operator precedence: a = b + (((c/d) / function_call()) * 5) Using this method, you can be assured that your expression will be evaluated properly and that the compiler will not rearrange operators for optimization purposes. 2. What does the modulus operator do? The modulus operator (%) gives the remainder of two divided numbers. For instance, consider the following portion of code: x = 15/7 If x were an integer, the resulting value of x would be 2. However, consider what would happen if you were to apply the modulus operator to the same equation: x = 15%7 The result of this expression would be the remainder of 15 divided by 7, or 1. This is to say that 15 divided by 7 is 2 with a remainder of 1. The modulus operator is commonly used to determine whether one number is evenly divisible into another. 3. Which is unary operator? Increment and decrement operator is also called as unary operator 4. Why increment decrement operator is called as unary operator? Because, it has only one operand a++ 5. What is a modulus operator? What are the restrictions of a modulus operator? A Modulus operator gives the remainder value. The result of x%y is obtained by (x-(x/y)*y). This operator is applied only to integral operands and cannot be applied to float or double. 6. What is the difference between the two operators = and ==? = assignment operator which is used to assign value to the operand. e.g.: a=10; == Equality operator which is used to compare two operands. e.g.: a==b
C Language
2-Operators
let, x = 1. Then answer will be. main() { int x=1,y; y = x++ + ++x; printf("/n%d",y); } Answer: y = 3 8. How to differentiate i++* and *++i? i++* is false representation. *++i->First it increment the value of i, after that is points the value to i. 9. Difference between assignment operator and copy constructor Two major differences between copy constructor and assignment are: (i) Copy constructor doesnt return any value (not even void) whereas assignment operator returns a value. (ii) Copy constructor will be called only when a new object is being instantiated whereas assignment operator is called for an existing object to which a new value is being assigned
26
C Language
3.1 Branching
Branching is the process of choosing the right branch for execution, depending on the result of conditional statement. Branch is the term given to the code executed in sequence as a result of change in the programs flow; the programs flow can be changed by conditional statements in the program.
As mentioned earlier, a decision control instruction can be implemented in C using: (a) The if statement (b) switch case statement (c) The conditional operators (d) goto statement
27
C Language
General Form:
if (test expression) This point of program has two paths to follow, one for the true condition and the other for the false condition.
Flow Chart:
The if statement may be used in different forms depending on the complexity of conditions to be tested. The different forms are, i) simple if statement ii) if....else statement iii) Nested if......else statement iv) else if ladder
General form
if (test expression) { statement-block; } statement x; Here, the statement block may contain a single statement or a group of statements. If the test expression is true then the statement block will be executed; otherwise it will be skipped to the statement x. This can be shown by the following flowchart,
28
C Language
Flowchart
Sample Code: Consider the case when we are asked to write a program for exforsys.com
where users are asked to give ratings on each article; we want to output different messages depending on the ratings given. Messages are as follow: 1 is bad, 2 is average and 3 are good. int rate; printf("Please Enter Rating? 1 for bad, 2 for average and 3 for good \n"); scanf("%d",&rate); if(rate==1) { printf("nit is poor"); } if(rate==2) { printf("nit is average"); } if(rate==3) { printf("nit is good"); }
29
C Language
General Form
if (test expression) { true-block statements; } else { False-block statements; } statement-x; Here, if the test expression is true, then the true-block statements will be executed, otherwise the false-block statements will be executed. In either case, either true block or false block statements will be executed, not both. The general form can be shown by the following flowchart
Flowchart
Sample Code: Imagine the case where we need an input greater than or equal to 5 and
we want to warn the user if they use invalid input (less than 5). int number; printf("Please Enter a number greater than or equal to 5?n");
30
C Language
General Form:
Here, if the condition 1 is false then it skipped to statement 3. But if the condition 1 is true, then it tests condition 2. If condition 2 is true then it executes statement 1 and if false then it executes statement 2. Then the control is transferred to the statement x. This can also be shown by the following flowchart,
31
C Language
Flowchart:
32
C Language
General Form
This construct is known as the else if ladder. The conditions are evaluated from the top, downwards. This can be shown by the following flowchart
Flowchart:
33
C Language
Sample Code:
int num; clrscr(); printf(enter a number below 41); scanf(%d,&num); if(num<=10) printf(the number is between 1-10); else if(num<=20) printf(the number is between 11-20); else if(num<=30) printf(the number is between 21-30); else if(num<=40) printf(the number is between 31-40); else printf(the number is above 40); printf(\n\n program ends); getch(); }
3.3 Switch-case:
The switch-case statement is a multi-way decision statement. Unlike the multiple decisions statement that can be created using if-else, the switch statement evaluates the conditional expression and tests it against numerous constant values. The branch corresponding to the value that the expression matches is taken during the execution. The value of the expressions in a switch-case statement must be an ordinal type i.e. int, char, short, long, etc. float and double are not allowed.
34
C Language
The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.
Flow Chart:
Sample Coding:
Consider the following program: main( ) { int i = 2 ; switch ( i ) { case 1 : printf ( "I am in case 1 \n" ) ; case 2 : printf ( "I am in case 2 \n" ) ; case 3 : printf ( "I am in case 3 \n" ) ; default : printf ( "I am in default \n" ) ; } } The output of this program would be: I am in case 2 I am in case 3
35
C Language
I am in default If you want that only case 2 should get executed, we didnt use break in cases, and here the program below there by using a break statement. Note that there is no need for a break statement after the default, since the control comes out of the switch anyway. main( ) { int i = 2 ; switch ( i ) { case 1 : printf ( "I am in case 1 \n" ) ; break; case 2 : printf ( "I am in case 2 \n" ) ; break; case 3 : printf ( "I am in case 3 \n" ) ; break; default : printf ( "I am in default \n" ) ; } } The output of this program would be: I am in case 2 At times we may want to execute a common set of statements for multiple cases, this can be done as shown in the following example. main( ) { char ch ; printf ( "Enter any of the alphabet a, b, or c " ) ; scanf ( "%c", &ch ) ; switch ( ch ) { case 'a' : case 'A' : printf ( "a as in ashar" ) ; break ; case 'b' : case 'B' : printf ( "b as in brain" ) ;
36
C Language
break ; case 'c' : case 'C' : printf ( "c as in cookie" ) ; break ; default : printf ( "wish you knew what are alphabets" ) ; } } Here, we are making use of the fact that once a case is satisfied the control simply falls through the case till it doesnt encounter a break statement. That is why if an alphabet a is entered the case a is satisfied and since there are no statements to be executed in this case the control automatically reaches the next case i.e. case A and executes all the statements in this case.
3.5 Go to Statement:
C has goto statement but one must ensure not to use too much of goto statement in their program because its functionality is limited and it is only recommended as a last resort if structured solutions are much more complicated.
37
C Language
First let us understand the goto statement, its syntax and functionality. The goto is an unconditional branching statement used to transfer control of the program from one statement to another.
General Form
goto label; label: . Statement; . . . . label: . Statement; goto label; Forward jump backward jump Program: main( ) { int goals ; printf ( "Enter the number of goals scored against India" ) ; scanf ( "%d", &goals ) ; if ( goals <= 5 ) goto sos ; else { printf ( "About time soccer players learnt C\n" ) ; printf ( "and said goodbye! adieu! to soccer" ) ; exit( ) ; /* terminates program execution */ } sos: printf ( "To err is human!" ) ; } And here are two sample runs of the program... Enter the number of goals scored against India 3 To err is human! Enter the number of goals scored against India 7 About time soccer players learnt C and said goodbye! adieu! to soccer
WORKSHOP 1) If-Else Construct 1) Read length & breath: print whether it is square or a rectangular. 2) Read 3 nos; Count the negative numbers and print. 3) Read an applicants age; print whether his age is between 22 nad 28 or not. 4) Read a character; print if it is a vowel or not.
38
C Language
2) Nested-If-Statements Read a no; print if it is a zero, positive or negative number. Read two nos ; print if both are equal. Otherwise print the biggest. Read three nos; print the biggest number. Read an option 1 or 2; if 1 Read a no; Print if it is an odd or even number; If 2 Read a no; print if it is a positive or negative number. 3) If-Else If Statements Read a weekday number[1 to 7]; Print weekdays name. Read a percentage of marks; Geade it. A grade :80-100%, B garde:60-70%, C grade:40-59%, D grade:0-39%. Read a purchase value; Calculate and print the discount amount based on following condition. No discount for purchase less than Rs.1000.00. 2% Discount for purchase upto Rs.2,000.00 5% Discount for purchase upto Rs.5,000.00 8% Discount for purchase above Rs.5000.00
4) Switch Construct Read a month number[1 to 12]; print month name. Read a month number[1 to 12]; print if it is first/second/third/fourth quarter. Read two nos; Display the following menu for selection. Then read the option, and do the appropriate action. a. Add b. Multiply c. Divide d. Do Nothing e. Choose Your Option[1-4]:________
39
C Language
40
C Language
4.Looping
4. Looping
4.1 INTRODUCTION
The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control instruction. There are three methods by way of which we can repeat a part of a program. They are: Using (a) For statement (b) Using a while statement (c) Using a do-while statement
General Form:
while(test-expression) { code to execute }
Flowchart:
Test expression
true
code
false
41
C Language
4.Looping
Sample Code:
Here we will consider the case of repeating the same line of code for 10 times int counter=1; while(counter <=10) { printf("\n Number: %d",counter); counter++; } The output of this program would be: 1 2 3 4 5 6 7 8 9 10
General Form:
do { code to iterate } while(test-expression)
Flow Chart:
code true
Test expression
false 42
C Language
4.Looping
Sample Code:
We will consider a simple menu using do...While this code for the even numbers between 1 and 10. int counter; do { //for(counter=1;counter<=10;counter++) { if(counter%2==0) printf("\n number: %d ",counter); } } while(count<=10); The output of this program would be: 2 4 6 8 10
General Form:
for (control-variable; continuation-condition; increment/decrement-control) { Code to iterate }
Flowchart:
43
C Language
4.Looping
Sample Code:
Consider the case of repeating the same line of code for 10 times. We write the code below. We will consider a simple menu using do...While this code for the even numbers between 1 and 10. int counter; for(counter=1;counter<=10;counter++) { if (counter%2==0) printf("\n number: %d ",counter); } The output of this program would be: 2 4 6 8 10
Flow Chart:
start
code
break code
end
Sample Code:
44
C Language
4.Looping
In this, we will write a program which will escape the loop using break as soon as the number is equal to 2. main( ) { int i = 1 , j = 1; while ( i++ <= 4) { while ( j++ <= 20 ) { if ( j == 15 ) break ; else printf ( "%d %d\n", i, j ) ; } } } In this program when j equals 15, break takes the control outside the inner while only, since it is placed inside the inner while.
Flow Chart:
start
code
continue
code
end
Sample Code:
We will consider the case in which the loop will skip all the even numbers between 1 and 10. main( )
45
C Language
4.Looping
{ int i, j ; for ( i = 1 ; i <= 2 ; i++ ) { for ( j = 1 ; j <= 2 ; j++ ) { if ( i == j ) continue ; printf ( "\n%d %d\n", i, j ) ; } } } The output of the above program would be... 12 21
EXERCISE:
What would be the output of the following programs? (a) main( ) { int i = -4, j, num ; j = ( num < 0 ? 0 : num * num ) ; printf ( "\n%d", j ) ; } (b) main( ) { int k, num = 30 ; k = ( num > 5 ? ( num <= 10 ? 100 : 200 ) : 500 ) ; printf ( "\n%d", num ) ; } (c) main( ) { int j = 4 ; ( !j != 1 ? printf ( "\n Welcome") : printf ( "\n Good Bye") ) ; } (d) main( )
46
C Language
4.Looping
{ int i = 0 ; for ( ; i ; ) printf ( "\n Here is some mail for you" ) ; } (e) main( ) { int i ; for ( i = 1 ; i <= 5 ; i++) printf ( "\n%d", i ) ; } (f) main( ) { int i = 1, j = 1 ; for ( ; ; ) { if ( i > 5 ) break; else j += i ; printf ( "\n%d", j ) ; i += j; } } (g) main( ) { int i ; for ( i = 1 ; i <= 5 ;i++) printf ( "\n %d", i ) ; }
C Language
4.Looping
printf ( "\n%d", i ) ; i++; } (i) main( ) { int i = 1, j = 1 ; for ( ; ; ) { if ( i > 5 ) break; else j += i; printf ( "\n%d", j ) ; i += j; } } (j) main( ) { int i ; for ( i = 1 ; i <= 5 ;); printf ( "\n%c", 65 ) ; i++; }
PROGRAMS 1. Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators. 2. Write a program to find out whether it is an odd number or even number. 3. Write a c program to find the eligibility for vote using if statement 4. Write a c program to find the largest of three numbers using nested if 5. Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not. 6. Write a c program using else if ladder to find the rank of 10 students using their marks 7. Write a program to find the grace marks for a student using switch. The user should enter the class obtained by the student and the number of subjects he has failed in. 8. Write a program to print all prime numbers from 1 to 300. (Hint: Use nested loops, break and continue)
48
C Language
4.Looping
9. Write a program to produce the following output: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 10. Write a program to find the factorial value of any number 11. Write a program to print all prime numbers from 1 to 300. Using nested loops, break and continue 12. Write a program to generate all combinations of 1, 2 and 3 using while loop. 13. Write a program to fill the entire screen with diamond and heart alternatively. The ASCII value for heart is 3 and that of diamond is 4. 14. What would be the output of the following programs? C INTERVIEW QUESTIONS: 1. What is a loop? In looping, a sequence of statements is executed until some conditions for terminating of the loop are satisfied. A program loop contains two parts, body of the loop and control statements. 2. What is the difference between entry-controlled loop and exit-controlled loop? In the entry-controlled loop, the control conditions are tested before the start of the loop execution. If the conditions are not satisfied, then the body of the loop will not be executed. In the case of an exit-controlled loop, the test is performed at the end of the body of loop and therefore the body is executed unconditionally for the first time. 3. What is the difference between a break statement and a continue statement? A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. 4. When is a switch statement better than multiple if statements? A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric type. 5. Why n++ executes faster than n+1? n++ executes faster than n+1 because n++ want only one instruction for execution where n+1 want more one instruction for execution. It (n+1) creates extra memory for adding. Whereas n++ refers to same memory.
49
C Language
4.Looping
6. How many times the below loop will run main() { int i; i = 0; do { --i; printf (%d,i); i++; } while (i >= 0) } Output:Infinite Explanation: In every iteration value of i is decremented and then incremented so remains 0 and hence an Infinite Loop. 7. What would be the output if option = H? switch (option) { case H : printf(Hello); case W : printf(Welcome); case B : printf (Bye); break; } Output:Hello Welcome Bye Explanation : If option = H then the first case is true so Hello gets printed but there is no break statement after this case to come out of the switch statement so the program execute all other case statements also and Hello Welcome Bye gets printed. 8. Suppose a, b, c are integer variables with values 5, 6, 7 respectively. What is the value of the expression? ! ((b + c) > (a + 10)) Output:1 Explanation: 1.! ((b + c) > (a + 10)) 2.!((6 + 7) > (5+10)) 3.!(13 > 15) 13 is less than 15 so it will return False (0 ). 4.!(0). Not of 0 is 1.
50
C Language
4.Looping
WORKSHOP For loop construct: Number series printing 1. Print the number series:0,5,10,15,20,25,30,35,40 2. Print the number series: 2,4,8,16,32,64 3. Print the number of series: 100,90,80,70,60,50,40,30,20,10,0 Loop Construct: Summation 1. Generate Series : 30 24 18 12 6 2. Generate Series : 15 20 25 30 35 40 45 3. Read 10 numbers and print the sum & average. Loop Construct : Conditional 1. Read 10 numbers and print the total even nos and total odd number. 2. Read 2 nos, but keep the biggest no; finally print the biggest no.
Loop Constructs : break & Continue 1. Print the series:1,2,4,8,16,32,.; stop after printing 10 nos. 2. Print the series: 1,2,4,8,16,32,; Stop when reached above 100. 3. Read a no; print if it is prime no or not. While Loop : Pre-determined count 1. Print the series: 2,4,6,8,20 2. Print the series: 1,10,100,1000,10000 3. Print the sum of the series: 1,2,4,8,16,32,1024 While Loops: Undetermined loopGet an option to stop 1. Read n number: Ask the user [y/n] before proceeding to next number. Finall print the sum of all read number. 2. Display the following menu for selection. Then read the option, and do the appropriate action. 3. Add 4. Multiply 5. Stop 6. Choose your option[1-3]
51
C Language
4.Looping
While loops: Undetermined loopDetect a sentinel value to stop 1. Read n numbers; stop reading when zero is input. Finally print the sum of all read numbers. 2. Read age and print; But repeat to ask until an age not lesser that 25 is entered. Do-while loops 1. Print the series 10,9,8,7.1 2. Read n number; Ask the user [1/2] before proceeding to next number. Finally print the sum of all read numbers.
52
C Language
C Language
argentina( ) { printf ( "\nI am in argentina" ) ; } The output of the above program when executed would be as under: I am in main I am in italy I am in brazil I am in argentina Lets illustrate with another example. main( ) { printf ( "\nI am in main" ) ; italy( ) ; printf ( "\nI am finally back in main" ) ; } italy( ) { printf ( "\nI am in italy" ) ; brazil( ) ; printf ( "\nI am back in italy" ) ; } brazil( ) { printf ( "\nI am in brazil" ) ; argentina( ) ; } argentina( ) { printf ( "\nI am in argentina" ) ; } And the output would look like... I am in main I am in italy I am in brazil I am in argentina I am back in italy I am finally back in main 5.1.3. Here, main( ) calls other functions, which in turn call still other functions. Trace carefully the way control passes from one function to another. Since the compiler always begins the
54
C Language
program execution with main( ), every function in a program must be called directly or indirectly by main( ). In other words, the main( ) function drives other functions. Any function can be called from any other function. Even main( ) can be called from other functions. For example, main( ) { message( ) ; } void message( ) { printf ( "\nCan't imagine life without C" ) ; main( ) ; } 5.1.4. A function can be called any number of times. For example, main( ) { message( ) ; message( ) ; } message( ) { printf ( "\nJewel Thief!!" ) ; } 5.1.5. The order in which the functions are defined in a program and the order in which they get called need not necessarily are same. For example, main( ) { message1( ) ; message2( ) ; } message2( ) { printf ( "\nBut the butter was bitter" ) ; } message1( ) { printf ( "\nMary bought some butter" ) ; }
55
C Language
However, it is advisable to define the functions in the same order in which they are called. This makes the program easier to understand. 5.1.6. A function can be called from other function, but a function cannot be defined in another function. main( ) { printf ( "\nI am in main" ) ; void argentina( ) { printf ( "\nI am in argentina" ) ; } } There are basically two types of functions: Library functions Ex. printf( ), scanf( ) etc. User-defined functions Ex. argentina( ), brazil( ) etc. 5.1.7. Why Use Functions Writing functions avoids rewriting the same code over and over. Using functions it becomes easier to write programs and keep track of what they are doing. Separating the code into modular functions also makes the program easier to design and understand.
C Language
calsum ( x, y, z ) { int x, y, z ; int d ; d = x + y + z; return ( d ) ; } And here is the output... Enter any three numbers 10 20 30 Sum = 60
57
C Language
square of a number using a function. The following program segment illustrates how to make square( ) capable of returning a float value. main( ) { float square ( float ) ; float a, b ; printf ( "\nEnter any number " ) ; scanf ( "%f", &a ) ; b = square ( a ) ; printf ( "\nSquare of %f is %f", a, b ) ; } float square ( float x ) { float y ; y=x*x; return ( y ) ; } And here is the output... Enter any number 1.5 Square of 1.5 is 2.250000 Enter any number 2.5 Square of 2.5 is 6.250000
C Language
i
5
65524
We see that the computer has selected memory location 65524 as the place to store the value 3. The location number 65524 is not a number to be relied upon, because some other time the computer may choose a different location for storing the value 3. The important point is, is address in memory is a number. We can print this address number through the following program: main( ) { int i = 3 ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; } The output of the above program would be: Address of i = 65524 Value of i = 3 Look at the first printf( ) statement carefully. & used in this statement is Cs address of operator. The expression &i returns the address of the variable i, which in this case happens to be 65524. Hence it is printed out using %u, which is a format specifier for printing an unsigned integer. We have been using the & operator all the time in the scanf( ) statement. The other pointer operator available in C is *, called value at address operator. It gives the value stored at a particular address. The value at address operator is also called indirection operator. main( ) { int i = 3 ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", *( &i ) ) ; } The output of the above program would be: Address of i = 65524
59
C Language
Value of i = 3 Value of i = 3 The expression &i gives the address of the variable i. This address can be collected in a variable, by saying, j = &i; and since j is a variable that contains the address of i, it is declared as, int *j; this declaration tells the compiler that j will be used to store the address of an integer value. In other words j points to an integer. Here is a program that demonstrates the relationships we have been discussing. main( ) { int i = 3 ; int *j ; j = &i ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nAddress of i = %u", j ) ; printf ( "\nAddress of j = %u", &j ) ; printf ( "\nValue of j = %u", j ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", *( &i ) ) ; printf ( "\nValue of i = %d", *j ) ; } The output of the above program would be: Address of i = 65524 Address of i = 65524 Address of j = 65522 Value of j = 65524 Value of i = 3 Value of i = 3 Value of i = 3 i j
3 5 65524
65524
65526
Pointer, we know is a variable that contains address of another variable. Now this variable itself might be another pointer. Thus, we now have a pointer that contains another pointers address. The following example should make this point clear. main( ) {
60
C Language
int i = 3, *j, **k ; j = &i ; k = &j; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nAddress of i = %u", j ) ; printf ( "\nAddress of i = %u", *k ) ; printf ( "\nAddress of j = %u", &j ) ; printf ( "\nAddress of j = %u", k ) ; printf ( "\nAddress of k = %u", &k ) ; printf ( "\nValue of j = %u", j ) ; printf ( "\nValue of k = %u", k ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", * ( &i ) ) ; printf ( "\nValue of i = %d", *j ) ; printf ( "\nValue of i = %d", **k ) ; } The output of the above program would be: Address of i = 65524 Address of i = 65524 Address of i = 65524 Address of j = 65522 Address of j = 65522 Address of k = 65520 Value of j = 65524 Value of k = 65522 Value of i = 3 Value of i = 3 Value of i = 3 Value of i = 3 i j
3 5 65524
k
65522
65524
65522
65520
Observe how the variables j and k have been declared, int i, *j, **k ; Here, i is an ordinary int, j is a pointer to an int (often called an integer pointer), whereas k is a pointer to an integer pointer. We can extend the above program still further by
61
C Language
creating a pointer to a pointer to an integer pointer. There is no limit on how far can we go on extending this definition.
62
C Language
Example 1: main( ) { int a = 10, b = 20 ; swapr ( &a, &b ) ; printf ( "\na = %d b = %d", a, b ) ; } swapr( int *x, int *y ) { int t ; t = *x; *x = *y; *y = t; } The output of the above program would be: a = 20 b = 10 5.4.2 Call by Value and Call by Reference 1.Call By Values : Values passed
2. Call By Reference : Address passed The first type refers to call by value and the second type refers to call by reference. For instance consider program1 main() { int x=50, y=70; interchange(x,y); printf(x=%d y=%d,x,y); } interchange(x1,y1) int x1,y1; { int z1; z1=x1; x1=y1; y1=z1; printf(x1=%d y1=%d,x1,y1); }
63
C Language
Here the value to function interchange is passed by value. Consider program2 main() { int x=50, y=70; interchange(&x,&y); printf(x=%d y=%d,x,y); } interchange(x1,y1) int *x1,*y1; { int z1; z1=*x1; *x1=*y1; *y1=z1; printf(*x=%d *y=%d,x1,y1); }
5.5.3 Recursion
In C, it is possible for the functions to call themselves. A function is called recursive if a statement within the body of a function calls the same function. Sometimes called circular definition, recursion is thus the process of defining something in terms of itself. Following is the recursive version of the function to calculate the factorial value. main( ) { int a, fact ; printf ( "\nEnter any number " ) ; scanf ( "%d", &a ) ; fact = rec ( a ) ; printf ( "Factorial value = %d", fact ) ; } rec ( int x ) { int f ; if ( x == 1 ) return ( 1 ) ; else f = x * rec ( x - 1 ) ; return ( f ) ; }
64
C Language
And here is the output for four runs of the program Enter any number 1 Factorial value = 1 Enter any number 2 Factorial value = 2 Enter any number 3 Factorial value = 6 Let it be clear that while executing the program there does not exist so many copies of the function rec( ). These have been shown in the figure just to help you keep track of how the control flows during successive recursive calls. from main( ) rec(int x) { int f; if(x==1) return(1) else f=x*rec(x-1); return(f); } rec(int x) { int f; if(x==1) return(1) else f=x*rec(x-1); return(f); }
EXERCISE
What would be the output of the following programs? (a) main( ) { int i = 45, c ; c = multiply ( i * 1000 ) ; printf ( "\n%d", c ) ; } check ( int ch ) { if ( ch >= 40000 ) return ( ch / 10 ) ; else return ( 10 ) ; }
65
C Language
(b) int *call(); void main(){ int *ptr; ptr=call(); clrscr(); printf("%d",*ptr); } int * call(){ int x=25; ++x; return &x; } (c) void main(){ int *ptr; printf("%u\n",ptr); printf("%d",*ptr); }
(d) int *p; int *q= (int *)0; #include<stdio.h> int *r=NULL; What will be output of following c program? (e) #include<string.h> #include<stdio.h> void main(){ char *p; char *q=NULL; strcpy(p,"cquestionbank"); strcpy(q,"cquestionbank"); clrscr(); printf("%s %s",p,q);
66
C Language
getch(); } (f) main( ) { void slogan( ) ; int c = 5 ; c = slogan( ) ; printf ( "\n%d", c ) ; } void slogan( ) { printf ( "\nOnly He men use C!" ) ; } (g) main( ) { int i = 5, j = 2 ; junk ( &i, &j ) ; printf ( "\n%d %d", i, j ) ; } junk ( int *i, int *j ) { *i = *i * *i ; *j = *j * *j ; } (h) main( ) { int i = 4, j = 2 ; junk ( &i, j ) ; printf ( "\n%d %d", i, j ) ; } junk ( int *i, int j ) { *i = *i * *i ; j=j*j; }
67
C Language
(i) main( ) { float a = 13.5 ; float *b, *c ; b = &a ; /* suppose address of a is 1006 */ c=b; printf ( "\n%u %u %u", &a, b, c ) ; printf ( "\n%f %f %f %f %f", a, *(&a), *&a, *b, *c ) ; } (j) main( ) { int i = 0 ; i++ ; if ( i <= 5 ) { printf ( "\nC adds wings to your thoughts" ) ; exit( ) ; main( ) ; } }
PROGRAMS:
1. Write a function to calculate the factorial value of any integer entered through the keyboard. 2. Write a function power (a, b), to calculate the value of a raised to b. 3. Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55 89... 4. Write a function that receives marks received by a student in 3 subjects and returns the average and percentage of these marks. Call this function from main( ) and print the results in main( ). 5. A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number: (1) Without using recursion (2) Using recursion 6. Write a program to find the area and perimeter of the circle.
68
C Language
C INTERVIEW QUESTIONS
1. What is dangling pointer in c? If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem. 2. What is wild pointer in c? Wild pointer: A pointer in c which has not been initialized is known as wild pointer. Example: What will be output of following c program? #include<stdio.h> int main(){ int *ptr; printf("%u\n",ptr); printf("%d",*ptr); return 0;} Output: Any address Garbage value 3. What is NULL pointer in c? Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of segment. Examples of NULL pointer: 1. int *ptr=(char *)0; 2. float *ptr=(float *)0; 3. char *ptr=(char *)0; 4. What is Generic pointer in c? void pointer in c is known as generic pointer. Literal meaning of generic pointer is a pointer which can point to any type of data. Example: void *ptr; Here ptr is generic pointer. 5. What is Far pointer in c programming? The pointer which can point or access whole the residence memory of RAM i.e. which can access all 16 segments is known as far pointer.
69
C Language
6. What is near pointer in c programming? The pointer which can points only 64KB data segment or segment number 8 is known as near pointer. 7. What is huge pointer in c programming? The pointer which can point or access whole the residence memory of RAM i.e. which can access all the 16 segments is known as huge pointer. 8. What is size of void pointer? Size of any type of pointer in c is independent of data type which is pointer is pointing i.e. size of all type of pointer (near) in c is two byte either it is char pointer, double pointer, function pointer or null pointer. void pointer is not exception of this rule and size of void pointer is also two byte. 9. What is difference between uninitialized pointer and null pointer? An uninitialized pointer is a pointer which points unknown memory location while null pointer is pointer which points a null value or base address of segment. 10. What is a const pointer? A const pointer means the pointer which represents the address of one value. So if you declare a pointer inside the function, it doesn't have scope outside the function. If it is also available to the outside function whenever we declare a pointer as const. 11. Declare a pointer which can point printf function in c. int (*ptr)(char const,); 12. What is a pointer variable? A pointer variable is a variable that may contain the address of another variable or any valid address in the memory. 13. Using the variable a, give definitions for the following: a) An integer b) A pointer to an integer c) A pointer to a pointer to an integer d) An array of 10 integers e) An array of 10 pointers to integers f) A pointer to an array of 10 integers g) A pointer to a function that takes an integer as an argument and returns an integer h) An array of ten pointers to functions that take an integer argument and return an integer
70
C Language
The answers are: a) int a; // An integer b) int *a; // A pointer to an integer c) int **a; // A pointer to a pointer to an integer d) int a[10]; // An array of 10 integers e) int *a[10]; // An array of 10 pointers to integers f) int (*a)[10]; // A pointer to an array of 10 integers g) int (*a)(int); // A pointer to a function a that takes an integer argument and returns an integer h) int (*a[10])(int); // An array of 10 pointers to functions that take an integer argument and return an integer 14. How are pointer variables initialized? Pointer variable are initialized by one of the following two ways - Static memory allocation - Dynamic memory allocation 15. What is a pointer value and address? A pointer value is a data object that refers to a memory location. Each memory location is numbered in the memory. The number attached to a memory location is called the address of the location. 16. What is an argument? Differentiate between formal arguments and actual arguments? Using argument we can pass the data from calling function to the called function. Arguments available in the function definition are called formal arguments. Can be preceded by their own data types. We use Actual arguments in the function call. 17. What is Function Pointer? Explain with an example? Using function pointer we can do almost anything with function name. We can pass parameters to a function that is called as pointer. A classic example is the library function qsort(), which takes a pointer to a function. This pointer often is coded as a constant; you might, however, want to code it as a function pointer variable that gets assigned the correct function to sort()s compare. I have given you a example of Function pointer. Function named function () is defined which will be called through a function pointer. A function named caller () accepts as parameters a function pointer and an integer, which will be passed as arguments to the function that will be called by caller ().
71
C Language
Example program: #include static void function(int a) { printf("function: %d\n", a); } static void caller(void (*func)(int), int p) { (*func)(p); } int main(void) { caller(function, 10); return 0; } WORKSHOP 1. Create a function that accepts a number and prints the square and cube values. 2. Create a function that accepts a number prints cube value. 3. Create a function that accepts a number and returns its factorial. 4. Create a function that accepts a number and returns whether it is a prime number or not.
72
C Language
6-Arrays
6. ARRAYS
6.1 INTRODUCTION
An array is a fixed size sequence collection of elements of same data types. The first element in the array is numbered 0, so the last element is 1 less than the size of the array. An array is also known as a subscripted variable. However big an array its elements are always stored in contiguous memory locations.
The type specifies the type of element that will be contained in the array, such as int, float, or char and the size indicates the maximum number of elements that can be stored inside the array. E.g.: float height [50]; int group [10]; char name [10];
/* array declaration */
73
C Language
6-Arrays
printf ( "\nEnter marks " ) ; scanf ( "%d", &marks[i] ) ; /* store data in array */ } for ( i = 0 ; i <= 29 ; i++ ) sum = sum + marks[i] ; /* read data from an array*/ avg = sum / 30 ; printf ( "\nAverage marks = %d", avg ) ; } There is a lot of new material in this program, so let us take it apart slowly.
C Language
6-Arrays
disp ( &marks[i] ) ; } disp ( int *n ) { printf ( "%d ", *n ) ; } And heres the output... 55 65 75 56 78 78 90 Here, we are passing addresses of individual array elements to the function display ( ). Hence, the variable in which this address is collected (n) is declared as a pointer variable. And since n contains the address of array element, to print out the array element we are using the value at address operator (*).
C Language
6-Arrays
Value of k = c Original address in x = 65524 Original address in y = 65520 Original address in z = 65519 New address in x = 65526 New address in y = 65524 New address in z = 65520 This is illustrated in the following program. main( ) { int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ; int *i, *j ; i = &arr[1] ; j = &arr[5] ; printf ( "%d %d", j - i, *j - *i ) ; } Here i and j have been declared as integer pointers holding addresses of first and fifth element of the array respectively. Suppose the array begins at location 65502, then the elements arr[1] and arr[5] would be present at locations 65504 and 65512 respectively, since each integer in the array occupies two bytes in memory. The expression j - i would print a value 4 and not 8. This is because j and i are pointing to locations that are 4 integers apart. What would be the result of the expression *j - *i? 36, since *j and *i return the values present at addresses contained in the pointers j and i. Our next programs show ways in which we can access the elements of this array. main( ) { int num[ ] = { 24, 34, 12, 44, 56, 17 } ; int i ; for ( i = 0 ; i <= 5 ; i++ ) { printf ( "\naddress = %u ", &num[i] ) ; printf ( "element = %d", num[i] ) ; } } The output of this program would be: address = 65512 element = 24 address = 65514 element = 34 address = 65516 element = 12
76
C Language
6-Arrays
address = 65518 element = 44 address = 65520 element = 56 address = 65522 element = 17 This method of accessing array elements by using subscripted variables is already known to us. This method has in fact been given here for easy comparison with the next method, which accesses the array elements using pointers. main( ) { int num[ ] = { 24, 34, 12, 44, 56, 17 } ; int i, *j ; j = &num[0] ; /* assign address of zeroth element */ for ( i = 0 ; i <= 5 ; i++ ) { printf ( "\naddress = %u ", j ) ; printf ( "element = %d", *j ) ; j++; /* increment pointer to point to next location */ } } The output of this program would be: address = 65512 element = 24 address = 65514 element = 34 address = 65516 element = 12 address = 65518 element = 44 address = 65520 element = 56 address = 65522 element = 17 In this program, to begin with we have collected the base address of the array (address of the 0th element) in the variable j using the statement, j = &num[0] ; /* assigns address 65512 to j */ When we are inside the loop for the first time, j contains the address 65512, and the value at this address is 24. These are printed using the statements, printf ( "\n address = %u ", j ) ; printf ( "element = %d", *j ) On incrementing j it points to the next memory location of its type (that is location no. 65514). But location no. 65514 contains the second element of the array, therefore when the printf( ) statements are executed for the second time they print out the second element of the array and its address (i.e. 34 and 65514)... and so on till the last element of the array has been printed
77
C Language
6-Arrays
Thus, 1234 is stored in stud [0] [0], 56 is stored in stud [0] [1] and so on. The above arrangement highlights the fact that a two- dimensional array is nothing but a collection of a number of one- dimensional arrays placed one below the other.
78
C Language
6-Arrays
The array arrangement shown in Figure 8.4 is only conceptually true. This is because memory doesnt contain rows and columns. In memory whether it is a one-dimensional or a twodimensional array the array elements are stored in one continuous chain. The arrangement of array elements of a two-dimensional array in memory is shown below: s[0][0] s[0][1] s[1][0] s[1][1] s[2][0] s[2][1] s[3][0] s[3][1] 1234 56 1212 33 1434 80 1312 78 65508 65510 65512 65512 65516 65518 65520 65522
79
C Language
6-Arrays
Type arrayname[s1][s2][s3][sm];
An example of initializing a three-dimensional array int arr[3][4][2] = { { { 2, 4 },{ 7, 8 },{ 3, 4 },{ 5, 6 } }, { { 7, 6 },{ 3, 4 },{ 5, 3 },{ 2, 3 } }, { { 8, 9 },{ 7, 2 },{ 3, 4 },{ 5, 1 } }, }; A three-dimensional array can be thought of as an array of arrays of arrays. The outer array has three elements, each of which is a two-dimensional array of four one-dimensional arrays, each of which contains two integers. In the array declaration note how the commas have been given.
2nd 2-D array 1 2-D array 0 2-D array
th st
8 7 6 4 3 3
9 2 4 1
2 7 3 5
4 8 4 6
In memory the same array elements are stored linearly as shown in below 0th 2-D array 2 4 7 8 65478 1st2-D array 6 7 3 4 5 65494 2nd 2-D array 9 7 2 3 4 5 65510
EXERCISE:
What is output of following? (a) main() { char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
80
C Language
6-Arrays
} (b) main() { char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]); } (c) main() { char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]); } (d) main() { char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]); (e) main( ) { int size ; scanf ( "%d", &size ) ; int arr[size] ; for ( i = 1 ; i <= size ; i++ ) { scanf ( "%d", arr[i] ) ; printf ( "%d", arr[i] ) ; } } (f) main( ) {
81
C Language
6-Arrays
int i, a = 2, b = 3 ; int arr[ 2 + 3 ] ; for ( i = 0 ; i < a+b ; i++ ) { scanf ( "%d", &arr[i] ) ; printf ( "\n%d", arr[i] ) ; } } (g) main( ) { int array[26], i ; for ( i = 0 ; i <= 25 ; i++ ) { array[i] = 'A' + i ; printf ( "\n%d %c", array[i], array[i] ) ; } } (h) main( ) { int sub[50], i ; for ( i = 0 ; i <= 48 ; i++ ) ; { sub[i] = i ; printf ( "\n%d", sub[i] ) ; } } (i) main( ) { int a[ ] = { 2, 4, 6, 8, 10 } ; int i ; change ( a, 5 ) ; for ( i = 0 ; i <= 4 ; i++ ) printf( "\n%d", a[i] ) ; } change ( int *b, int n ) {
82
C Language
6-Arrays
int i ; for ( i = 0 ; i < n ; i++ ) *( b + i ) = *( b + i ) + 5 ; } (j) main( ) { int a[5], i, b = 16 ; for ( i = 0 ; i < 5 ; i++ ) a[i] = 2 * i ; f ( a, b ) ; for ( i = 0 ; i < 5 ; i++ ) printf ( "\n%d", a[i] ) ; printf( "\n%d", b ) ; } f ( int *x, int y ) { int i ; for ( i = 0 ; i < 5 ; i++ ) *( x + i ) += 2 ; y += 2; }
PROGRAMS:
1. Write a program to arrange 5 numbers in ascending order 2. Write a program to find largest and smallest number out of 10 numbers using array 3. Write a program to enter 15 numbers at a time and display them in reverse order 4. Write a program to pick up the largest number from any 5 row by 5 column matrix. 6. Write a program to add, subtract and multiply any two 6 x 6 matrices. 7. Write a program to sort all the elements of a 4 x 4 matrix 8. Write a program to find average marks obtained by a class of 30 students in a test. 9. Write a program to count the number of students belonging to each of following groups of marks 0-9, 10-19, 20-29.100 10. Write a program to compute and print a multiplication table for numbers 1 to 5 11. Write a program to find if a square matrix is symmetric.
83
C Language
6-Arrays
C INTERVIEW QUESTIONS 1. What is the Array? How to define and declare them? Basically Array are the collection of same data type. It has common name and addressed as a group. Declaration of an Array: We have to declare Array also as a single data object. int Array[10]; In this array of integers are created. Than first member in the array are addressed as Array [0] and last member has been declared as Array [9]. Example: int Array[MAX_SIZE]; int n; for (n = 1; n <= MAX_SIZE; n++) { Array[n] = n; } 2. What are the characteristics of arrays in C? some main characteristics of arrays are given below: 1. All entry in array should have same data type. 2. Tables can store values of difference data types. 3. When does the compiler not implicitly generate the address of the first element of an array? When array name appears in an expression such as: 1. Array as an operand of the size of operator. 2. Array as an operand of & operator. 3. Array as a string literal initialize for a character array. 4. Difference between arrays and pointers? Arrays automatically allocate space with fixed in size and location, but in pointers above are dynamic. Array is referred directly to the elements. But a pointer refers to address of the elements. 5. What is thrashing? Thrashing is that in which a computer takes the much type to load the data from secondary memory to main memory or main memory to secondary memory as compared to execution of loaded data. When we divide memory into pages than thrashing from this is called 'page thrashing'.
84
C Language
6-Arrays
6. What is the difference b/n run time binding and compile time binding? When the address of functions are determined a run time then it is called run time or dynamic binding or late binding. While when the address of functions is determined in a compile time then it is called compile time or static binding or early binding. In compile time binding, memory is allocated during compile time and in runtime binding, memory is allocated during running the program 7. How to differentiate local memory and global memory? Local and global memory allocation is applicable with Intel 80x86 CPUs. Some main difference b/n local and global variables are given below: 1. Using local memory allocation we can access the data of the default memory segment, where as with global memory allocation we can access the default data, located outside the segment, usually in its own segment. 8. What is the difference between char *a and char a []? Char a[]; is an variable of array store elements of same data type from above the array a[] store only characters can't store integers values. Char *a; is a pointer that stores address of the variable. Since pointer *a is a variable it also have an address. 9. What is the difference between null array and an empty array? Due to difference in memory allocation, Null array has not allocated memory spaces. Whereas Empty array has memory allocated spaces. In a Null array object are not assign to the variables, where as in an empty array object are assign to the variables. Suppose, it we want to add some values in both array than in case of Null array first we have to assign the object to the variables after that we have to add values. Where as in case of Empty array we have to only add the values. When we declare int* arr[] as global it has only null that means it is an null array. When array has 0 elements is called empty array 10. What is static memory allocation and dynamic memory allocation? Information regarding static memory allocation and dynamic memory allocation are given below: Static memory allocation: The compiler allocates the required memory space for a declared variable. Using the address of operator, the reserved address is obtained and assigned to a pointer variable. Most of the declared variables have static memory; this way is called as static memory allocation.
85
C Language
6-Arrays
For getting memory dynamically It uses functions such as malloc ( ) or calloc ( ).the values returned by these functions are assigned to pointer variables, this way is called as dynamic memory allocation. In this memory is assigned during run time WORKSHOP 1. Read 10 numbers and store in an array. Print the sum of those numbers. 2. Read 10 numbers and store in an array Print the numbers that are 100 and above. 3. Read 10 numbers and store in an array. But do not allow duplicates. 4. Read a 3 x 2 matrix, and print. 5. Read roll no & five subject marks for 3 students and store in an array. Print the rollno and minimum marks obtained by each student. 6. Read roll no & five subject marks for 3 students and store in an array. Print the all student totals of each subjects. 7. Read rollno & five subject marks for 3 students and store in an array. Print the highest mark among all students and subjects. 8. Read 10 numbers and store an array. Then read a number, search for it in the array, and print its position if found. 9. Read 10 numbers and store in an array. Then read a numbers, search for it in the array, and print no of times it is repeated. 10. Read roll no & percentage for 5 students ad store in an array. Then read a roll no, search and print his percentage.
86
C Language
8-Structures
7. STRINGS
7.1 What are Strings?
The group of integers can be stored in an integer array; similarly a group of characters can be stored in a character array. Character arrays are also called strings. A string constant is a one-dimensional array of characters terminated by a null (\0). For example, char name[ ] = { 'A', D', V', 'E', 'T', 'E', 'C',H '\0' } ; Each character in the array occupies one byte of memory and the last character is always \0. \0 is called null character. Note that \0 and 0 are not same. ASCII value of \0 is 0, whereas ASCII value of 0 is 48. Note that the elements of the character array are stored in contiguous memory locations. The terminating null (\0) is important, because it is the only way the functions that work with a string can know where the string ends. In fact, a string not terminated by a \0 is not really a string, but merely a collection of characters.
C Language
8-Structures
i++ ; } } And here is the output... Klinsman The %s used in printf( ) is a format specification for printing out a string. The same specification can be used to receive a string from the keyboard main( ) { char name[ ] = "Klinsman" ; printf ( "%s", name ) ; }
88
C Language
8-Structures
This will also illustrate how the library functions in general handle strings. Let us study these functions one by one.
7.3.1 Strlen ( )
This function counts the number of characters present in a string. Its usage is illustrated in the following program. main( ) { char arr[ ] = "Coimbatore" ; int len1, len2 ; len1 = strlen ( arr ) ; len2 = strlen ( "Gandhi puram) ; printf ( "\nstring = %s length = %d", arr, len1 ) ; printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
89
C Language
8-Structures
} The output would be... string = Bamboozled length = 10 string = Humpty Dumpty length = 12
7.3.2 Strcpy ( )
This function copies the contents of one string into another. The base addresses of the source and target strings should be supplied to this function. Here is an example of strcpy( ) in action... main( ) { char source[ ] = "Sayonara" ; char target[20] ; strcpy ( target, source ) ; printf ( "\nsource string = %s", source ) ; printf ( "\ntarget string = %s", target ) ; } And here is the output... source string = Sayonara target string = Sayonara
7.3.3 Strcat ( )
This function concatenates the source string at the end of the target string. For example, Bombay and Nagpur on concatenation would result into a string BombayNagpur. Here is an example of strcat( ) at work. main( ) { char source[ ] = "Folks!" ; char target[30] = "Hello" ; strcat ( target, source ) ; printf ( "\nsource string = %s", source ) ; printf ( "\ntarget string = %s", target ) ; } And here is the output... source string = Folks! target string = HelloFolks! Note that the target string has been made big enough to hold the final string. I leave it to you to develop your own xstrcat( ) on lines of xstrlen( ) and xstrcpy( ).
90
C Language
8-Structures
7.3.4 Strcmp ( )
This is a function which compares two strings to find out whether they are same or different. The two strings are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value zero. If theyre not, it returns the numeric difference between the ASCII values of the first non-matching pairs of characters. Here is a program which puts strcmp( ) in action. main( ) { char string1[ ] = "Jerry" ; char string2[ ] = "Ferry" ; int i, j, k ; i = strcmp ( string1, "Jerry" ) ; j = strcmp ( string1, string2 ) ; k = strcmp ( string1, "Jerry boy" ) ; printf ( "\n%d %d %d", i, j, k ) ; } And here is the output... 0 4 -32
C Language
8-Structures
a = strcmp ( &masterlist[i][0], yourname ) ; if ( a == 0 ) { printf ( "Welcome, you can enter the palace" ) ; flag = 1 ; break ; } } if ( flag == 0 ) printf ( "Sorry, you are a trespasser" ) ; } And here is the output for two sample runs of this program... Enter your name dinesh Sorry, you are a trespasser Enter your name raman Welcome, you can enter the palace Instead of initializing names, had these names been supplied from the keyboard, the program segment would have looked like this... for( i = 0 ; i <= 5 ; i++ ) scanf ( "%s", &masterlist[i][0] ) ; While comparing the strings through strcmp( ), note that the addresses of the strings are being passed to strcmp( ). As seen in the last section, if the two strings match, strcmp( ) would return a value 0, otherwise it would return a non-zero value.
92
C Language
8-Structures
Akshay\0
Ram\0
Srinivas\0
182
Gopal\0
189 201
Rakesh\ 210 0
195
Parag\0
182 65514
189 65516
195 65518
That is, base address of akshay is stored in names[0], base address of parag is stored in names[1] and so on, let the next program illustrates, /* Exchange names using 2-D array of characters */ main( ) { char names[ ][10] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" }; int i ; char t ; printf ( "\nOriginal: %s %s", &names[2][0], &names[3][0] ) ; for ( i = 0 ; i <= 9 ; i++ ) { t = names[2][i] ; names[2][i] = names[3][i] ; names[3][i] = t ; } printf ( "\nNew: %s %s", &names[2][0], &names[3][0] ) ; } And here is the output... Original: raman srinivas New: srinivas raman Note that in this program to exchange the names we are required to exchange corresponding characters of the two names. In effect, 10 exchanges are needed to interchange two names.
93
C Language
8-Structures
Let us see, if the number of exchanges can be reduced by using an array of pointers to strings. Here is the program... main( ) { char *names[ ] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" }; char *temp ; printf ( "Original: %s %s", names[2], names[3] ) ; temp = names[2] ; names[2] = names[3] ; names[3] = temp ; printf ( "\n New: %s %s", names[2], names[3] ) ; } And here is the output... Original: raman srinivas New: srinivas raman The output is same as the earlier program. In this program all that we are required to do is exchange the addresses (of the names) stored in the array of pointers, rather than the names themselves. Thus, by effecting just one exchange we are able to interchange names. This makes handling strings very convenient.
C Language
8-Structures
printf ( "\n Enter name " ) ; scanf ( "%s", names[i] ) ; } } The program doesnt work because; when we are declaring the array it is containing garbage values. And it would be definitely wrong to send these garbage values to scanf( ) as the addresses where it should keep the strings received from the keyboard.
Exercise What would be the output of the following programs? (a) main( ) { char c[2] = "A" ; printf ( "\n%c", c[0] ) ; printf ( "\n%s", c ) ; } (b) main( ) { char s[ ] = "Get organised! learn C!!" ; printf ( "\n%s", &s[2] ) ; printf ( "\n%s", s ) ; printf ( "\n%s", &s ) ; printf ( "\n%c", s[2] ) ; } (c) main( ) { char s[ ] = "No two viruses work similarly" ; int i = 0 ; while ( s[i] != 0 ) { printf ( "\n%c %c", s[i], *( s + i ) ) ; printf ( "\n%c %c", i[s], *( i + s ) ) ; i++ ; } }
95
C Language
8-Structures
(d) main( ) { char *str1 = "United" ; char *str2 = "Front" ; char *str3 ; str3 = strcat ( str1, str2 ) ; printf ( "\n%s", str3 ) ; } (e) main( ) { int arr[ ] = { A, B, C, D } ; int i ; for ( i = 0 ; i <= 3 ; i++ ) printf ( "\n%d", arr[i] ) ; } (f) main( ) { char arr[8] = "Rhombus" ; int i ; for ( i = 0 ; i <= 7 ; i++ ) printf ( "\n%d", *arr ) ; arr++ ; } (g) main( ) { char str1[ ] = { H, e, l, l, o } ; char str2[ ] = "Hello" ; printf ( "\n%s", str1 ) ; printf ( "\n%s", str2 ) ; } (h) main( ) { printf ( 5 + "Good Morning " ) ; }
96
C Language
8-Structures
Programs
1. Write a c program to print the string from given character 2. Write a c program to convert the string from lower case to upper case 3. Write a c program to counting different characters in a string using c program 4. Write a c program to concatenation of two strings 5. Write a c program to concatenation of two strings using pointer in 6. Write a c program which prints initial of any name 7. How to reverse a string in c without using reverse function 8. Write a c program to reverse a string using pointers 9. Write a c program to String concatenation without using string functions 10. Write a c program to compare two strings in c without using Strcmp 11. Write a c program for String copy without using strcpy in c 12. Write a c program to convert string into ASCII values in c programming language:
C interview questions
1. What is the difference between String and Array? Array can hold group of element of the same type, and which allocates the memory for each element in the array, if we want we can obtain the particular value from an array by giving index value. Ex: int a[10]; A variable holds the values of integer at max 10. String can hold any type of data, but it makes together we can't obtain the particular value of the string. String s="Pra12"; 2. What is the difference between memcpy and strcpy? The key difference between memcpy and strcpy are given below: 1. Memcpy is used to copy the NULL bytes even if size is not mentioned, where as strcpy is stopped copying when it encounters NULL bytes. 2. Memcpy can copy null bytes also if the size of memory is given strcpy stops after the first null byte 3. How to convert a string into integer? this program illustrates how to convert string into integer int s(char str[]) { int n=0,m; for(int m=0;str[m]>='0' && str[m]<='9';m++) n=10*n+(str[m]-'0'); if(mintf("Error String"); return 0;
97
C Language
8-Structures
} return n; } 4. Difference between strdup and strcpy? Both copy a string. strcpy wants a buffer to copy into. strdup allocates a buffer using malloc().Unlike strcpy(), strdup() is not specified by ANSI . 5. What is a volatile variable? We cannot modify the variable which is declared to volatile during execution of whole program. Example: Volatile int i = 10; value of i cannot be changed at run time. 6. What is the difference between the functions memmove () and memcpy ()? The arguments of memmove () can overlap in memory. The arguments of memcpy () cannot. 7. What is a file pointer? The pointer to a FILE data type is called as a stream pointer or a file pointer. A file pointer points to the block of information of the stream that had just been opened. 8. Out of fgets () and gets () which function is safe to use and why? fgets () is safer than gets(), because we can specify a maximum input length. Neither one is completely safe, because the compiler cant prove that programmer wont overflow the buffer he pass to fgets (). 9. How would you use the functions fseek(), freed(), fwrite() and ftell()? fseek(f,1,i) Move the pointer for file f a distance 1 byte from location i. fread(s,i1,i2,f) Enter i2 data items, each of size i1 bytes, from file f to string s. fwrite(s,i1,i2,f) send i2 data items, each of size i1 bytes from string s to file f. ftell(f) Return the current pointer position within file f. The data type returned for functions fread,fseek and fwrite is int and ftell is long int. 10. What is a stream? A stream is a source of data or destination of data that may be associated with a disk or other I/O device. The source stream provides data to a program and it is known as input stream. The destination stream receives the output from the program and is known as output stream.
98
C Language
8-Structures
WORKSHOP 1. Write a program to concat the two strings 2. Write a program to Reverse Strings 3. Write a program for Comparing Strings 4. Write a program for Palindrome 5. Write a program for vowel count
99
C Language
8-Structures
8. STRUCTURES
8.1 What is structure?
A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. The general form of a structure is given below: struct <structure name> { structure element 1 ; structure element 2 ; structure element 3 ; ...... ...... }; The keyword struct introduces a structure declaration, which is a list of declarations enclosed in braces. An optional name called a structure tag may follow the word struct (as with point here). The tag names this kind of structure, and can be used subsequently as shorthand for the part of the declaration in braces. The variables named in a structure are called members. 8.2 Declaring a Structure In our example program, the following statement declares the structure type: struct book { char name ; float price ; int pages ; } This statement defines a new data type called struct book. Each variable of this data type will consist of a character variable called name, a float variable called price and an integer variable called pages. Once the new structure data type has been defined one or more variables can be declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as, struct book b1, b2, b3 ; (1) Struct book { Char name; float price ; int pages ; } struct book b1, b2, b3 ;
100
C Language
8-Structures
(2)
struct book { char name ; float price ; int pages ; } b1, b2, b3; struct book { char name[10] ; float price ; int pages ; }; struct book b1 = { "Basic", 130.00, 550 } ; struct book b2 = { "Physics", 150.80, 800 } ; A structure contains a number of data types grouped together. These data types may or may not be of the same type. The following example illustrates the use of this data type. struct book { char name ; float price ; int pages ; }; struct book b1, b2, b3 ; main( ) { printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ; scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ; scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ; scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ; printf ( "\nAnd this is what you entered" ) ; printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ; printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ; printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ; }
(3)
And here is the output... Enter names, prices and no. of pages of 3 books A 100.00 354
101
C Language
8-Structures
C 256.50 682 F 233.70 512 And this is what you entered A 100.000000 354 C 256.500000 682 F 233.700000 512 This program demonstrates two fundamental aspects of structures: (a) declaration of a structure (b) accessing of structure elements Note the following points while declaring a structure type: (a)The closing brace in the structure type declaration must be followed by a semicolon. (b)It is important to understand that a structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the form of the structure. (c)Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined.
C Language
8-Structures
Actually the structure elements are stored in memory as shown in the Figure b1.names b1.price b1.pages B 130.00 550 65518 65519 65523
C Language
8-Structures
Placing the cursor at an appropriate position on screen Drawing any graphics shape on the screen Receiving a key from the keyboard Checking the memory size of the computer Finding out the list of equipment attached to the computer Formatting a floppy Hiding a file from the directory Displaying the directory of a disk Sending the output to printer Interacting with the mouse
Exercise:
(a) main( ) { struct gospel { int num ; char mess1[50] ; char mess2[50] ; }m; m.num = 1 ; strcpy ( m.mess1, "If all that you have is hammer" ) ; strcpy ( m.mess2, "Everything looks like a nail" ) ; /* assume that the strucure is located at address 1004 */ printf ( "\n%u %u %u", &m.num, m.mess1, m.mess2 ) ; } (b) struct virus { char signature[25] ; char status[20] ; int size ; } v[2] = { "Yankee Doodle", "Deadly", 1813, "Dark Avenger", "Killer", 1795 };
104
C Language
8-Structures
(c) main( ) { int i ; for ( i = 0 ; i <=1 ; i++ ) printf ( "\n%s %s", v.signature, v.status ) ; }
(d) struct s { char ch ; int i ; float a ; }; (e) main( ) { struct s var = { 'C', 100, 12.55 } ; f ( var ) ; g ( &var ) ; } f ( struct s v ) { printf ( "\n%c %d %f", v -> ch, v -> i, v -> a ) ; } struct gospel { int num ; char mess1[50] ; char mess2[50] ; } m1 = { 2, "If you are driven by success", "make sure that it is a quality drive" }; (f) main( ) { struct gospel m2, m3 ; m2 = m1 ;
105
C Language
8-Structures
Programs:
1. Create a structure to specify data on students given below: Roll number, Name, Department, Course, year of joining Assume that there are not more than 450 students in the collage. (a) Write a function to print names of all students who joined in a particular year. (b) Write a function to print the data of a student whose roll number is given. 2. Write a C program to implement average of students using Structure 2 Write a C program to implement the same using Structure with Array 3 Write a C program to implement the same using Structure with Function 4 Write a C program to Implement Structure the same using with Pointers
C interview questions
1. What is a structure? Structure constitutes a super data type which represents several different data types in a single unit. A structure can be initialized if it is static or global. 2. What is a union? Union is a collection of heterogeneous data type but it uses efficient memory utilization technique by allocating enough memory to hold the largest member. Here a single area of memory contains values of different types at 3. Is that possible to pass a structure variable to a function/ If so, explain the detailed ways? yes it is possible to pass structure variable to a function struct emp { int eno; }; void disp(struct emp e) { printf(e.eno); } void main() { struct emp e; e.eno=10; disp(e); }
106
C Language
8-Structures
4. What is the difference between a structure and a union? A union is essentially a structure in which all of the fields overlay each other; you can only use one field at a time. (You can also cheat by writing to one field and reading from another, to inspect a type's bit patterns or interpret them differently, but that's obviously pretty machinedependent.) The size of a union is the maximum of the sizes of its individual members, while the size of a structure is the sum of the sizes of its members. (In both cases, the size may be increased by padding. 5. What are the differences between structures and arrays? Structure is a collection of heterogeneous data type but array is a collection of homogeneous data types. Array 1-It is a collection of data items of same data type. 2-It has declaration only 3-.There is no keyword. 4- Array name represent the address of the starting element. Structure 1-It is a collection of data items of different data type. 2- It has declaration and definition 3- keyword struct is used 4-Structure name is known as tag it is the short hand notation of the declaration.
6. What are the advantages of using Unions? Major advantages of using unions are: (i) Efficient use of memory as it does not demand memory space for its all members rather it require memory space for its largest member only. (ii) Same memory space can be interpreted differently for different members of the union. 7. How are Structure passing and returning implemented by the complier? When structures are passed as argument to functions, the entire structure is typically pushed on the stack. To avoid this overhead many programmer often prefer to pass pointers to structure instead of actual structures. Structures are often returned from functions in a location pointed to by an extra, compiler-supported hidden argument to the function. 8. What is the similarity between a Structure, Union and enumeration? All of them let the programmer to define new data type.
107
C Language
8-Structures
9. Can a Structure contain a Pointer to itself? Yes such structures are called self-referential structures. 10. Why cant we compare structures? There is no single, good way for a compiler to implement structure comparison which is consistent with Cs low-level flavour. A simple byte-by-byte comparison could found on random bits present in unused holes in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. 11. How are structure passing and returning implemented? When structures are passed as arguments to functions, the entire structure is typically pushed on the stack, using as many words as are required. Some compilers merely pass a pointer to the structure, though they may have to make a local copy to preserve pass-by-value semantics. Structures are often returned from functions in a location pointed to by an extra, compilersupplied hidden argument to the function. Some older compilers used a special, static location for structure returns, although this made structure-valued functions non-reentrant, which ANSI C disallows. 12. Can we initialize unions? ANSI Standard C allows an initialize for the first member of a union. There is no standard way of initializing any other member (nor, under a pre-ANSI compiler, is there generally any way of initializing a union at all). 13. Why doesnt struct x {}; x the struct; work? C is not C++. Typedef names are not automatically generated for structure tags. 14. What are bit fields? Bit Field is used to make packed of data in a structure. Using bit fields we can communicate Disk drives and OS at a low level. Disk drives have many registers, if want to packed together in only one register we have to use bit fields. 15. What is the use of bit fields in a structure declaration? A bit field is a set of adjacent bits with a single implementation. Syntax: struct { unsugned int is_keyword : 1; unsigned is_extern :1; unsigned is_static : 1 ; } flags ; flags.is_extern = flags.is_static = 1 ;
108
C Language
8-Structures
WORKSHOP 1) Write a program to get the employee details and print it(Use Structures) 2) Write a program to get company details & employee details .Print the details(Use Nested Structures) 3) Write a program to get employee details and print it(Use Pointers as tag name)
109
C Language
9-File
9.FILE
9.1 INTRODUCTION
In this chapter we learn File Operations, using fopen, fwrite, and fread, fprintf, fscanf, fgetc and fputc. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. For example: FILE *fp; Fopen
To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file. FILE *fopen(const char *filename, const char *mode); In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than a single backslash as you otherwise risk an escape character such as \t. Using double backslashes \\ escapes the \ key, so the string works as it is expected.
C Language
9-File
char ch; clrscr(); fp=fopen(pr.c,r); while(1) { ch = fgetc(fp); if(ch==EOF) break; printf(%c,ch); } fclose(fp); }
fopen modes The allowed modes for fopen are as follows: r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists) Note that it's possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the NULL pointer. Here's a simple example of using fopen: FILE *fp; fp= fopen("c:\\test.txt", "r"); This code will open test.txt for reading in text mode. Fclose When you're done working with a file, you should close it using the function int fclose(FILE *a_file); fclose returns zero if the file is closed successfully. An example of fclose is
111
C Language
9-File
fclose(fp); Reading and writing with fprintf, fscanf fputc, and fgetc To work with text input and output, you use fprintf and fscanf, both of which are similar to printf and scanf except that you must pass the FILE pointer as first argument. For example: FILE *fp; fp=fopen("c:\\test.txt", "w"); fprintf(fp, "Testing...\n"); It is also possible to read (or write) a single character at a time this can be useful if you wish to perform character-by-character input (for instance, if you need to keep track of every piece of punctuation in a file it would make more sense to read in a single character than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns an int, will let you read a single character from a file: int fgetc (FILE *fp); Notice that fgetc returns an int. What this actually means is that when it reads a normal character in the file, it will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when you're at the very end of the file, you can't get a character value in this case, fgetc will return "EOF", which is a constant that indicates that you've reached the end of the file. example using fgetc . The fputc function allows you to write a character at a time int fputc( int c, FILE *fp ); Note that the first argument should be in the range of an unsigned char so that it is a valid character. The second argument is the file to write to. On success, fputc will return the value c, and on failure, it will return EOF. String I/O in Files Reading or writing strings of characters from and to files is as easy as reading and writing individual characters.Here is a an example program that writes strings to a file using the function fputs().
112
C Language
9-File
Example 1 It receives strings from keyboard and writes them to file # include<stdio.h> # include<stdlib.h> # include<string.h> void main() { FILE *fp; char s[80]; fp=fopen(pt.txt,w); if(fp==NULL) { puts(Cannot open file); exit(1); } printf(\n Enter a few lines of text\n); while(strlen(gets(s)>0) { fputs(s,fp); fputs(\n,fp); fclose(fp); }
113
C Language
9-File
Example 2 This program reads & writes text in to the file according to the choice made by the user #include<stdio.h> #include<conio.h> void main() { FILE *f1; char c; int op; clrscr(); f1=fopen("abc.txt","a+"); while(5) { clrscr(); printf("\n Type 1 for reading and 2 for writing and 3 for exit \n"); scanf("%d",&op); if(op==1) { rewind(f1); printf("\n The file 'abc' has the matter of following\n "); while(!feof(f1)) { c=getc(f1); putchar(c); }
114
C Language
9-File
} else if(op==2) { printf("\n Finish yr message with symbol 'n' \n"); while( (c=getchar())!=EOF) putc(c,f1); } else break; getch(); } fclose(f1); getch(); }
C Language
9-File
fp=fopen(EMPLOYEE.DAT,w); if( fp ==NULL) { puts(Cannot open file); exit(1); } while(another==Y) { printf(\n Enter Name, Age and Basic salary:); scanf(%s %d %f,e.name,&e.age,&e.bs); fprintf(fp,%s %d %f \n,e.name,e.age,e.bs); printf(Add another recordY/N); fflush(stdin); another =getche(); } fclose(fp); } } WORKSHOP 1.Write a program to write Content in to a file 2.Write a program to Read & Write Content to a file 3.Write a program which writes content to a file using structures
116
C Language
Solution
SOLUTION
SOLUTION SET-1
//1)Read a bill no : print its next 2 bill numbers. # include<stdio.h> # include<conio.h> void main() { int billno,n1,n2; clrscr(); printf("\n Enter The Bill No:: \n"); scanf("%d",&billno); n1=billno; n2=n1+1; printf("\n The Next Two Bill Nos Are %d \t %d::",n1,n2); getch(); } //2) Read two nos : Swap them and print # include<stdio.h> # include<conio.h> void main() { int a,b,temp; clrscr(); printf("\n Enter The A and B values\n");
117
C Language
Solution
scanf("%d",&a); scanf("%d",&b); temp=a; a=b; b=temp; printf("\n The A& B Values After Swapping Are :: %d \t %d\n",a,b); getch(); } //3)Read miles: Print in Kilometers # include<stdio.h> # include<conio.h>
void main() { float m,km; clrscr(); printf("Enter The Miles !!!\n"); scanf("%d",&m); km=m*1.6; printf("Distance In Terms of KILOMETRES %d\n",km); getch(); } //4) Given total months, find out the no of years and months. # include<stdio.h> # include<conio.h>
118
C Language
Solution
void main() {
int tmon,yrs,mn; clrscr(); printf("\n Enter The Total Months\n"); scanf("%d",&tmon); yrs=tmon/12; mn=tmon%12; printf("\n The No. Of Yrs is %d No: of Months is %d\n",yrs,mn); getch();
} //5)Given year and months, find out the months. # include<stdio.h> # include<conio.h> void main() { int yr,mn; clrscr(); printf("\n Enter The No: Of Yrs \n"); scanf("%d",&yr); printf("\n Enter The No: Of Months \n"); scanf("%d",&mn);
119
C Language
Solution
m=(yr*30)+mn; printf("\n The Total No:of Months Is %d\n",m); getch(); } # include<stdio.h> # include<conio.h> // 6) Given opening stock, purchase qty and sales qty find out the stock of the item. void main() { int opstk,pur,salesqty,sthand; clrscr(); printf("Enter The Opening Stock!!!\n"); scanf("%d",&opstk); printf("Enter The Purchase Quantity \n"); scanf("%d",&pur); printf("Enter The Sales Quantity \n"); scanf("%d",&salesqty); sthand =(opstk+pur)-salesqty; printf("The Present Stock Is %d\n",sthand); getch(); } //7) Given annual premium and no of years, calculate the total amount paid. #include<stdio.h> #include<conio.h> void main()
120
C Language
Solution
{ long int anprem,totno,tamtpaid; clrscr(); printf("Enter The AnnualPremium Amount\n"); scanf("%ld",&anprem); printf("Enter The Total No of Years \n"); scanf("%ld",&totno); tamtpaid =anprem*totno; printf("The Total Amount After Years %ld\n",tamtpaid); getch(); } //8) Given basic salary and no of days absent, find the gross salary. Add DA 40%. Deduct Rs.300 for insurance. Print the net salary payable.
#include<stdio.h> # include<conio.h> void main() { float bs,da,ins,wd,na,m,days,pd,daamt,insamt=300,pds; int totsal,per_day_sal; clrscr(); printf("\n\n Enter The Basic Salary !!!!\n"); scanf("%f",&bs); da =0.4; printf("Enter The No. Of Days Absent\n");
121
C Language
Solution
scanf("%f",&na); printf("Enter The No Of Month\n"); scanf("%f",&m); if(m==1 || m==3 || m == 5 || m==7 || m==9 || m==11) days =31; else if(m==2 || m==4 || m==6|| m==8) days =30; else days =28; wd=days-na; pds=bs/days; per_day_sal=pds*wd; daamt=da*bs; totsal=(daamt+per_day_sal)-insamt; printf("\nThe TOTAL SALARY IS %d\n",totsal); getch();
} //9.Given the Rate per Dozen, and no of items purchased, calculate the purchase value. # include<stdio.h> # include<conio.h>
C Language
Solution
clrscr(); printf("\n Enter The Rate per Dozen \n"); scanf("%d",ratedz); printf("\n Enter The Purchase Quantity \n"); scanf("%d",purqtydz); tot=(ratedz*purqtydz); printf("\n The TOTAL IS %d\n",tot); getch(); } //10) Given years and months print the total no of days.(Assume 30 days/month,365 days/year) # include<stdio.h> # include<conio.h>
void main() { int yr,mn,totdays; clrscr(); printf("\n Enter The Years \n"); scanf("%d",&yr); printf("\n Enter The Months \n"); scanf("d",&mn); totdays =(yr*12)+(mn*30) ; printf("\n The Total No: Of Days Is %d\n",totdays); getch(); }
123
C Language
Solution
SOLUTION SET-2
//1) Read length & breath: print whether it is square or a rectangular. # include<stdio.h> # include<conio.h> void main() { int len,br; clrscr(); printf("\n Enter The Length and Breadth \n"); scanf("%d",&len); scanf("%d",&br); if(len==br) printf("\n It's a Square \n"); else printf("\n It's a Rectangle\n"); getch(); } //2) Read 3 nos; Count the negative numbers and print. # include<stdio.h> # include<conio.h> //Negative no count: void main() { int a[3],countneg=0;
124
C Language
Solution
clrscr(); printf("\n Enter The Number\n"); for(i=0;i<3;i++) { scanf("%d",&a[i]); if(a[i]<0) { printf("It's a Negative Number\n"); countneg=countneg+1; } } printf("\n The Count Of Negetaive Number is %d\n",countneg); getch(); } //3)Read an applicants age; print whether his age is between 22 nad 28 or not. # include<stdio.h> # include<conio.h> void main() { int age; clrscr(); printf("\n Enter The Age \n"); scanf("%d",&age); if(age>=22 && age <=28) printf("\n Age Is between 22 and 28\n");
125
C Language
Solution
getch(); } //4)Read a character; print if it is a vowel or not. # include<stdio.h> # include<conio.h> void main() { char c; clrscr(); printf("\n Enter The Character\n"); scanf("%c",&c); if(c=='a'|| c=='e'|| c=='i'|| c=='o'|| c== 'u') { printf("It's a Vowel \n"); } else printf("\n It's Not Vowel \n"); getch(); }
SOLUTION SET-3 //1) Read a no; print if it is a zero, positive or negative number.
# include<stdio.h> # include<conio.h>
126
C Language
Solution
void main() { int a; clrscr(); printf("\n Enter The Number\n"); scanf("%d",&a); if(a==0) printf("It's Value Is Zero\n"); else if(a>0) printf("It's a Positive Number\n"); else if(a<0) printf("It's a Negative Number\n"); getch(); } //2) Read two nos ; print if both are equal. Otherwise print the biggest. # include<stdio.h> # include<conio.h> void main() { int a,b; clrscr(); printf("\n Enter The A and B Values\n"); scanf("%d %d",&a,&b); if(a>b) printf("\n A is Greater \n");
127
C Language
Solution
else printf("\n B is Greater\n"); getch(); } //3)Read three nos; print the biggest number. # include<stdio.h> # include<conio.h> void main() { int a,b,c; clrscr(); printf("\n Enter The A and B and C Values\n"); scanf("%d %d %d",&a,&b,&c); if(a>b && a>c) printf("\n A is Greater Than B and C\n"); else if(b>a && b>c) printf("\n B is Greater Than A and C \n"); else printf("\n C is Greater\n"); getch(); } //4)Read an option 1 or 2; if 1 Read a no; Print if it is an odd or even number; If 2 Read a no; print if it is a positive or negative number. # include<stdio.h> # include<conio.h>
128
C Language
Solution
void main() { int a; clrscr(); printf("\n Enter The Number\n"); scanf("%d",&a); if(a==0) printf("It's Value Is Zero\n"); else if(a>0) printf("It's a Positive Number\n"); else if(a<0) printf("It's a Negative Number\n"); getch(); }
SOLUTION SET-4
void main() { int ch,w; clrscr(); printf("\n Enter The Choice 1-7 to represent Week day Names\n");
129
C Language
Solution
else if(ch==2) printf("\n Tuesday\n"); else if(ch==3) printf("\n Wednesday\n"); else if(ch==4) printf("\n Thursday \n"); else if(ch==5) printf("\n Friday \n"); else if (ch==6) printf("\n Saturday\n");
getch(); }
//2)Read a percentage of marks; Grade it. A grade :80-100%, B grade:60-70%, C grade:40-59%, D grade:0-39%. # include<stdio.h> # include<conio.h>
130
C Language
Solution
void main() { int sub1,sub2,sub3,per; clrscr(); printf("\n Enter The Subject1 MarK !!!\n"); scanf("%d",&sub1); printf("\n Enter The Subject2 Mark !!!\n"); scanf("%d",&sub2); printf("\n Enter The Subject3 Mark !!!\n"); scanf("%d",&sub3); per=((sub1+sub2+sub3)/3); if(per>=80 && per<=100) printf("\n Grade A...\n"); else if(per>=60 && per<=70) printf("\n Grade B... \n"); else if(per>=40 && per<=69) printf("\n C Grade \n"); else if(per>=0 && per<=39) printf("\n D grade\n"); getch(); } //3)Read a purchase value; Calculate and print the discount amount based on following condition. No discount for purchase less than Rs.1000.00. 2% Discount for purchase upto Rs.2,000.00
131
C Language
Solution
5% Discount for purchase upto Rs.5,000.00 8% Discount for purchase above Rs.5000.00 # include<stdio.h> # include <conio.h> void main() { int pur; float disamt; clrscr(); printf("\n Enter The Purchase Value \n"); scanf("%d",&pur); if(pur<1000) printf("\n No Discount !!!!\n"); else if (pur>=1000 && pur <2000) { disamt =(pur*0.02); printf("\n The Discount Amount Is %f\n",disamt); } else if (pur>=2000 && pur<5000) { disamt =(pur*0.05); printf("\n The Discount Amount Is %f\n",disamt); } else if (pur>=5000) {
132
C Language
Solution
SOLUTION SET-5
//1) Read a month number[1 to 12]; print month name. # include<stdio.h> # include<conio.h> void main() { int ch; clrscr(); printf("\n Enter The Month Number \n"); scanf("%d",&ch); switch(ch) { case 1: printf("\n January !!!\n"); break; case 2: printf("\n Febrary !!!\n"); break; case 3:
133
C Language
Solution
printf("\n March !!!\n"); break; case 4: printf("\n April \n"); break; case 5: printf("\n May \n"); break; case 6: printf("\n June \n"); break; case 7: printf("\n July \n"); break; case 8: printf("\n August \n"); break; case 9: printf("\n September \n"); break; case 10: printf("\n October \n"); break; case 11: printf("\n November \n");
134
C Language
Solution
break; case 12: printf("\n December \n"); break; } getch(); } //2) Read a month number[1 to 12]; print if it is first/second/third/fourth quarter. # include<stdio.h> # include<conio.h> void main() { int ch; clrscr(); printf("\n Enter The Month Number \n"); scanf("%d",&ch); switch(ch) { case 1: case 2: case 3: { printf("\n First Quarter !!!\n"); break; }
135
C Language
Solution
case 7: case 8: case 9: { printf("\n Third Quarter !!!\n"); break; } case 10: case 11: case 12: { printf("\n Fourth Quarter!!! \n"); break; } } getch(); }
136
C Language
Solution
//3Read two nos; Display the following menu for selection. Then read the option, and do the appropriate action. f. g. h. i. j. Add Multiply Divide Do Nothing Choose Your Option[1-4]:________
# include<stdio.h> # include<conio.h> void main() { int ch,a,b,c; clrscr(); printf ("\n Enter The Choice 1->ADD 2->Multiply 3->Divide 4->Nothing !!!\n"); scanf("%d",&ch); printf("\n Enter The A & B Values \n"); scanf("%d %d" ,&a,&b); switch(ch) { case 1: { c=a+b; printf("\n The Addition Performed !!! %d\n",c); break; } case 2: {
137
C Language
Solution
c=a-b; printf("\n The Subtraction Performed !!! %d\n",c); break; } case 3: { c=a*b; printf("\n The Multiplication Performed !!! %d\n",c); break; } default: printf("\n Nothing !!!\n"); } getch(); }
SOLUTION SET-6
C Language
Solution
for(i=0;i<=40;) { i=i+5; printf(" \t %d",i); } getch(); } //2)Print the number series: 8,12,16,20,24,28,32,36,40 # include <stdio.h> # include<conio.h> void main() { int i,j=1; clrscr(); for(i=2;i<=64;) { i=i+2; j=2*i; if(j==64) break;
printf("\t%d",j); } getch(); }
139
C Language
Solution
//3 Print the number of series: 100,90,80,70,60,50,40,30,20,10,0 # include <stdio.h> # include<conio.h> void main() { int i; clrscr(); for(i=100;i>=0;) { printf("\t%d",i); i=i-10; } getch(); }
SOLUTION SET-7
1) Generate the series : 30 24 18 12 6 # include <stdio.h> # include<conio.h> //30 24 18 12 6 void main() { int i; clrscr(); for(i=30;i>=6;)
140
C Language
Solution
{ printf("\t %d",i); i=i-6; } getch(); } //2)Generate Series 15 20 25 30 35 40 45 # include<stdio.h> # include<conio.h> // 15 20 25 30 35 40 void main() { int i; clrscr(); for(i=15;i<=40;) { printf("\t %d",i); i=i+5; } getch(); } //3)Read 10 numbers and print the sum & average. #include<stdio.h> #include<conio.h> void main()
141
C Language
Solution
{ int i,a[10],n,sum=0; float avg; clrscr(); printf("Enter The No\n"); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); sum=sum+a[i]; } avg=sum/n; printf("The Average Is %f\n",avg); getch(); }
SOLUTION SET-8
//1)Read 10 numbers and print the total even nos and total odd number. # include<stdio.h> # include<conio.h> void main() { int num[9],i,counte=0,countod=0; clrscr(); printf("\n Enter The 10 Numbers\n");
142
C Language
Solution
for(i=0;i<9;i++) { scanf("%d",&num[i]); } for(i=0;i<9;i++) { if( ( (num[i])%2 )==0) { counte=counte+1; } else if( (num[i])%2 !=0 ) { countod=countod+1; } } printf("The Count Of Odd Numbers Is %d\n",countod); printf("The Count Of EVEN Numbers Is %d\n",counte); getch(); } //2)Read 2 nos, print the biggest no. # include<stdio.h> # include<conio.h> void main() { int a,b;
143
C Language
Solution
clrscr(); printf("\n Enter The A and B Values\n"); scanf("%d %d",&a,&b); if(a==b) printf("\n Both Values Are Equal\n"); else if(a>b) printf("\n A is Greater \n"); else printf("\n B is Greater\n"); getch(); }
SOLUTION SET-9
//1)Print the series:2,4,8,16,32,.; stop after printing 200 nos. # include<stdio.h> # include<conio.h>
144
C Language
Solution
printf("\t %ld",i); i=i*2; if(i==200) break; } getch(); } //2)Print the series:2,4,8,16,32,; Stop when reached above 100. # include<stdio.h> # include<conio.h> //2 4 16 32 ...1024 void main() { long int i; clrscr(); for(i=2;i<=1024;) {
C Language
Solution
//3)Read a no; print if it is prime no or not. //Write a program to find the prime numbers #include<stdio.h> # include<conio.h> void main() { int n, c = 2; printf("Enter a number to check if it is prime\n"); scanf("%d",&n); for ( c = 2 ; c <= n - 1 ; c++ ) { if ( n%c == 0 ) { printf("%d is not prime.\n", n); break; } } if ( c == n ) printf("%d is prime.\n", n); getch(); }
SOLUTION SET-10
C Language
Solution
# include<conio.h> //2 4 6 8 20 void main() { int i; clrscr(); for(i=2;i<=20;) { printf("\t %d",i); i=i+2; } getch(); } //2) Print the series: 1,10,100,1000,10000 # include<stdio.h> # include<conio.h>
//1 10 100 1000 10,000 void main() { long int i; clrscr(); for(i=1;i<=10000;) { printf("\t %ld",i);
147
C Language
Solution
i=i*10; } getch(); }
SOLUTION SET-11
//1) Read n number: Ask the user [1/2] before proceeding to next number. Finall print the sum of all read number. #include<stdio.h> # include<conio.h> void main() { int i,sum=0,a[15],n,num; int w ; clrscr(); printf("\n Enter The No of Items To be Entered "); scanf("%d",&n); printf("\n Enter 1 to continue or 2 to exit\n"); scanf("%d",&w); if(w==1) { for(i=0;i<n;i++) { scanf("%d",&num); sum=sum+num;
148
C Language
Solution
//2) Display the following menu for selection. Then read the option, and do the appropriate action. a. b. c. d. Add Multiply Stop Choose your option[1-3]
# include<stdio.h> # include<conio.h> void main() { int ch,a,b,c; clrscr(); printf ("\n Enter The Choice 1->ADD 2->Multiply 3->Stop !!!\n"); scanf("%d",&ch); printf("\n Enter The A & B Values \n"); scanf("%d %d" ,&a,&b); switch(ch) {
149
C Language
Solution
case 1: { c=a+b; printf("\n The Addition Performed !!! %d\n",c); break; } case 2: { c=a*b; printf("\n The Subtraction Performed !!! %d\n",c); break; } case 3: { exit(0); } default: printf("\n Nothing !!!\n"); } getch(); }
SOLUTION SET-12
//1)Read n numbers; stop reading when zero is input. Finally print the sum of all read numbers. # include<stdio.h>
150
C Language
Solution
# include<conio.h> //read 10 num sum of read numbers stop if zero is input void main() { int a[10],i,sum=0; clrscr(); printf("\n Enter The Number's One By One\n"); for(i=0;i<9;i++) { scanf("%d",&a[i]); if(a[i]==0) break; sum=sum+a[i]; } printf("\n The Total Is %d\n",sum); getch(); } //2)Read age and print; But repeat to ask until an age not lesser that 25 is entered. # include<stdio.h> # include<conio.h> //read age until lesser than 25 void main() { int a[10],i; clrscr();
151
C Language
Solution
printf ("\n Enter The Age ->10 Values\n"); for(i=0;i<9;i++) { scanf("%d",&a[i]); if(a[i]<25) { printf("\n The Age Is Below 25\n"); break ; } else printf("The Age Is %d\n",a[i]); } getch(); }
//1)Print the series 10,9,8,7.1 # include<stdio.h> # include<conio.h> //Generate series 10 9 8 7 ...1 void main() { int i; clrscr(); for(i=10;i>=1;)
152
C Language
Solution
//2) Print the multiplication table for 2,3, &4 # include <stdio.h> # include <conio.h> void main() { int r, c, y, n ; clrscr() ; r=1; printf("Enter a number up to which you want tables: "); scanf("%d", &n); printf("\n\nThe multiplication table for first %d numbers is :\n\n", n) ; do { c=1; do { y=r*c; printf("%5d", y) ;
153
C Language
Solution
SOLUTION SET-14
//1)Read 10 numbers and store in an array. Print the sum of those numbers. # include<stdio.h> # include<conio.h> //read 10 num, sum of read numbers void main() { int a[10],i,sum=0; clrscr(); printf("\n Enter The Number's One By One\n"); for(i=0;i<9;i++) { scanf("%d",&a[i]); sum=sum+a[i]; } printf("\n The Total Is %d\n",sum); getch();
154
C Language
Solution
} //2) Read 10 numbers and store in an array Print the numbers that are 100 and above.
# include<stdio.h> # include<conio.h> void main() { int a[10]; int i,j; clrscr(); printf("\n Enter The Values One By One \n"); for(i=0;i<9;i++) { scanf("%d",&a[i]); } for(i=0;i<9;i++) for(j=i+1;j<=10;j++)
C Language
Solution
//3) Read 10 numbers and store in an array. But do not allow duplicates. # include<stdio.h> # include<conio.h> void main() { int a[10]; int i,j; clrscr(); printf("\n Enter The Values One By One \n"); for(i=0;i<9;i++) { scanf("%d",&a[i]); } for(i=0;i<9;i++) { for(j=i+1;j<=10;j++) { if(a[i]==a[j]) { printf("\n DUPLICATE VALUES ARE PRESENT \n"); break; } } } getch();
156
C Language
Solution
} //4) Read 5 numbers and store in an array. Check if any number is similar.Dont Repeat similar Nos # include<stdio.h> # include<conio.h> //Do Not Allow Repeated Values void main() { int a[10]; int i,j; clrscr(); printf("\n Enter The Values One By One \n"); for(i=0;i<9;i++) { scanf("%d",&a[i]);
C Language
Solution
} getch(); }
SOLUTION SET-15
//1)Read a 3 x 2 matrix, and print. # include<stdio.h> # include<conio.h> void main() { int a[3][2]; int i,j; clrscr(); //Reading printf("\n Enter Array Elements One By One \n"); for(i=0;i<3;i++) for(j=0;j<2;j++) scanf("%d\n",&a[i][j]); //Printing printf("\n The Array Elements Are ::\n"); for(i=0;i<3;i++) for(j=0;j<2;j++) printf("\t %d",a[i][j]);
getch();
158
C Language
Solution
} //2)Read roll no & five subject marks for 3 students and store in an array. Print the rollno and minimum marks obtained by each student. # include<stdio.h> # include<conio.h> // MIN PERCENTAGE MARK void main() { int i,phy,chem,mat,tot,temp; float avg,std[10],j;
clrscr();
for( i=1;i<=5;i++) { printf("\n Enter The Marks for Student No :: %d\n",i); scanf("%d",&phy); scanf("%d",&chem); scanf("%d",&mat); tot=phy+chem+mat ; avg=tot/3; std[i]=avg; } printf("\n Enter Student Roll No For Which Percentage Is To Be Displayed...\n"); scanf("%f",&j);
159
C Language
Solution
printf("\n PERCENTAGE TO BE DISPLAYED %f\n",std[j]); // MIN MARKS DISPLAYED for(i=1;i<=5;i++) for(j=i+1;j<=5;j++) if(std[i]<std[j]) { temp=std[i]; std[i]=std[j]; std[j]=temp; } printf("\n THE MIN PERCENTAGE IS %f \n",std[5]); getch(); }
//3)Read roll no & five subject marks for 3 students and store in an array. Print the all student totals of each subjects. # include<stdio.h> # include<conio.h> // TOTAL MARK void main() { int i,phy,chem,mat,tot,temp; int avg,std[10],j;
160
C Language
Solution
clrscr(); for( i=1;i<=5;i++) { printf("\n Enter The Marks for 5 Student No NumberWise :: %d\n",i); scanf("%d",&phy); scanf("%d",&chem); scanf("%d",&mat); tot=phy+chem+mat ; std[i]=tot; } printf("\n Enter Student RollNo For Which Total Is To Be Displayed...\n"); scanf("%d",&j); printf("\n TOTAL OF ROLLNO %d IS %d\n",j,std[j]); getch(); }
//4)Read rollno & five subject marks for 3 students and store in an array. Print the highest mark among all students and subjects. # include<stdio.h> # include<conio.h> // MAX MARK void main() { int i,phy,chem,mat,tot,temp; float avg,std[10],j;
161
C Language
Solution
clrscr(); for( i=1;i<=5;i++) { printf("\n Enter The Marks for Student No :: %d\n",i); scanf("%d",&phy); scanf("%d",&chem); scanf("%d",&mat); tot=phy+chem+mat ; avg=tot/3; std[i]=avg; } printf("\n Enter Student Roll No For Which Percentage Is To Be Displayed...\n"); scanf("%f",&j); printf("\n PERCENTAGE TO BE DISPLAYED %f\n",std[j]); // MAX MARKS DISPLAYED for(i=1;i<=5;i++) for(j=i+1;j<=5;j++) if(std[i]>std[j]) { temp=std[i]; std[i]=std[j]; std[j]=temp; } printf("\n THE MAX PERCENTAGE IS %f \n",std[5]); getch();
162
C Language
Solution
SOLUTION SET-16
//1)Read 10 numbers and store an array. Then read a number, search for it in the array, and print its position if found. # include<stdio.h> # include<conio.h> //Find position void main() { int a[10],num; int i,j; clrscr(); printf("\n Enter The Values One By One \n"); for(i=0;i<9;i++) { scanf("%d",&a[i]); } printf("\n Enter The Number\n"); scanf("%d",&num); for(i=0;i<9;i++) { if(a[i]==num) { printf("\n FOUND THE NUMBER \n"); printf("\n THE POSITION IS %d \n",i);
163
C Language
Solution
} } getch(); }
//2)Read 10 numbers and store in an array. Then read a numbers, search for it in the array, and print no of times it is repeated. # include<stdio.h> # include<conio.h> // No of times values are Repeated void main() { int a[10],count=0; int i,j; clrscr(); printf("\n Enter The Values One By One \n"); for(i=0;i<9;i++) { scanf("%d",&a[i]);
164
C Language
Solution
printf("\n REPEATED NUMBER\n"); count =count+1; break; } } } printf("The No of Times Values Are Repeated %d\n",count); getch(); }
//3)Read roll no & percentage for 5 students ad store in an array. Then read a roll no, search and print his percentage. # include<stdio.h> # include<conio.h> // MAX MARK void main() { int i,phy,chem,mat,tot,temp; float avg,std[10],j; clrscr(); for( i=1;i<=5;i++) { printf("\n Enter The Marks for Student No :: %d\n",i); scanf("%d",&phy); scanf("%d",&chem);
165
C Language
Solution
scanf("%d",&mat); tot=phy+chem+mat ; avg=tot/3; std[i]=avg; } printf("\n Enter Student Roll No For Which Percentage Is To Be Displayed...\n"); scanf("%f",&j); printf("\n Percentage Displayed for the above Mentioned RollNo Is %f\n",std[j]); getch(); }
SOLUTION SET-17
//1) Write a program to concat the two strings # include<stdio.h> # include<conio.h> # include<string.h> void main() { char s1[45],s2[45]; clrscr(); printf(Enter The String1\n); scanf(%s,s1); printf(Enter The String2\n); scanf(%s,s2); strcat(s1,s2);
166
C Language
Solution
printf(The Output String Is %s\n,s1); getch(); } //2) Write a program to Reverse Strings # include <stdio.h> # include<conio.h> # include<string.h> void main() { char s1[45]; clrscr(); printf(Enter The String\n); scanf(%s,s1); strrev(s1); printf(The Reversed String %s\n,s1); getch();
//3)Write a program for Comparing Strings # include<stdio.h> # include<conio.h> # include<string.h> void main() { char s1[45],s2[45]; clrscr();
167
C Language
Solution
printf(Enter The String1\n); scanf(%s,s1); printf(Enter The String2\n); scanf(%s,s2); if(strcmp(s1,s2)==0) printf(The Two Strings Are Equal\n) else printf(Two Strings Are Not Equal\n); getch(); } //4)Write a program for Palindrome # include<stdio.h> # include<conio.h> # include<string.h> void main() { char s1[45],s2[45]; clrscr(); printf(Enter The String1\n); scanf(%s,s1); strcpy(s2,s1); strrev(s2); if(strcmp(s1,s2)==0) printf(Its a palindrome\n); else
168
C Language
Solution
printf(Its Not a palindrome..\n); getch(); } //5)Write a program for vowel count # include<stdio.h> # include<conio.h> void main() { char c; int count=0; clrscr(); printf("\n Enter The Character\n"); scanf("%c",&c); if(c=='a'|| c=='e'|| c=='i'|| c=='o'|| c== 'u') { printf("It's a Vowel \n"); count = count+1; } else printf("\n It's Not Vowel \n"); printf("\n The count of vowel is %d\n",count); getch(); }
169
C Language
Solution
SOLUTION SET-18
//1) Create a function that accepts a number and prints the square and cube values. //Square & cube # include<stdio.h> # include<conio.h> int num,rr,n2,rr1,k1; void main() { clrscr(); printf("\n Enter The Number\n"); scanf("%d",&num); rr=cube(num); rr1=sq(num); printf("\n The Cube Of Given Number Is %d\n",rr); printf("\n The Square Of Given Number Is %d\n",rr1); getch(); } int cube(int n1) { n2=(n1*n1*n1); return n2; } int sq(int k) {
170
C Language
Solution
k1=(k*k); return k1; } //2) Create a function that accepts a number prints cube value. //cube # include<stdio.h> # include<conio.h> int num,rr,n2; void main() { clrscr(); printf("\n Enter The Number\n"); scanf("%d",&num); rr=cube(num); printf("\n The Cube Of Given Number Is %d\n",rr); getch(); } int cube(int n1) { n2=(n1*n1*n1); return n2; }
171
C Language
Solution
//3)Create a function that accepts a number and returns its factorial. # include<stdio.h> # include<conio.h> //Program To Find the Factorial of a number int num,i,k,fact=1,n1,rr; void main() { clrscr(); printf("Enter The Number For Which Factorial is to b Calculated\n"); scanf("%d",&num); rr=funct(num); printf("The Factorial Of Given No is %d\n",rr); getch(); }
172
C Language
Solution
return fact; }
4)Create a function that accepts a number and returns whether it is a prime number or not. #include<stdio.h> # include<conio.h> void main() { clrscr(); primnum(); getch(); } primnum() { int n, c = 2; printf("Enter a number to check if it is prime\n"); scanf("%d",&n); for ( c = 2 ; c <= n - 1 ; c++ ) { if ( n%c == 0 ) { printf("%d is not prime.\n", n); break; } }
173
C Language
Solution
SOLUTION SET-19
//1) Write a program to get the employee details and print it(Use Structures) # include<stdio.h> # include<conio.h> struct emp { char name[45]; int no; float sal; }; struct emp e1; void main() { clrscr(); printf("Enter The Name :\n"); scanf("%s",e1.name); printf("Enter The No:\n"); scanf("%d",&e1.no); printf("Enter The Salary :\n"); scanf("%f",&e1.sal);
174
C Language
Solution
disp(); getch(); } disp() { printf("The Name Is : %s\n",e1.name); printf("The No Is : %d\n",e1.no); printf("The Salary Is : %f\n",e1.sal); return 0; }
//2) Write a program to get company details & employee details .Print the details(Use Nested Structures) # include<stdio.h> # include<conio.h> struct comp { char name[45]; char addr[45]; struct sales { char spname[45]; int no ; float sal; }s1;
175
C Language
Solution
}c1; void main() { clrscr(); printf("Enter The Company Name :\n"); scanf("%s",c1.name); printf("Enter The Company Address:\n"); scanf("%s",c1.addr); printf("Enter The Sales Person Name :\n"); scanf("%s",c1.s1.spname); printf("Enter The Sales Person No:\n"); scanf("%d",&c1.s1.no); printf("Enter The Salary:\n"); scanf("%f",&c1.s1.sal); disp(); getch(); } disp() { printf("The Company Name Is :%s\n",c1.name); printf("The Company Address: %s\n",c1.addr); printf("The Sales Person Name : %s\n",c1.s1.spname); printf("The Sales Person No: %d\n",c1.s1.no); printf("The Salary: %f\n",c1.s1.sal);
176
C Language
Solution
return 0; }
//3) Write a program to get employee details and print it(Use Pointers as tag name) #include<stdio.h> # include<conio.h> struct emp { int no; float sal; }; struct emp *e1; void main() { clrscr(); printf("Enter The No:\n"); fflush(stdin); scanf("%d",&e1->no); printf("Enter The Salary :\n"); scanf("%f",&e1->sal); disp(); getch(); } disp()
177
C Language
Solution
// 1.Write a program to write content in to a file # include<stdio.h> # include<stdlib.h> # include<string.h> void main() { FILE *fp; Char s[80]; fp=fopen(pt.txt,w); if(fp==NULL) { puts(Cannot open file); exit(1); } printf(\n Enter a few lines of text\n); while(strlen(gets(s)>0) { fputs(s,fp);
178
C Language
Solution
fputs(\n,fp); fclose(fp); } //2) .Write a program to Read & Write content to a file #include<stdio.h> #include<conio.h> void main() { FILE *f1; char c; int op; clrscr(); f1=fopen("abc.txt","a+"); while(5) { clrscr(); printf("\n Type 1 for reading and 2 for writing and 3 for exit \n"); scanf("%d",&op); if(op==1) { rewind(f1); printf("\n The file 'abc' has the matter of following\n "); while(!feof(f1)) { c=getc(f1);
179
C Language
Solution
putchar(c); } } else if(op==2) { printf("\n Finish yr message with symbol 'n' \n"); while( (c=getchar())!=EOF) putc(c,f1); } else break; getch(); } fclose(f1); getch(); } //3) Write a program which writes content to a file using structures //Structure & Files # include<stdio.h> # include<conio.h> void main() { FILE *fp; char another=Y; struct emp
180
C Language
Solution
{ char name[40]; int age; float bs; }; struct emp e; fp=fopen(EMPLOYEE.DAT,w); if( fp ==NULL) { puts(Cannot open file); exit(1); } while(another==Y) { printf(\n Enter Name, Age and Basic salary:); scanf(%s %d %f,e.name,&e.age,&e.bs); fprintf(fp,%s %d %f \n,e.name,e.age,e.bs); printf(Add another recordY/N); fflush(stdin); another =getche(); } fclose(fp); } }
181
C Language
Solution
182