C Is Easy

3,143 views

Published on

C is known as first programming language for programers.As the time grows, many languages developed like C++, Java and many more.But still C is in demand and it is first programming language we learned in our school & college. So first should be easy to learn. In this book, I try to elaborate the C contents in a easy manner so it's make "C Is Easy" for begginner.

Published in: Education
0 Comments
14 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,143
On SlideShare
0
From Embeds
0
Number of Embeds
13
Actions
Shares
0
Downloads
0
Comments
0
Likes
14
Embeds 0
No embeds

No notes for slide

C Is Easy

  1. 1. C-LANGUAGE @iDiary By Sharmistha
  2. 2. C-LANGUAGE@iDiary i About the Author The author of this book is well qualified. She has done MCA and then M. Phill. She has 2+ years Developing and Training experience. She provides the training in C, C++ & Java. She is recently exploring android and hope will published next book very soon.
  3. 3. C-LANGUAGE@iDiary ii Acknowledgements It was a great journey when I started to wrote a c book. During this journey I have met so many students, developers, professors, publishers and authors who expressed their opinions about my book. They have been the main motivators in my effort to continuously improve this book. In particular I am indebted to iDiarySoft Pvt. Ltd. who had a faith in this book idea, believed in my writing ability, whispered the words of encouragement and made helpful suggestions from time to time. And finally my heartfelt gratitude to the countless students who made me looks into every nook and my loving family. I would forever remain indebted to them.
  4. 4. C-LANGUAGE@iDiary iii Table of Contents OVERVIEW OF C ............................................................................................................................1  History of C ............................................................................................................................1  Importance of C......................................................................................................................1  Programming style .................................................................................................................3  Basic structure of C program ...................................................................................................4  Compiling and Running a C program........................................................................................8 UNDERSTANDING MEMORY MAP ................................................................................................12  Memory organization: DOS as Case study ..............................................................................12  Program memory area at runtime .........................................................................................13 CONSTANTS, VARIABLES & DATA TYPES.......................................................................................15  Character set, C Tokens.........................................................................................................15  Keywords & Identifiers..........................................................................................................16  Data type & its memory representation.................................................................................19  Format Specifier...................................................................................................................20  Overflow & Underflow of data ..............................................................................................22 OPERATORS & EXPRESSIONS .......................................................................................................24  8 types of Operators.............................................................................................................24  Bitwise Operators explained..................................................................................................33  Operator precedence............................................................................................................37  Operator associativity...........................................................................................................37  Type conversion in expression...............................................................................................38 CONTROL STRUCTURES: BRANCHING ...........................................................................................40  Decision making with if statement ........................................................................................40  If….else statement ...............................................................................................................41  Nested if …..else statement ..................................................................................................43  Else ….if ladder.....................................................................................................................45  Switch statement .................................................................................................................47  GOTO statement .................................................................................................................50 CONTROL STRUCTURES: LOOPING................................................................................................53  For Loop ..............................................................................................................................53  While Loop...........................................................................................................................56  Do – While Loop...................................................................................................................59
  5. 5. C-LANGUAGE@iDiary iv  Jumps in loop.......................................................................................................................62 o Break.......................................................................................................................63 o Continue..................................................................................................................64 ARRAYS & STRINGS .....................................................................................................................68  Benefits of an Array..............................................................................................................69  Types of arrays (1D , 2D , Multi-D) ........................................................................................69  Limitations of an array ..........................................................................................................83  Manipulating a String............................................................................................................83  Arrays of Strings ...................................................................................................................85  Comparison of Strings...........................................................................................................86  String handling functions ......................................................................................................87 HANDLING POINTERS ..................................................................................................................89  Understanding basics of Pointers...........................................................................................89  Rules for Pointers .................................................................................................................91  Pointer declaration...............................................................................................................92  Accessing a variable through its Pointer.................................................................................92  Pointer to Pointer.................................................................................................................93  Pointers and Arrays ..............................................................................................................94  Array of Pointers ..................................................................................................................96  Common Pointer Pitfalls .......................................................................................................97 FUNCTIONS .................................................................................................................................99  Why Functions .....................................................................................................................99  Types of Functions..............................................................................................................100  Function type based on signature........................................................................................101  Passing Parameters to a function.........................................................................................110  Some facts about function ..................................................................................................112  Recursion...........................................................................................................................114 STRUCTURES & UNIONS.............................................................................................................116  Defining a structure............................................................................................................116  Structure initialization.........................................................................................................116  Structure with Array ...........................................................................................................118  Structure and Function .......................................................................................................120  Structure and Pointer .........................................................................................................123  Structures within structures................................................................................................125  Unions & its properties .......................................................................................................127  Difference between Union and Structure.............................................................................130
  6. 6. C-LANGUAGE@iDiary v  Application of Union...........................................................................................................132 FILE HANDLING IN C...............................................................................................................135  What is a File? .................................................................................................................135  File Structure....................................................................................................................135  Defining, Opening a file....................................................................................................135  Closing a file.....................................................................................................................137  Input/ Output Operations on files ...................................................................................138
  7. 7. C-LANGUAGE@iDiary 1 OVERVIEW OF C Before we can begin to write serious programs in C, it would be interesting to find out what really is C, how it came into existence and how does it compare with other computer languages. The purpose of this chapter is to present an overview of the C programming language, its origins, its uses, and its underlying philosophy. This chapter is mainly for newcomers to C. History of C C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. C is the result of a development process that started with an older language called BCPL. BCPL was developed by Martin Richards, and it influenced a language called B, which was invented by Ken Thompson. B led to the development of C. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. Fig 1.1 : Evolution of C
  8. 8. C-LANGUAGE@iDiary 2 Importance of C 1- C is often called a middle-level computer language. You all aware about low-level(e.g machine language) and high-level(e.g java ), but you’ll surprise why I told C a middle-level computer language. But I yelled because it combines the best elements of high-level languages with the control and flexibility of assembly language. It can interact with hardware at quiet a low level. You write very low-level stuff (like device-drivers and such) that runs almost as fast as assembly-written programs. 2- I suppose C provide the platform to learn programming languages then after you can switch to any programming language. Once you master c, you'll have the potential to get mastering with other languages because till then you will deal with basic concepts. 3- Major parts of popular operating systems like Windows, UNIX, Linux is still written in C. This is because even today when it comes to performance (speed of execution) nothing beats C. Moreover, if one is to extend the operating system to work with new devices one needs to write device driver programs. These programs are exclusively written in C. 4- C is elaborate much that why you can find the solutions of your problem from many resources like e-books, forums & blogs as well as you will get so many source codes regarding your problem which you face at the time of developing software. 5- Mobile devices like cellular phones and palmtops are becoming increasingly popular. C language still can be used to develop the portable platforms such as smart phones. 6- C is used to create embedded systems like microwave oven, washing machines and digital cameras. These programs not only have to run fast but also have to work in limited amount of memory. With these constraints on time and space, C is the language of choice while building such operating systems and programs.
  9. 9. C-LANGUAGE@iDiary 3 7- At times one is required to very closely interact with the hardware devices. Since C provides several language elements that make this interaction feasible without compromising the performance it is the preferred choice of the programmer. My advice would be to learn C, and then add C++ to that afterwards. Later you can learn C# and Java, which should be easier to learn when you know C and C++ first. I think till now you will be understand why I am force to learn C , because you can’t start from X,Y,Z…. You need the basic that is A,B,C.. i.e. C programming got it. Programming Style Programming style is a set of rules or guidelines used when writing the source code for a computer program. It helps the programmers to read and understand source code conforming to the style, and help to avoid introducing errors. Below mentioned tips is enough for a good programming style. 1- Try to keep your programs simple and clear means the purpose of every variable and every function should be clear. Functions, data structures, and variable names make sense to you in the future for example if you creating a variable which store age then give the name age to variable. 2- There is a style of programming that believes that every line of source code should have a comment associated with it, because it’ll guide the programmer for future changes without much effort. 3- Code should be structured so the underlying algorithms are clearly visible. Try to keep each function short and let it have a single purpose. If details need to be handled, let a support function take care of them. 4- The visual layout of a program is crucial to its readability. Blocks (code between { and } ) should be indented. In the below mentioned code it is easy to understand when the block is start and closed.
  10. 10. C-LANGUAGE@iDiary 4 Basic Structure of C Program The structure of a C program is a protocol (rules) to the programmer, while writing a C program. The general basic structure of C program is shown in the figure below. The whole program is controlled within main ( ) along with left brace denoted by “{” and right braces denoted by “}”. If you need to declare local variables and executable program structures are enclosed within “{” and “}” is called the body of the main function. The main ( ) function can be preceded by documentation, preprocessor statements and global declarations. Fig 1.2 Fig 1.3
  11. 11. C-LANGUAGE@iDiary 5 Now, I will explain each part one by one thoroughly. Documentations The documentation section consist of a set of comment lines giving the name of the program, the another name and other details, which the programmer would like to use later. Preprocessor Statements The preprocessor statement begin with # symbol and are also called the preprocessor directive. These statements instruct the compiler to include C preprocessors such as header files and symbolic constants before compiling the C program. Some of the preprocessor statements are listed below. Global Declarations The variables are declared before the main ( ) is called global variables. These global variables can be accessed by all the user defined functions including main ( ) function. Fig 1.4
  12. 12. C-LANGUAGE@iDiary 6 The main ( ) function Each and every C program should contain only one main ( ). The C program execution starts with main ( ) function. No C program is executed without the main function. The main ( ) function should be written in small letters and it should not be terminated by semicolon. The main( ) executes user defined program statements, library functions and user defined functions and all these statements should be enclosed within left and right braces. Braces Every C program should have a pair of curly braces ({, }). The left braces indicates the beginning of the main ( ) function and the right braces indicates the end of the main ( ) function. These braces can also be used to indicate the user-defined functions beginning and ending. These two braces can also be used in compound statements. Local Declarations The variable declaration is a part of C program and all the variables are used in main ( ) function should be declared in the local declaration Fig 1.5
  13. 13. C-LANGUAGE@iDiary 7 section is called local variables. Not only variables, we can also declare arrays, functions, pointers etc. These variables can also be initialized with basic data types. For examples :- void main ( ) { int sum = 0 ; int x ; float y ; } Here, the variable sum is declared as integer variable and it is initialized to zero. Other variables declared as int and float and these variables inside any function are called local variables. Program statements These statements are building blocks of a program. They represent instructions to the computer to perform a specific task .An instruction may contain an input-output statements, arithmetic statements, control statements, simple assignment statements and any other statements and it also includes comments that are enclosed within /* and */ . The comment statements are not compiled and executed and each executable statement should be terminated with semicolon. User defined functions These are subprograms, generally, a subprogram is a function and these functions are written by the user are called user defined functions. These functions are performed by user to do some specific tasks and this also contains set of program statements. They may be written before or after a main () function and called within main () function. This is an optional to the programmer. Now, I am writing a small program which will print welcome message. # include <stdio.h> void main() {
  14. 14. C-LANGUAGE@iDiary 8 printf ("welcome to the world of C/n"); } In the first line of above code we include a file called stdio.h (Standard Input/Output header file). This file contains lot of built-in function for input or output which we can use in our program. For instance it has commands for input like reading from the keyboard and output commands like printing things on the screen. Every program must have a main(). It is the starting point of every program. The two curly brackets ({}) are used to group all commands together. In this case all the commands between the two curly brackets belong to main(). The curly brackets are often used in the C language to group commands together. The printf is used for printing things on the screen. In the above example it will print “welcome to the C World”. As you can see the data that is to be printed is put inside round brackets. The words Hello World are inside inverted commas, because they are what is called a string. Strings must always be put between inverted commas. The n is called an escape sequence. In this case it represents a newline character. After printing something to the screen you usually want to print something on the next line. If there is no n then a next printf command will print the string on the same line. I hope you have understood about the basic structure of C language. Compiling and Running a C Program Compilation Compilation refers to the processing of source code files and the creation of an 'object' file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. For instance, if you compile three separate files, you will
  15. 15. C-LANGUAGE@iDiary 9 have three object files created as output, each with the name <filename>.o or <filename>.obj. Each of these files contains a translation of your source code file into a machine language file but this is not executable file. If you need to turn them into executables your operating system can use. That's where the linker comes in. Linking Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned. . It resolves references to external symbols, assigns final addresses to procedures/functions and variables, and revises code and data to reflect new addresses. Fig 1.6
  16. 16. C-LANGUAGE@iDiary 10 Compiling C programs requires you to work with four kinds of files: 1. Source code files  These files contain the instruction written in C language and have names which end with ".c". 2. Header files  Header file contains different predefined functions, which are required to run the program. All prototypes of standard input/output functions are stored in header file 'stdio.h' while console input/output functions are stored in 'conio.h'. 3. Object files These files are produced as the output of the compiler. They consist of function definitions in binary form, but they are not executable by themselves. Object files end with ".obj". 4. Binary executables These are produced as the output of a program called a "linker". The linker links together a number of object files to produce a binary file which can be directly executed. Binary executables end with ".exe" on Windows. Running the program The next stage is to actually run your executable program. To run an executable in UNIX, you simply type the name of the file containing it.This executes your program, printing any results to the screen. At this stage there may be run-time errors, such as division by zero, or it may become evident that the program has produced incorrect output. If so, you must return to edit your program source, and recompile it, and run it again.
  17. 17. C-LANGUAGE@iDiary 11 Exersise :- 1. Who developed C programming language? 2. Why is C language called middle level language? 3. How many main functions can be there in a c program? 4. Can a function call itself? If yes, where does it return to? Fig 1.7
  18. 18. C-LANGUAGE@iDiary 12 UNDERSTANDING MEMORY MAP A memory map is a structure of data that indicates how memory is laid out. Memory maps can have a different meaning in different parts of the operating system. In C programs, a memory map refers to the mapping between loaded executable/library files and memory regions. These memory maps are used to resolve memory addresses such as function pointers to actual symbols. Memory Organization: Dos as Case study You are all aware that a C program which is compiled to an executable and loaded into memory for execution has 4 main segments in memory. They are data, code, stack, and heap segments. Fig 1.8
  19. 19. C-LANGUAGE@iDiary 13 Figure :- Memory Organization Program memory at Runtime I already mentioned a compiled C program creates and uses four logically distinct segment of memory. I start from the very first (bottom to top) segment named code that actually holds the program's executable code. The next segment named Data is used to store global variables. The remaining two segments are the stack and the heap. The stack is used to holds the return addresses of function calls, arguments to functions, and local variables. It will also save the current state of the CPU. The heap is a segment of free memory that your program can use for dynamic memory allocation, such as the use of the malloc function, memory is allocated in the heap area. Fig 1.9 :- Memory Utilization at Runtime Although the exact physical layout of each of the four regions of memory differs among CPU types and C implementations, the diagram in Figure shows conceptually how your C programs appear in memory.
  20. 20. C-LANGUAGE@iDiary 14 Exercise:- 1. What is memory map? 2. How many segment created by compile C program? 3. What is heap?
  21. 21. C-LANGUAGE@iDiary 15 CONSTANTS, VARIABLES & DATA TYPES A ‘constant’ is an entity that does not change, but a ‘variable’ as the name suggests may change. We do a number of calculations in a computer and the computed values are stored in some memory spaces. In order to retrieve and re-use those values from the computer’s memory locations they are given names. Since the value stored in each location may change, the names given to these locations are called as ‘variable names’. The type of data a variable can store is known as ‘data type’. The C Character Set A character denotes any alphabet, digit or special symbol used to represent information. The following are the valid alphabets, numbers and special symbols permitted in C. The alphabets, numbers and special symbols when properly combined form constants, variables and keywords. C Tokens In a C source program, the basic element recognized by the compiler is the "token”. It may be a single character or a sequence of characters to form a single item. The tokens can be Fig 2.0
  22. 22. C-LANGUAGE@iDiary 16 The keywords, constants, identifiers, string literals, and operators described in this section are examples of tokens. Punctuation characters such as brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens. Keywords Keywords are the words whose meaning has already been explained to the C compiler. That’s why keywords are also known as ‘Reserved words’. Keep in mind that C is a case-sensitive language, and it requires that all keywords be in lowercase. The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. There are only 32 keywords available in C. The C language uses the following keywords: Fig 2.1
  23. 23. C-LANGUAGE@iDiary 17 Constants Constants refer to fixed values that the program may not alter. Constants can be of any of the basic data types. For examples:- Identifiers In C, the names of variables, functions, labels, and various other user- defined items are called Identifiers. The first character must be a letter or an underscore, and subsequent characters must be letters, digits, or underscores. Here are some correct and incorrect identifier names: Correct Incorrect count 1count int age; integer variable declared named age age = 29; here constant value is 29 char letter; Character variable declared named letter letter=’a’ here constant vale is ‘a’ Fig 2.2
  24. 24. C-LANGUAGE@iDiary 18 test23 hi!there high_balance high . . . balance String - literal A string literal is a set of characters enclosed in double quotes. For example, ''this is a test" is a string literal. If a single character is enclosed within a pair of double quotes, it will also be interpreted as a string literal and not a character constant. Every string is terminated by a null character (‘0’). Punctuators A punctuator is a token that has syntactic and semantic meaning to the compiler, but the exact significance depends on the context. [ ] ( ) { } , : ; * = ... # . -> ++ -- ## & + - ~ ! / % << >> != < > <= >= == ^ | && || ? *= /= %= += -= <<= >>= &= ^= |= Table . C and C++ punctuators Operator An operator is a symbol that tells the computer to perform certain mathematical and logical manipulation on data stored in variable. + , - ,
  25. 25. C-LANGUAGE@iDiary 19 > , ++ etc are all operators. We will discuss operator in detail in further chapter. Data type & its memory representation The data type of a variable is important because it determines the operations that are allowed on it and the range of values that can be stored. C defines several types of data, and each type has unique characteristics. Because data types differ, all variables must be declared prior to their use, and a variable declaration always includes a type specifier. The compiler requires this information in order to generate correct code. The four basic data types are INTEGER :- These are whole numbers, both positive and negative. Unsigned integers (positive values only) are supported. In addition, there are short and long integers. The keyword used to define integers is, int. An example of an integer value is 32. An example of declaring an integer variable called sum is, int sum; sum = 20; FLOATING POINT :-These are numbers which contain fractional parts, both positive and negative. The keyword used to define float variables is, float An example of a float value is 34.12. An example of declaring a float variable called money is, float money; money = 0.12; DOUBLE :-These are exponetional numbers, both positive and negative. The keyword used to define double variables is, double An example of a double value is 3.0E2. An example of declaring a double variable called big is, double big; big = 312E+7;
  26. 26. C-LANGUAGE@iDiary 20 CHARACTER :-These are single characters. The keyword used to define character variables is, char An example of a character value is the letter A. An example of declaring a character variable called letter is, char letter; letter = 'A'; The assignment of the character A to the variable letter is done by enclosing the value in single quotes. Sample program illustrating each data type #include < stdio.h > void main() { int sum; float money; char letter; double pi; sum = 10; /* assign integer value */ money = 2.21; /* assign float value */ letter = 'A'; /* assign character value */ pi = 2.01E6; /* assign a double value */ printf("value of sum = %dn", sum ); printf("value of money = %fn", money ); printf("value of letter = %cn", letter ); printf("value of pi = %en", pi ); } Sample program output value of sum = 10 value of money = 2.210000 value of letter = A value of pi = 2.010000e+06 Format Specifier The "Format specifier"(e.g %d,%f) is the sequence passed as the formatting string argument; "Characters matched" gives the format of the sequence sought or printed, with a hyperlink to the section on literals which applies to that format; "Argument type" gives the type of
  27. 27. C-LANGUAGE@iDiary 21 expression expected by printf and of pointer expected by scanf. There are many format specifiers defined in C This table shows the format specifiers used by scanf and printf. Sample program illustrating Format Specifier #include<stdio.h> void main() Fig 2.3 Fig 2.4
  28. 28. C-LANGUAGE@iDiary 22 { int a,b; float c,d; a = 15; b = a / 2; printf("%dn",b); printf("%3dn",b); printf("%03dn",b); c = 15.3; d = c / 3; printf("%3.2fn",d); } Sample program output 7 7 007 5.10 Overflow & Underflow of data Buffer overflows, both on the stack and on the heap, are a major source of security vulnerabilities in C code. Every time your program solicits input (whether from a user, from a file, over a network, or by some other means), there is a potential to receive inappropriate data. For example, the input data might be longer than what you have reserved room for in memory. When the input data is longer than will fit in the reserved space, if you do not truncate it, that data will overwrite other data in memory. When this happens, it is called a buffer overflow. If the memory overwritten contained data essential to the operation of the program, this overflow causes a bug that, being intermittent, might be very hard to find. If the overwritten data includes the address of other code to be executed and the user has done this deliberately, the user can point to malicious code that your program will then execute. Similarly, when the input data is or appears to be shorter than the reserved space (due to erroneous assumptions, incorrect length values, or
  29. 29. C-LANGUAGE@iDiary 23 copying raw data as a C string), this is called a buffer underflow. This can cause any number of problems from incorrect behavior to leaking data that is currently on the stack or heap. Although most programming languages check input against storage to prevent buffer overflows and underflows, C, Objective-C, and C++ do not. Because many programs link to C libraries, vulnerabilities in standard libraries can cause vulnerabilities even in programs written in “safe” languages. For this reason, even if you are confident that your code is free of buffer overflow problems, you should limit exposure by running with the least privileges possible. Exercise:- 1. What is variable? Can we used a keyword as a variable name? 2. Define Data types and its memory representation? 3. What is formatted string? Define it with example.
  30. 30. C-LANGUAGE@iDiary 24 OPERATORS & EXPRESSIONS C is very rich in built-in operators. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation on data stored in variables. The variables that are operated are termed as operands. While an expression is a combination of variables, constants and operators arranged according to syntax of the language. Some examples of expressions are: 8 Types of operators C programming language provides several operators to perform different kind to operations. These operators can be classified into a number of categories. They are as follows:- 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operator 5. Increment and decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators Arithmetic Operators operands c = (m + n) * (a - b) ; expression operators Fig 2.5
  31. 31. C-LANGUAGE@iDiary 25 Arithmetic operators work on numeric type of operands. C provides all the basic arithmetic operators. There are five arithmetic operators in C. Operator Purpose Example Result + Addition 3 + 6 9 - Subtraction 7 - 5 2 * Multiplication 5 * 2 10 / Division 6 / 3 2 % Remainder 5 % 2 1 Table . Arithmetic Operator Remember that in the Division operation you can’t divide any integer by zero. Otherwise it will shown “Divide by Zero” exception. Sample program illustrating arithmetic operations #include < stdio.h > void main() { int a = 100 ; /* assign integer value to a */ int b = 3 ; /* assign integer value to b */ int c ; /* declare a variable c */ c = a + b ; /* addition operation performed */ printf("a + b = %dn", c ); c = a - b ; /* substraction operation performed */ printf("a - b = %dn", c ); c = a * b ; /* multiplication operation performed */ printf("a * b = %dn", c ); c = a / b ; /* division operation performed */ printf("a / b = %dn", c ); c = a % b ; /* remainder operation performed */ printf("a % b = %dn", c ); }
  32. 32. C-LANGUAGE@iDiary 26 Sample program output a + b = 103 a - b = 97 a * b = 300 a / b = 33 a % b = 1 In the above sample program you will confuse in division operation why it gave the output 33. Then don’t be panic ; the reason behind this you are using integer data type that’s why it truncated the decimal value. For example :- 100/3= 33.333.. , it’ll show 33 remaining part will be truncated. In above examples we have only used integers variables. When you use an operator on mixed type they will be implicitly converted into a common type before the operation is performed. The common type is derived using a few rules, but generally, a “smaller” operand is converted to the “larger” operand’s type. Let us look at some examples:- Sample program illustrating Implicit Conversion #include < stdio.h > void main() { int a = 65000 ; char c = 120 ; int iresult ; char cresult ; iresult = a + c ; printf(“a + c = %dn”, iresult) ; cresult = a+c ; printf(“a + c = %dn”, cresult ) ; } Sample program output a + b = 65120 a + b = 96
  33. 33. C-LANGUAGE@iDiary 27 In the above sample program first c is converted to an int and then added to a. This value is assigned to iresult. But in the next case result is assigned to char. The binary representation of 65120 is 1111111001100000. Since the size of char is 8 bits, so it gives 01100000 , which means 96 in decimal. Relational operators Relational operator is used to compare two operands to see whether they are equal to each other, unequal, or one is greater or lesser than the other and as result return 1 for true or o for false. Operator Purpose Example Result = = Equal to (i) 3 = = 6 (ii) 6 = = 6 False True ! = Not equal to (i) 3 ! = 3 (ii) 6 ! = 3 False True < Less than (i) 7 < 6 (ii) 6 < 8 False True < = Less than or equal to (i) 3 < = 1 (ii) 6 < = 8 (iii) 6 < = 6 False True True > Greater than (i) 2 > 10 (ii) 10 > 8 False True > = Greater than or equal to (i) 5 > = 6 (ii) 9 > = 8 (iii) 9 > = 9 False True True Table . Relational Operators Sample program illustrating relational operations #include < stdio.h > void main() 1 1 1 1 1 1 1 0 0 1 1 0 0 0 0 0 8 bits Fig 2.6
  34. 34. C-LANGUAGE@iDiary 28 { int i, j, k ; i =10 ; j = 5 ; k = i > j ; printf(“ %d ”, k ) ; /* it will print 1 because 1 means true */ } Sample program output 1 Logical operators Logical operators are used to combine two or more relational expressions. C provides three logical operators. 1-Logical AND ( && ) 2-Logical OR ( || ) 3-Logical NOT ( ! ) Logical AND Expression 1 Expression 2 Result True False False False True False False False False True True True Logical OR Expression 1 Expression 2 Result True False True False True True False False False True True True
  35. 35. C-LANGUAGE@iDiary 29 Logical NOT Expression Result True False False True Table . Logical AND, Logical OR, Logical NOT Sample program illustrating logical operators #include < stdio.h > void main() { int i, j, k ; i =10 ; j = 5 ; k = ( i > j ) && ( j > I ); // True && True = True printf(“ %d ”, k ) ; /* it will print 1 because 1 means true */ } Assignment Operators Assignment operators are used to store the result of an expression to a variable. An expression with assignment operator is of the following form :- Sample program illustrating relational operations #include < stdio.h > void main() { int i ; i = 5 ; /* value 5 assigned to variable i */ printf(“ %d ”, i ) ; Value is assigned to variable Variable = expression Fig 2.7
  36. 36. C-LANGUAGE@iDiary 30 i = i + 10 ; /* value 5 + 10 i.e. 15 assigned to variable i */ printf(“ n %d ”, i ); getch(); } Sample program output 5 15 Increment and Decrement Operators C has two very useful operators + + and - - called increment and decrement operators respectively. These are unary operators as they require only one operand. The operands must be a variable name. The operator ++ adds 1 to its operand, and – – subtracts 1. In other words: x = x+1; is the same as ++x; and x = x–1; is the same as x– –; . Table . Increament and Decreament Operator Both the increment and decrement operators may either prefix or postfix the operand. For example, x = x+1; can be written ++x; or x++; . When an increment or decrement operator precedes its operand, the
  37. 37. C-LANGUAGE@iDiary 31 increment or decrement operation is performed before obtaining the value of the operand for use in the expression. If the operator follows its operand, the value of the operand is obtained before incrementing or decrementing it. Sample program illustrating Increament/Decreament operations Ex: #include < stdio.h > void main() { int a = 10 , b =0 ; a++ ; printf(“n a = %d ”, a) ; b = ++ a ; printf(“n a = %d, b = %d ”, a, b) ; b = a++ ; printf(“n a = %d, b = %d ”, a, b) ; getch(); } Sample program output a = 11 a = 12 b = 12 a = 13 b =13 Ex: #include <stdio.h> #include <conio.h> void main() { int i=5; printf("%d",--i - ++i); printf("%d",++i + ++i); printf("%d",i++ + ++i); printf("%d",--i + ++i); getch(); }
  38. 38. C-LANGUAGE@iDiary 32 Sample program output 0 14 12 10 Ex: #include<stdio.h> void main( ) { int i = 3 , j = 4 , k ; k = i++ + --j ; printf("i = %d, j = %d, k = %d",i,j,k); getch(); } Sample program output i=4, j=3, k=6 Conditional Operators Conditional Operator (?:) is ternary operator (demands 3 operands), and is used in certain situations, replacing if-else condition phrases. Conditional operator’s shape is: Condition_phrase ? phrase1 : phrase2; If conditional_phrase is true, phrase1 is executed and whole phrase is assigned with value of this phrase1. If the conditional phrase is false, then phrase2 is executed, and whole phrase is assigned with phrase2 value. For example :- int a, b, c; ... c = a > b ? a : b; // if a>b "execute" a, else b Sample program illustrating Conditional Operation #include < stdio.h > void main() { Int a, b, c, d, e ;
  39. 39. C-LANGUAGE@iDiary 33 a = 5 ; b = 6 ; c = 12 ; d = 11 ; e =(a < b) ? c : d ; printf(“ e = %d ”, e); } Sample program output e= 12 Bitwise Operators Bitwise operators are used for manipulation of data at bit level. These operators are used for testing the bits, or shifting them right or left. These permit the programmer to access and manipulate individual bits within a piece of data. The various Bitwise Operators available in C are as follows:- Table . Bitwise Operator These operators can operate upon ints and chars but not on floats and doubles. Bits are numbered from zero onwards, increasing from right to left as shown below:
  40. 40. C-LANGUAGE@iDiary 34 One’s Complement In one’s complement change all the 0 bits to 1 and all the 1s to 0s. For example:- void main() { unsigned int Value=4; /* 4 = 0000 0100 */ Value = ~ Value; /* 251 = 1111 1011 */ } Bit shift The << operator shifts its first operand left by a number of bits given by its second operand, filling in new 0 bits at the right. Similarly, the >> operator shifts its first operand right. If the first operand is unsigned, >> fills in 0 bits from the left, but if the first operand is signed, >> might fill in 1 bits if the high-order bit was already 1. For example:- void main() { unsigned int Value=4; /* 4 = 0000 0100 */ unsigned int Shift=2; Value = Value << Shift; /* 16 = 0001 0000 */ Value <<= Shift; /* 64 = 0100 0000 */ Fig 2.8
  41. 41. C-LANGUAGE@iDiary 35 printf("%dn", Value); /* Prints 64 */ } Bitwise AND The & operator performs a bitwise AND on two integers. Each bit in the result is 1 only if both corresponding bits in the two input operands are 1. For example:- void main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a & b; /* 12 = 0000 1100 */ } Bitwise OR The | (vertical bar) operator performs a bitwise OR on two integers. Each bit in the result is 1 if either of the corresponding bits in the two input operands is 1. For example:- void main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a | b; /* 61 = 0011 1101 */ } Bitwise XOR The ^ (caret) operator performs a bitwise exclusive-OR on two integers. Each bit in the result is 1 if one, but not both, of the corresponding bits in the two input operands is 1. For example:- void main()
  42. 42. C-LANGUAGE@iDiary 36 { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a ^ b; /* 49 = 0011 0001 */ } Special Operator C language also provides number of special operators. These operators are as follows:- Operator Purpose Example sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return 4. & Returns the address of an variable. &a ; will give actual address of the variable. * Pointer to a variable. *a ; will pointer to a variable. , Link the related expressions together int x, y, z ; z = ( a = 10 , y = 20 , x + y) Table . Special Operator Sample program illustrating Conditional Operation Ex: #include < stdio.h > void main() { printf(“ %d , %d ” , sizeof ( int ) , sizeof ( float ) ) ; getch(); } Sample program output 2 , 4 The reason of this output is only because the machine on which this program was run allotted 2 bytes for int type and 4 bytes for float type.
  43. 43. C-LANGUAGE@iDiary 37 Operators Precedence & Associativity An expression may contain more than one operator. Which operator will execute first depends on its precedence. Operators of same precedence are evaluated from left to right or right to left, depending upon the level. This is known as Operator associativity. A complete list of operator precedence with their associativity as applicable in c is presented below. Operator Type Operator Associativity Primary Expression Operators () [] . -> expr++ expr-- left-to-right Unary Operators * & + - ! ~ ++expr - -expr (typecast) sizeof right-to-left Binary Operators * / % left-to-right + - >> << < > <= >= == != & ^ | && || Ternary Operator ?: right-to-left Assignment Operators = += -= *= /= %= >>= <<= &= ^= |= right-to-left Comma , left-to-right Sample program illustrating Operator Precedence Fig 2.9
  44. 44. C-LANGUAGE@iDiary 38 Ex: #include < stdio.h > void main() { int a = 9 ; int b = 4 ; int c = 6 ; printf(“ %d ” , a + b * c ) ; } Sample program output 33 Explanation a + b * c // put the value of a ,b , c = 9 + 4 * 6 // in + , * , multiplication has higher precedence =9 + 24 // 4 * 6 = 24 =33 // atlast + operator resolved, 9 +24 =33 Type Conversion in expression When expressions are evaluated the type of an operand is converted. These conversions may happen implicitly or explicitly. Fig 3.0: A type conversion Example
  45. 45. C-LANGUAGE@iDiary 39 Implicit conversion is done automatically. If the operands are of different types, the lower type is automatically converted into higher type before the operation proceeds. The final result of an expression is converted to the type of the variable on the left of the assignment sign before assigning the value to it. Explicit conversion is special programming instruction which specifies what data type to treat a variable as in a given expression. Sample program illustrating explicit conversion Ex: #include < stdio.h > void main() { double da = 3.3; double db = 3.3; double dc = 3.4; int result = (int)da + (int)db + (int)dc; // result == 9 printf(“ %d ” , result ) ; } Sample program output 9 Exercise:- 1. What is operator? Define increament and decreament operators? 2. What is the significance of ternary operator? 3. Define Bitwise operator.
  46. 46. C-LANGUAGE@iDiary 40 CONTROL STRUCTURES: BRANCHING Execution of a program is essentially sequential in nature. Statements are executed in the order of their appearance in program. But the statements that allow programmers to alter the sequential flow of execution of the program and control the flow are called control statements. Decision Making with if statement The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed. The general form of the if statement is if (expression) statement; else statement; where a statement may consist of a single statement, a block of statements, or nothing .The else clause is optional. Sample program illustrating if statement Ex: #include <stdio.h> void main() { int magic = 786 ; int guess ; printf (“ Enter your guess ”) ; scanf(“ %d ”, &guess) ; if( guess == magic ) printf (“ Congratulation ! You won ”) ; }
  47. 47. C-LANGUAGE@iDiary 41 In the program user will enter a number, which will be store in variable guess. Then the value compares with 786. If the value of variable guess is equal to 786 then the message “Congratulation ! You won” will be displayed in output screen . if it not match nothing will not be displayed. Ex: #include <stdio.h> #include <stdlib.h> void main() { int magic ; int guess ; magic = rand(); /* generate the magic no. */ printf (“ Enter your guess ”) ; scanf(“ %d ”, &guess) ; if( guess == magic ) printf (“ Congratulation ! You won ”) ; } Ex: #include <stdio.h> void main() { int iResponse = 0; printf("ntAC Control Unitn"); printf("n1tTurn the AC onn"); printf("2tTurn the AC offn"); printf("nEnter your selection: "); scanf("%d", &iResponse); if (iResponse == 1) printf("nAC is now onn"); if (iResponse == 2) printf("nAC is now offn"); } If… else statement Else part is optional. When the given condition is false then else part will be executed. I made changes in above program, now if your guess
  48. 48. C-LANGUAGE@iDiary 42 doesn’t match with the value of variable magic, then else part will be executed. Ex: #include <stdio.h> #include <stdlib.h> void main() { int magic ; int guess ; magic = rand(); /* generate the magic no. */ printf (“ Enter your guess ”) ; scanf(“ %d ”, &guess) ; if( guess == magic ) printf (“ Congratulation ! You won ”) ; else printf(“ Better luck next time”); } Below I have mentioned a flow chart and as well as source code for better understanding with if… else statement. Fig 3.1
  49. 49. C-LANGUAGE@iDiary 43 Sample program illustrating if...else statement Ex: #include <stdio.h> #include <stdlib.h> void main() { int temp ; printf (“ Enter the temperature ”) ; scanf(“ %d ”, &temp) ; if( temp >= 80 ) printf (“ Turn AC On ”) ; else printf (“ Turn AC Off ”) ; } Nested if… else statement Nested If statement means to use the if statement inside the other if statement. It is a conditional statement which is used when we want to check more than one condition at a time in a same program. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. If it found the condition is true then it executes the block of associated statements of true part else it goes to next condition to execute. Sample programs illustrating Nested if... else statement Ex : #include <stdio.h> void main() { int a = 5, b = 6, c = 1 ; if( a > b ) { if( a > c ) printf( “ a is greatest ” ) ;
  50. 50. C-LANGUAGE@iDiary 44 else printf( “ c is greatest ” ) ; } else { if( b > c ) printf( “ b is greatest ” ) ; else printf( “ c is greatest ” ) ; } } Ex : #include <stdio.h> void main() { int iSelection = 0; float fTransAmount = 0.0; float fBalance = 100.25; printf("ntATMn"); printf("n1tDeposit Fundsn"); printf("2tWithdraw Fundsn"); printf("nEnter your selection: "); scanf("%d", &iSelection); if (iSelection == 1) { printf("nEnter fund amount to deposit: "); scanf("%f", &fTransAmount); printf("nYour new balance is: $%.2fn", fBalance + fTransAmount); } //end if if (iSelection == 2) { printf("nEnter fund amount to withdraw: "); scanf("%f", &fTransAmount); if (fTransAmount > fBalance) /* if within a if printf("nInsufficient fundsn"); else
  51. 51. C-LANGUAGE@iDiary 45 printf("nYour new balance is $%.2fn", fBalance - fTransAmount); } //end if } //end main function else… if ladder When a series of many conditions have to be checked we may use the ladder else… if statement which takes the following general form. Syntax : if(condition 1) statement-1; else if(condition 2) statement-2; Fig 3.2
  52. 52. C-LANGUAGE@iDiary 46 else if(condition n) statement-n; else default statement; next statement; The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement – x . When all the condition becomes false, the final else containing the default statement will be executed. Below I have mentioned a flow chart and as well as source code for better understanding with if… else statement. Fig 3.3
  53. 53. C-LANGUAGE@iDiary 47 Sample program illustrating else…if ladder Ex: #include<stdio.h> void main() { int i = 2 ; if( i== 0) printf ( " i == 0 n" ); else if( i == 1 ) printf ( " i == 1 n" ); else if( i == 2 ) printf ( " i == 2 n"); } Switch statement C has a built- in multiple branch selection statement which is known as switch statement. The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed. Syntax : switch(expression) { case value1: block1; break; case value2: block2; break; ...... ..... default: default block;
  54. 54. C-LANGUAGE@iDiary 48 break; } The clause 'default' is optional. The expression is an integer expression or characters. value1, value2,.... are constants or constant expressions and are known as case labels. Each of these values should be unique within a switch statement. block1, block2,...... are statement lists and may contain zero or more statements. There is no need to put braces around these blocks. Note that case labels end with a colon. Fig 3.4
  55. 55. C-LANGUAGE@iDiary 49 On execution of the keyword switch, the value of the expression is successively compared against the values value1, value2, ..... If the value of the expression for a particular case matches with a case value , then the block of statements that follows the case are executed. The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-n following the switch. The default is an optional case. When present, it will be executed if the expression does not match any of the case values. Sample program illustrating Switch statement Ex: #include<stdio.h> void main() { int day ; printf( “ Enter the number from 1 to 7 ” ) ; scanf( “ %d ”, &day ) ; switch( day ) { case 1 : printf ( “ Monday ” ) ; break; case 2 : printf ( “ Tuesday ” ) ; break; case 3 : printf ( “ Wednesday ” ) ; break; case 4 : printf ( “ Thursday ” ) ; break; case 5 : printf ( “ Friday ” ) ; break; case 6 : printf ( “ Saturday ” ) ;
  56. 56. C-LANGUAGE@iDiary 50 break; case 7 : printf ( “ Sunday ” ) ; break; default : printf( “ Wrong Choice ” ) ; } } Ex: #include<stdio.h> void main() { int num; printf ( “ Enter any number ” ) ; scanf ( “ %d ”, &num ) ; switch( num % 2 ) { case 0 : printf ( " The number %d is even n", num ) ; break ; case 1 : printf ( " The number %d is odd n", num ) ; break ; } } Goto statement The goto statement is a jump statement which jumps from one point to another point in the program. A goto statement uses an identifier, called label, which specifies the statement to which branching statement would start execution after a goto has been encountered. A label must be followed by a colon. A label is placed immediately before the statement where the control is to be transferred.
  57. 57. C-LANGUAGE@iDiary 51 Sample program illustrating goto statement Ex: #include <stdio.h> void main() { int n = 0 ; loop : ; printf( " n%d ", n) ; n++ ; if ( n < 10 ) { goto loop ; } } Exercise:- 1. What is Decision making? Why we need decision making statement? 2. What is the difference between Nested else…if and switch statement? Fig 3.5
  58. 58. C-LANGUAGE@iDiary 52 3. What is the significance of break in switch statement? 4. What is goto statement? Define its advantage.
  59. 59. C-LANGUAGE@iDiary 53 CONTROL STRUCTURES: LOOPING Loop is used to execute a set of instructions repeatedly until a particular condition is being satisfied. Three types of looping statements are there 1) For Loop 2) While Loop 3) Do while Loop For Loop:- A for loop allows execution of a statement or block of statements repeatedly number of times until the given condition is satisfied. Syntax: for(initialize counter variable ; condition ; increment/decrement the counter variable) { Statement1; ... Statement n; } Flow chart for For loop:
  60. 60. C-LANGUAGE@iDiary 54 Sample program illustrating for loop: Ex: #include <stdio.h> void main() { int i ; for (i = 1; i<=10 ; i++ ) printf( “n Sharmistha ”) ; } In the above program “Sharmistha” will be printed 10 times . Fig 3.6
  61. 61. C-LANGUAGE@iDiary 55 Ex: #include <stdio.h> void main() { int i ; for (i = 1; i<=10 ; i++ ) printf( “n i ”) ; /* print natural no. from 1 to 10 */ } Ex: #include <stdio.h> void main() { int i ; for (i = 10 ; i >= 1 ; i -- ) printf( “n i ”) ; /* print reverse no. from 10 to 1 */ } Ex: #include <stdio.h> void main() { int i ; for (i = 1; i<=10 ; i++ ) { if (i %2 = = 0 ) printf( “n Even no = ”, i ); /* print even no. from 1-10 */ else printf( “n Odd no = ”, i ) ; /* print odd no. from 1-10 */ } }
  62. 62. C-LANGUAGE@iDiary 56 Ex: #include <stdio.h> main() { char letter; for( letter = 'A'; letter <= 'E'; letter = letter + 1 ) { printf("%c ", letter); } } Sample Program Output A B C D E WHILE LOOP: A while loop allows the number of times a statement is to be executed until the condition is satisfied ; but how many times it’ll execute is not known in advance. Syntax: while( condition) { Statement1; ... Statement n; } Flow chart for While loop:
  63. 63. C-LANGUAGE@iDiary 57 Sample program illustrating while loop: Ex: #include <stdio.h> void main() { int i ; i = 1 ; while ( i<=10 ) { printf( “n Sharmistha ”) ; i++ ; } } Ex: #include <stdio.h> void main() Fig 3.7
  64. 64. C-LANGUAGE@iDiary 58 { int i ; i = 1 ; while ( i<=10 ) { printf( “n i ”) ; /* print natural no. from 1 to 10 */ i++ ; } } Ex: #include <stdio.h> void main() { int i ; i = 10 ; while ( i >= 1 ) { printf( “n i ”) ; /* print reverse no. from 10 to 1 */ i - - ; } } Ex: #include <stdio.h> void main() { int i ; i = 1 ; while( i<= 10 ) { if (i %2 = = 0 ) printf( “n Even no = ”, i ); /* print even no. from 1-10 */ else printf( “n Odd no = ”, i ) ; /* print odd no. from 1-10 */ i++ ; } }
  65. 65. C-LANGUAGE@iDiary 59 Ex: #include <stdio.h> main() { int loop; int count; loop = 1; while( loop <= 5 ) { count = 1; while( count <= loop ) { printf("%d", count); count++; } loop++; } printf("n"); } Sample program output 1 22 333 4444 55555 DO WHILE LOOP: In DO WHILE LOOP first execute the statements then it checks the condition. Syntax: do { Statement1; ...
  66. 66. C-LANGUAGE@iDiary 60 Statement n; }while(condition); Flow chart for Do while loop: Sample program illustrating while loop: Ex: #include <stdio.h> Fig 3.8
  67. 67. C-LANGUAGE@iDiary 61 void main() { int i ; i = 1 ; do { printf( “n Sharmistha ”) ; i++ ; } while ( i<=10 ) ; } Ex: #include <stdio.h> void main() { int i ; i = 1 ; do { printf( “n i ”) ; /* print natural no. from 1 to 10 */ i++ ; } while ( I <= 10 ) ; } Ex: #include <stdio.h> void main() { int i ; i = 10 ; do { printf( “n i ”) ; /* print reverse no. from 10 to 1 */ i - - ; } while ( i >= 1 ) }
  68. 68. C-LANGUAGE@iDiary 62 Ex: #include <stdio.h> void main() { int i ; i = 1 ; do { if (i %2 = = 0 ) printf( “n Even no = ”, i ); /* print even no. from 1-10 */ else printf( “n Odd no = ”, i ) ; /* print odd no. from 1-10 */ i++ ; } while ( i <= 10 ) } Ex: #include <stdio.h> main() { int value, r_digit; printf("Enter the number to be reversed.n"); scanf("%d", &value); do { r_digit = value % 10; printf("%d", r_digit); value = value / 10; } while( value != 0 ); printf("n"); } Jumps in loop Jump statements allow to exit a loop, start the next iteration of a loop, or explicitly transfer program control to a specified location in the program. C allows to jump within loop by using continue and break keyword.
  69. 69. C-LANGUAGE@iDiary 63 Break Sometimes we need to exit from loop statement even before the test condition becomes false. We can exit from loop anytime by using break keyword. Sample program illustrating break keyword Ex: #include <stdio.h> void main() { int i ; for( i=0 ; i < 10 ; i++ ) { if(i==5) break; printf ( “%d ”, i ) ; } } Fig 3.9
  70. 70. C-LANGUAGE@iDiary 64 Sample program output 1 2 3 4 Here the control will leave the loop body when the value of 'i' becomes 5. Continue While by using continue keyword we can force to skip the current execution statement in loop and execute the next statement until the given condition is satisfied. Sample program illustrating continue keyword Ex: #include <stdio.h> void main() { int i ; for( i=0 ; i < 10 ; i++ ) { Fig 4.0
  71. 71. C-LANGUAGE@iDiary 65 if(i==5) continue; printf ( “%d ”, i ) ; } } Sample program output 1 2 3 4 6 7 8 9 Here the control will jump to next iteration when the value of 'i' becomes 5. Ex: #include <stdio.h> void main() { int i , n ; for( i = 0 ; i < 10 ; i ++ ) { printf( " nEnter a number:- " ) ; scanf( "%d" , &n) ; if(n == -10) continue ; printf("n%d",n) ; } } Remember break and continue, both the keywords can be included within a while, a do-while or a for statement. Sample program illustrating Control Statement: Ex: #include<stdio.h>
  72. 72. C-LANGUAGE@iDiary 66 #include<conio.h> void main() { int a , b , result , ch; clrscr() ; for(;;) { do { printf("Enter your choice"); printf("n1 for addition"); printf("n2 for subtraction"); printf("n3 for multiplication"); printf("n4 for divisionn"); printf("0 for exitn"); scanf("%d",&ch); } while(((ch<1)||(ch>4))&&(ch!=0)); if(ch==0) break; printf("Enter two no."); scanf("%d%d",&a,&b); switch(ch) { case 1:result=a+b; printf("Sum = %dn",result); break; case 2:if(a>b) { result=a-b; } else { result=b-a; } printf("Sub = %dn",result); break; case 3:result=a*b; printf("Multiplication = %dn",result);
  73. 73. C-LANGUAGE@iDiary 67 break; case 4:if(a>b) { result=a/b; } else { result=b/a; } printf("Div = %dn",result) } } } Exersise :- 1. Define different type of loops with example? 2. Difference between while and do-while loop? 3. What is the need of jumping in loop?
  74. 74. C-LANGUAGE@iDiary 68 ARRAY & STRINGS An array is a collection of data items of same data type that share a common name. Arrays elements can be stored in contiguous memory locations and can be accessed by an index number. Before using an array its type and dimension must be declared. The size indicates the maximum number of elements that can be stored inside the array. For example:- int age[5]; here age is an integer type variable which store the 5 elements in an array. 20 17 40 27 76 A specific element in an array is accessed by an index. In C, a string is a null-terminated character array. Thus, a string contains the characters that make up the string followed by a null. When declaring a character array that will hold a string, you need to declare it to be one character longer than the largest string that it will hold. For example, to declare an array str that can hold a 10-character string, you would write char str[11]; Here str is a string which hold 10 characters and the last block for NULL character (‘0’). C inserts the null character automatically. 0 1 2 3 4 Index start from 0 age variable stores 5 element s h a r m i s t h a 0 Fig. 4.2 Null Character Fig 4.1
  75. 75. C-LANGUAGE@iDiary 69 A string constant is a list of characters enclosed in double quotes. For example: ''hello there" Benefits of an Array 1. You can use one name for similar objects and save then with the same name but different indexes. 2. Arrays are very useful when you are working with sequences of the same kind of data. 3. Array element can be accessed using index number. Therefore all the elements can be processed in a desired manner in a single for loop that runs for each element. 4. Array elements are physically created continuously in the memory, they can be accesses using pointers. 5. Arrays use reference type and so. Types of Arrays 1- Single dimensional array 2- Multidimensional array Single dimensional Array Single dimensional array is a collection of similar elements in a linear way. These similar elements could be all ints, or all floats, or all chars, etc. Syntax of single dimension array: Datatype arrayname[size of the array]={list of values}; Example: int num[5] = {2, 8, 7, 6, 0}; Fig 4.3
  76. 76. C-LANGUAGE@iDiary 70 Sample programs illustrating single dimensional array Ex: #include <stdio.h> void main() { int i , a[10] ; for ( i = 0 ; i < 10 ; i++ ) { printf( “Enter a[%d] = ”, i) ; scanf( “%dn” , a[ i ]) ; } printf(“Array elements:”) ; for( i = 0; i < 10 ; i++) printf( “ %d ”, a[ i ] ) ; } //To read single dimensional array and add the array elements. Ex: #include <stdio.h> void main() { int i , a[10] , sum = 0 ; for ( i = 0 ; i < 10 ; i++ ) { printf( “Enter a[%d] = ”, i) ; scanf( “%dn” , a[ i ]) ; } for ( i = 0 ; i < 10 ; i++ ) sum = sum + a[ i ] ; //adding of array elements printf(“ nSum of array elements is : %d ”, sum) ; }
  77. 77. C-LANGUAGE@iDiary 71 //Bubble Sort Ex: #include<stdio.h> void main() { int arr[5] , i , j , temp ; printf("Enter any 5 numbersn") ; for( i = 0 ; i < 5 ; i++ ) scanf( " %d ", &arr[i] ) ; for ( i = 0 ; i < 5 ; i++ ) { for( j=0 ; j < 4 ; j++ ) { if( arr[j] > arr[j+1] ) { temp = arr[j] ; arr[j] = arr[j+1] ; arr[j+1] = temp ; } } } for( i = 0 ; i < 5 ; i++ ) { printf( " %dn ", arr[i] ) ; } }
  78. 78. C-LANGUAGE@iDiary 72 // Selection Sort Ex: #include<stdio.h> void main() { int arr[5] , i , j , min , temp ; printf( " Enter any 5 numbersn " ) ; Fig 4.4
  79. 79. C-LANGUAGE@iDiary 73 for( i=0 ;i < 5 ; i++ ) scanf( " %d ", &arr[i] ) ; printf ( " nArray before sorting:n " ) ; for ( i = 0 ; i < 5 ; i++ ) printf( " %dt ", arr[i] ) ; for ( i = 0 ; i < 4 ; i++ ) { for ( j = i+1 ; j < 5 ; j++ ) { if (arr[i] > arr[j] ) { temp = arr[i] ; arr[i] = arr[j] ; arr[j] = temp ; } } } printf ( " nnArray after sorting:n ") ; for(i = 0 ; i < 5 ; i++) printf( " n%dt ", arr[i] ) ; }
  80. 80. C-LANGUAGE@iDiary 74 // Insertion Sort Ex: #include<stdio.h> void main() { int arr[5] , i , j , k , temp ; printf(" Enter any 5 numbersn "); Fig 4.5
  81. 81. C-LANGUAGE@iDiary 75 for(i=0 ; i < 5 ; i++) scanf(" %d " , &arr[i] ) ; for ( i = 1 ; i <= 4 ; i++ ) { for ( j = 0 ; j < i ; j++ ) { if ( arr[j] > arr[i] ) { temp = arr[j] ; arr[j] = arr[i] ; for ( k = i ; k > j ; k-- ) arr[k] = arr[k - 1] ; arr[k + 1] = temp ; } } } printf("Sorted array is :n"); for(i=0;i<5;i++) printf("n%d",arr[i]); }
  82. 82. C-LANGUAGE@iDiary 76 // Serial Search Ex: #include<stdio.h> void main() { int arr[10],i,ser,count=0; printf("Enter any 10 numbersn"); for(i=0;i<10;i++) scanf("%d",&arr[i]); printf("Enter the search element :"); scanf("%d",&ser); for(i=0;i<10;i++) { if(arr[i]==ser) { Fig 4.6
  83. 83. C-LANGUAGE@iDiary 77 printf("Search element is found at %d indexn",i); count++; } } printf("Searching element found %d times",count); } //BINARY SEARCH Ex: #include<stdio.h> void main() { int arr[10],i,ser,temp,mid; int lower=0,upper=9,flag=1 ; printf("Enter any 10 numbersn"); for(i=0;i<10;i++) scanf("%d",&arr[i]); printf("Enter the search element : "); scanf("%d",&ser); for(mid=(lower+upper)/2; lower <= upper; mid=(lower+upper)/2 ) { if(arr[mid ]== ser) Fig 4.7
  84. 84. C-LANGUAGE@iDiary 78 { printf("The number is at index %d in the array.",mid); flag = 0 ; break ; } if(arr[mid]>ser ) upper=mid-1 ; else lower=mid+1; } if(flag) printf("Element is not present in the array."); } MULTIDIMENTIONAL ARRAYS Multidimensional arrays are a little more complicated to use than one- dimensional ones. It allows one or more dimensional arrays also. To store and manipulate two dimensional data structures such as matrices and tables. Fig 4.8
  85. 85. C-LANGUAGE@iDiary 79 Declaration of two dimensional arrays: Datatype arrayname[rowsize][columnsize]; Example: int n[2][3]; In above example 2 is the row size and 3 is column size. Total memory length is, row*column*sizeof the datatype = 2*3*2 = 12 bytes. Initialization of the two dimensional array: int n[2][3]={ {1,1,1},{2,2,2}}; Memory representation for 2- dimensional array Declaration of multidimensional array: Datatype arrayname[r1][r2].....[r n]; Sample programs illustrating Multidimensional array Ex: #include<stdio.h> void main() { int a[5][5], i , j ; //variable declaration Fig 4.9
  86. 86. C-LANGUAGE@iDiary 80 for( i = 0 ; i < 5 ; i++ ) //for row elements for( j = 0 ; j < 5 ; j++) //for column { printf ( “ n Enter a[%d][%d]: ” , i , j ) ; scanf (“ %d ”, &a[ i ][ j ]) ; } printf(“Display of array elements:n” ); for( i = 0 ; i < 5 ; i++) { for( j = 0 ; j < 5 ; j++) printf (“ %dt ”, i , j , a[ i ][ j ]) ; printf(“n”); } } //Row column sum Ex: #include<stdio.h> void main() { int arr[3][3] , i , j , r = 0 , c = 0 ; for ( i = 0 ; i < 3 ; i++ ) { for ( j = 0 ; j < 3 ; j++ ) { scanf( "%d", &arr[ i ][ j ] ) ; } } for ( i = 0 ; i < 3 ; i++ ) { for( j = 0 ; j < 3 ; j++) { printf( " %dt ", arr[ i ][ j ]) ; } printf(" n ") ; } printf(" nThe sum of the elements of each row " ) ; for( i = 0 ; i < 3 ; i++) {
  87. 87. C-LANGUAGE@iDiary 81 r = 0 ; for( j = 0 ; j < 3 ; j++) { r=r + arr[ i ][ j ] ; } printf( " nThe sum of the elements of %d row =%d " , i+ 1 , r) ; } printf( " nnThe sum of the elements of each coloumn ") ; for(i = 0 ; i < 3 ; i++) { c = 0 ; for( j = 0 ; j < 3 ; j++) { c = c + arr[ j ][ i ] ; } printf(" nThe sum of the elements of %d coloum =%d " , i+1 , c ) ; } } //Symmetric Ex: #include<stdio.h> void main() { int arr[3][3],i,j,m=0; for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&arr[i][j]); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%dt",arr[i][j]); } printf("n"); }
  88. 88. C-LANGUAGE@iDiary 82 for(i=0;i<3;i++) { for(j=0;j<3;j++) { if(arr[i][j]!=arr[j][i]) m=1; } } if(m==0) printf("It is symmetric"); else printf("It is not symmetric"); } // Identity Matrix Ex: #include<stdio.h> void main() { int arr[3][3],b,c,f=0; for(b=0;b<3;b++) { for(c=0;c<3;c++) { printf("Enter the no. for [%d,%d] = " ,b+1,c+1); scanf("%d" ,&arr[b][c]); } } for(b=0;b<3;b++) { for(c=0;c<3;c++) { printf("%dt" ,arr[b][c]); } printf("n"); } for(b=0;b<3;b++)
  89. 89. C-LANGUAGE@iDiary 83 { for(c=0;c<3;c++) { if(b!=c && arr[b][c]!=0) { f=1; break; } if(b==c && arr[b][c]!=1 ) { f=1; break; } } } if(f==0) printf("I-matrix"); else printf("Not I-matrix"); } Limitation of an array 1-An array is a static data structure. After declaring an array it is impossible to change its size. Thus sometime memory spaces are misused. 2-Each element of array are of same data type as well as same size. We cannot work with elements of different data type. 3-In an array the task of insertion and deletion is not easy because the elements are stored in contiguous memory location. 4-Array is a static data structure thus the number of elements can be stored in it are somehow fixed. Manipulating a String Manipulating string means to perform some action on string data, such as copying one string into another and concatenating strings to each other. Also common is the need to convert strings to either all
  90. 90. C-LANGUAGE@iDiary 84 lowercase or all uppercase, which can be important when comparing one string to another. Sample programs illustrating Manipulating a String Ex: #include<stdio.h> void main( ) { char name[ ] = "Klinsman" ; int i = 0 ; while ( name[i] != `0' ) { printf ( "%c", name[i] ) ; i++ ; } } Ex: #include <stdio.h> #include <string.h> void main() { char word[20]; strcpy( word, "hi there." ); printf("%sn", word ); } Ex: #include <stdio.h> #include <string.h> void main() { char name[80]; /* declare an array of characters 0-79 */ printf("Enter in a name in lowercasen"); scanf( "%s", name ); strupr( name );
  91. 91. C-LANGUAGE@iDiary 85 printf("The name is uppercase is %s", name ); } Ex: #include <stdio.h> #include <ctype.h> void main() { char name[80]; int loop; printf("Enter in a name in lowercasen"); scanf( "%s", name ); for( loop = 0; name[loop] != 0; loop++ ) name[loop] = toupper( name[loop] ); printf("The name is uppercase is %s", name ); } Arrays of Strings A String is an array of char objects. An array of string can be declared and handled like a 2d(two dimensional) arrays. You can see in the given example that we have declare a 2 dimensional character array consisting of three 'rows' and twelve 'columns'. The array is initialized with three character strings. In C, a format specifier %s is used with the printf to print the string. Sample programs illustrating Array of Strings Ex: #include <stdio.h> #include <conio.h> void main() { clrscr(); char arr[3][12]= { "Rose", "India", "technologies" }; printf("Array of String is = %s,%s,%sn", arr[0], arr[1], arr[2]);
  92. 92. C-LANGUAGE@iDiary 86 getch(); } Ex: #include <stdio.h> typedef char * string; void main() { string strs[5]; // Make 5 strings int i; strs[0] = "first string"; strs[1] = "second string"; strs[2] = "third string"; strs[3] = "this is the fourth string"; strs[4] = "and finally this is the fifth string"; for(i = 0;i < 5;++i) puts(strs[i]); } Sample program output first string second string third string this is the fourth string and finally this is the fifth string Comparison of Strings strcmp() 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. After comparing the two strings, the strcmp() function returns a single numeric value that indicates whether the first string is equal to, less than, or greater than the second string.
  93. 93. C-LANGUAGE@iDiary 87 Sample function Return value Description strcmp(string1, string2) 0 string1 is equal to string2 strcmp(string1, string2) <0 string1 is less than string2 strcmp(string1, string2) >0 string1 is greater than string2 Here is a program which puts strcmp( ) in action. Ex: #include <stdio.h> #include <string.h> void 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 ) ; } String Handling functions C supports a wide range of functions that manipulate strings. There are number of string handling functions present in header file string.h. Hence you need to include this header file whenever you use these string handling functions in your program. All these functions take either character pointer or character arrays as arguments. The most common string handling function and their use are listed here: Fig 5.0
  94. 94. C-LANGUAGE@iDiary 88 Exersise :- 1. What is array? Define the type of array. 2. Difference between array and string. 3. Define comparison operator with example. 4. Is string character array? Define with statement. Fig 5.1
  95. 95. C-LANGUAGE@iDiary 89 HANDLING POINTERS Computers use their memory for storing instructions of the programs and the values of the variable. Memory is a sequential collection of storage cells. Each cell has an address associated with it. Whenever we declare a variable the system allocates a memory location and a unique address is assigned to this variable. Pointer is a variable which can hold the address of a memory location rather than the value at the location. For example :- int num = 84 ; int *p ; Understanding basics of pointers In C when we define a pointer variable we do so by preceding its name with an asterisk. In C we also give our pointer a type which, in this case, refers to the type of data stored at the address we will be storing in our pointer. For example, consider the variable declaration: int *ptr; Here ptr is the name of our variable. The '*' informs the compiler that we want a pointer variable. The int says that we intend to use our pointer variable to store the address of an integer. Such a pointer is said to "point to" an integer.ptr has no value because we haven't stored an address in it in the above declaration. In this case, again if the declaration is outside of any function, it is initialized to a value guaranteed in such a way that it is guaranteed to not point to any C object or function. A pointer initialized in this manner is called a "null" pointer. Num Variable name Value 1001 Address of memory location 84 Fig 5.2
  96. 96. C-LANGUAGE@iDiary 90 Suppose now that we want to store in ptr the address of our integer variable k. ptr = &k; Now, ptr is said to "point to" k. The "dereferencing operator" is the asterisk and it is used as follows: *ptr = 7; will copy 7 to the address pointed to by ptr. Thus if ptr "points to" k, the above statement will set the value of k to 7. That is, when we use the '*' this way we are referring to the value of that which ptr is pointing to, not the value of the pointer itself. Similarly, we could write: printf("%dn",*ptr); to print the integer value stored at the address pointed to by ptr;. Okay, let's move on. Let us consider why we need to identify the type of variable that a pointer points to, as in: int *ptr; One reason for doing this is so that later, once ptr "points to" something, if we write: *ptr = 2; the compiler will know how many bytes to copy into that memory location pointed to by ptr. If ptr was declared as pointing to an integer, 2 bytes would be copied, if a long, 4 bytes would be copied. Similarly for floats and doubles the appropriate number will be copied. But , defining the type that the pointer points to permits a number of other interesting ways a compiler can interpret code. For example, consider a block in memory consisting if ten integers in a row. That is, 20 bytes of memory are set aside to hold 10 integers. Now, let's say we point our integer pointer ptr at the first of these integers. Furthermore lets say that integer is located at memory location 100 (decimal). What happens when we write: ptr + 1;
  97. 97. C-LANGUAGE@iDiary 91 Because the compiler "knows" this is a pointer (i.e. its value is an address) and that it points to an integer (its current address, 100, is the address of an integer), it adds 2 to ptr instead of 1, so the pointer "points to" the next integer, at memory location 102. Similarly, were the ptr declared as a pointer to a long, it would add 4 to it instead of 1. The same goes for other data types such as floats, doubles, or even user defined data types such as structures. This is obviously not the same kind of "addition" that we normally think of. In C it is referred to as addition using "pointer arithmetic", a term which we will come back to later. Similarly, since ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in the program when ptr is incremented may be different), incrementing a pointer using the unary ++ operator, either pre- or post, increments the address it stores by the amount sizeof(type) where "type" is the type of the object pointed to. (i.e. 2 for an integer, 4 for a long, etc.). Rules for Pointers These are more common sense than hard and fast rules.  Always initialize pointer variables.  With strings, never forget to include the terminating '0' when calculating the storage size.  Check the return value of malloc() and make sure it's not NULL before using it then cast it to the desired type.  For every malloc() there is an equal and opposite free()!  Remember that &variable is a pointer.  After freeing a pointer always set it to NULL.  Pointer variable cannot be multiplied by a constant.  Pointer variables cannot be added.
  98. 98. C-LANGUAGE@iDiary 92 Pointer Declaration The declaration of a pointer variable takes the following form: data_type *ptr_name; This tells the compiler three things about the variable ptr_name. 1-The asterisk (*) tells that the variable ptr_name is a pointer variable. 2-ptr_name needs a memory location. 3- ptr_name points to a variable of type data type. For example:- int *ptr; declares a variable ptr as a pointer variable that points to an integer data type. The type int refers to the data type of the variable being pointed to by ptr and not the type of the value of the pointer. Accessing a variable through its pointer Consider the following statements : int i, *ptr, q ; i = 35 ; ptr = &i ; q = *ptr ; ptr is a pointer to an integer containing the address of i. In the fourth statement we have assigned the value at address contained in ptr to another variable q. Thus, indirectly we have accessed the variable i through q. Pointer to Pointer Since we can have pointers to int, and pointers to char, and in fact pointers to any type in C. As the definition of pointer says that it’s a special variable that can store the address of another variable. Then the other variable can very well be a pointer in case of pointer to pointer. This means that it’s perfectly legal for a pointer to be pointing to another pointer. Suppose we have a pointer ‘p1′ that points to yet another pointer ‘p2′ that points to a character ‘ch’.
  99. 99. C-LANGUAGE@iDiary 93 In memory, the three variables can be visualized as : So we can see that in memory, pointer p1 holds the address of pointer p2. Pointer p2 holds the address of character ‘ch’. So ‘p2′ is pointer to character ‘ch’, while ‘p1′ is pointer to ‘p2′ or we can also say that ‘p2′ is a pointer to pointer to character ‘ch’. Now, in code ‘p2′ can be declared as : char *p2 = &ch; But ‘p1′ is declared as : char **p1 = &p2; So we see that ‘p1′ is a double pointer (ie pointer to a pointer to a character) and hence the two *s in declaration. Now, ‘p1′ is the address of ‘p2′ ie 5000. ‘*p1′ is the value held by ‘p2′ ie 8000. ‘**p1′ is the value at 8000 ie ‘c’. Sample programs illustrating Pointer to Pointer Ex: include<stdio.h> void main() { char **ptr = NULL; char *p = NULL; char c = 'd'; p = &c; ptr = &p; printf("n c = %cn",c); Fig 5.2
  100. 100. C-LANGUAGE@iDiary 94 printf("n *p = %cn",*p); printf("n **ptr = %cn",**ptr); } Sample program output c = d *p = d **ptr = d Pointers and Arrays When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element (index 0) of the array. The compiler also defines the array name as a constant pointer to the first element. The array declared as: static int arr[5]= {1,2,3,4,5} ; is stored as follows: Elements arr[0] arr[1] arr[2] arr[3] arr[4] value 1 2 3 4 5 Address 1000 1002 1004 1006 1008 Consider the following: int a[10], x; int *p; p = &a[0]; /* pa pointer to address of a[0] */ x = *p; /* x = contents of pa (a[0] in this case) */ To get somewhere in the array using a pointer we could do: Fig 5.3 Fig 5.4
  101. 101. C-LANGUAGE@iDiary 95 p + i = a[i] ; For example we can just type p = a; instead of p = &a[0]; and a[i] can be written as *(a + i). i.e. &a[i] a + i. We also express pointer addressing like this: p[i] *(p + i). Sample programs illustrating Pointer and Arrays Ex: #include <stdio.h> #define ROWS 5 #define COLS 10 int multi[ROWS][COLS]; void main() { int row, col; for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { multi[row][col] = row*col; } } for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { printf("n%d ",multi[row][col]); printf("%d ",*(*(multi + row) + col)); } } } Sample program output
  102. 102. C-LANGUAGE@iDiary 96 Array of Pointers Just like array of integers or characters, there can be array of pointers too. Since pointers are variables. An array of pointers can be declared as : <type> *<name>[<number-of-elements]; For example : char *ptr[3]; The above line declares an array of three character pointers.In the below figure visualized the memory representation : Sample programs illustrating Arrays of Pointers Ex: #include<stdio.h> void main() { char *p1 = "Sharmistha"; char *p2 = "iDiary"; char *p3 = "India"; char *arr[3]; Fig 5.5
  103. 103. C-LANGUAGE@iDiary 97 arr[0] = p1; arr[1] = p2; arr[2] = p3; printf("n p1 = %s n",p1); printf("n p2 = %s n",p2); printf("n p3 = %s n",p3); printf("n arr[0] = %s n",arr[0]); printf("n arr[1] = %s n",arr[1]); printf("n arr[2] = %s n",arr[2]); } In the above code, we took three pointers pointing to three strings. Then we declared an array that can contain three pointers. We assigned the pointers ‘p1′, ‘p2′ and ‘p3′ to the 0,1 and 2 index of array. Sample program output p1 = Sharmistha p2 = iDiary p3 = India arr[0] = Sharmistha arr[1] = iDiary arr[2] = India Common Pointer Pitfalls Here we will highlight two common mistakes made with pointers. 1. Not assigning a pointer to memory address before using it int *x; *x = 100; we need a physical location say: int y; x = &y; *x = 100; 2. Illegal indirection
  104. 104. C-LANGUAGE@iDiary 98 Suppose we have a function malloc() which tries to allocate memory dynamically at run time and returns a pointer to block of memory requested if successful or a NULL pointer otherwise. Let us have a pointer: char *p; *p = (char *) malloc(100); /* request 100 bytes of memory */ *p = `y'; There is mistake above. Malloc returns a pointer. Also p does not point to any address. The correct code should be: p = (char *) malloc(100); If code rectified one problem is if no memory is available and p is NULL. Therefore we can't do: *p = `y';. Exersise :- 1. What is pointer? What is the advantage of pointer? 2. Defining dereferencing and point to operator. 3. What is the importance of pointer in array? 4. Define cons and pros of pointer.
  105. 105. C-LANGUAGE@iDiary 99 FUNCTIONS A function in C can perform a particular task, and supports the concept of modular programming design techniques. Every C program must have a function named main(). Program execution will always begin by carrying out the instructions in function main(). Why Functions Two reasons: (a) Writing functions avoids rewriting the same code over and over. (b) Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code into modular functions also makes the program easier to design and understand. Fig 5.5
  106. 106. C-LANGUAGE@iDiary 100 Advantages :  It is easy to use.  Debugging is more suitable for programs.  It reduces the size of a program.  It is easy to understand the actual logic of a program.  Highly suited in case of large programs.  By using functions in a program, it is possible to construct modular and structured programs. Type of Functions C functions can be classified into two categories. 1- Library Function 2- User defined function Library Function C provides library functions for performing some operations. These functions are present in the c library and they are predefined for example: sqrt() is a mathematical library function which is used for finding the square root of any number The function scanf() and printf() are input and output library function. Similarly we have strcmp() and strlen() for string manipulations. To use a library function we have to include some header file using the preprocessor directive #include. For example : to use input and output function like printf() and scanf() we have to include stdio.h, for math library function we have to include math.h, for string library string.h should be included . User defined function A user can create their own functions for performing any specific task of program. These types are called user defined function. To create and use these function we have to know these 3 things.
  107. 107. C-LANGUAGE@iDiary 101 1. Function Declaration 2. Function Definition 3. Function Call Declaring a Function A function declaration informs the compiler about the format and existence of a function. A function declaration consists of a return type, a name, and a parameter list. They are as follows:  Create a unique name which says clearly what the function does.  Use functions to return a single value of built-in C datatype (including pointers). Functions that don't return anything will be declared as void.  Choose the function's parameters and their types. Functions which don't need anything will use void. The general method of declaring a function is to declare the function in the beginning of the program. Defining a function A function definition contains a function declaration and the body of a function. Structure of a Function definition There are two main parts of the function: The function header and the function body. int sum(int x, int y) { int ans = 0; //holds the answer that will be returned ans = x + y; //calculate the sum return ans //return the answerv } Function Header In the first line of the above code, int sum(int x, int y) It has three main parts
  108. 108. C-LANGUAGE@iDiary 102 1. The name of the function i.e. sum 2. The parameters of the function enclosed in paranthesis 3. Return value type i.e. int Function Body Whatever is written with in { } in the above example is the body of the function. Calling the function When the function is called the control, transfers to the function and all the statements present in the function definition gets executed and after which the control, returns back to the statement following the function call. Sample programs illustrating Function Ex: #include<stdio.h> #include<conio.h> void leap(int y); // declaration void main() { int year; clrscr(); printf("Enter the year :"); scanf("%d",&year); leap(year); // calling getch(); } void leap(int y) // definition { if(y%4==0&&y%100!=0) printf("n %d is a leap year ",y); else printf("n %d is not a leap year",y); }
  109. 109. C-LANGUAGE@iDiary 103 Sample program output Enter the year : 2012 2012 is a leap year Function Type based on Signature 1. Functions with no arguments and no return value. A C function without any arguments means you cannot pass data to the called function. Similarly, function with no return type does not pass back data to the calling function. It is one of the simplest types of function in C. This type of function which does not return any value cannot be used in an expression it can be used only as independent statement. Let’s have an example to illustrate this. Ex: #include<stdio.h> #include<conio.h> void printmsg() { printf("I am in user defined functionn"); } Fig 5.6
  110. 110. C-LANGUAGE@iDiary 104 void main() { clrscr(); printf("Welcome to function in Cn"); printmsg(); printf("Function easy to learn."); getch(); } Sample program output Welcome to function in C I am in user defined function Function easy to learn. Explanation The above C program example illustrates that how to declare and use a function with no argument and no return type. We declared a function name printmsg(), which print “I am in user defined function”. It neither take any argument and nor return any data to the called function. 2. Functions with arguments and no return value. A C function with can accept data from calling function. In other words, you send data to the called function from calling function but you cannot send result data back to the calling function. Fig 5.7
  111. 111. C-LANGUAGE@iDiary 105 We can control the output of function by providing various values as arguments. Let’s have an example to get it better. Ex: #include<stdio.h> #include<conio.h> void add(int x, int y) { int result; result = x+y; printf("Sum of %d and %d is %d.nn",x,y,result); } void main() { clrscr(); add(30,15); add(63,49); add(952,321); getch(); } Sample program output Sum of 30 and 15 is 45. Sum of 63 and 49 is 112. Sum of 952 and 321 is 1273. Explanation This program simply sends two integer arguments to the function add() which calculates its sum and stores in another variable and then prints that value. 3. Functions with arguments and return value. This type of function can send arguments from the calling function to the called function and wait for the result to be returned back from the called function back to the calling function.
  112. 112. C-LANGUAGE@iDiary 106 This type of function can do two way communications; it can accept data as arguments as well as can send back data as return value. The data returned by the function can be used later in our program for further calculations. Let’s have an example to illustrate this. Ex: #include<stdio.h> #include<conio.h> int add(int x, int y) { int result; result = x+y; return(result); } void main() { int z; clrscr(); z = add(952,321); printf("Result %d.nn",add(30,55)); printf("Result %d.nn",z); getch(); } Fig 5.8
  113. 113. C-LANGUAGE@iDiary 107 Sample program output Result 85. Result 1273. Explanation This program sends two integer values function add(), which adds these two values and sends back the result to the calling function. We can return values to the calling function by using return keyword as follows: return(result); Here result variable hold the data which we want to return to the calling function. In the above program calling function contain an integer variable named z to hold result, which comes from called function. Now you can use this z anywhere within calling function. You can directly prints the result of called function by using printf() method. 4. Functions with no arguments but returns value. We may need a function which does not take any argument but only returns values to the calling function then this type of function is useful. The best example of this type of function is “getchar()” library function which is declared in the header file “stdio.h”. Fig 5.9
  114. 114. C-LANGUAGE@iDiary 108 Let’s have an example to illustrate this. Ex: #include<stdio.h> #include<conio.h> int send() { int no1; printf("Enter a no : "); scanf("%d",&no1); return(no1); } void main() { int z; clrscr(); z = send(); printf("nYou entered : %d.", z); getch(); } Sample program output Enter a no : 5 You entered : 5. Explanation In this program we have a user defined function named send which takes one integer as input from keyboard and sends back to the calling function. 5. Functions that return multiple values. If we want to send back more than one values then how we could do this? We have used arguments to send values to the called function, in the same way we can also use arguments to send back information to the calling function. The arguments that are used to send back data are called Output Parameters. Let’s see an example:

×