Learn C Programming in 13 Days PDF

Document Details

CooperativeFermat8423

Uploaded by CooperativeFermat8423

St. Joseph's College (Autonomous), Bangalore

Denzil Lobo SJ

Tags

C programming programming computer science programming language

Summary

This handbook provides a comprehensive guide to C programming, covering fundamental concepts in 13 days. The material is suitable for undergraduate-level learners.

Full Transcript

Learn C in 13 days Denzil Lobo SJ St Joseph’s College (Autonomous) BANGALORE Learn C Programming in 13 Days 1 Handbook TABLE OF CONTENTS DAY 1 Programming Fundamentals: PSEUDOCODE In this chapter you will learn about The meaning of pseudocde...

Learn C in 13 days Denzil Lobo SJ St Joseph’s College (Autonomous) BANGALORE Learn C Programming in 13 Days 1 Handbook TABLE OF CONTENTS DAY 1 Programming Fundamentals: PSEUDOCODE In this chapter you will learn about The meaning of pseudocde Arithmetic and assignment operators Thee initial statements in pseudocode. How to use ASSIGNMENT, INPUT and OUTPUT statements in pseudocode Variables and the conventions in naming them. DAY 2 The OUTPUT & INPUT STATEMENTS In this chapter you will learn about The OUTPUT statement The INPUT statement and FLOWCHARTING fundamentals. DAY 3 OPERATORS and STATEMENTS in C In this chapter you will learn about OPERATORS and STATEMENTS in C. How to name variables in C The format of a C program How to compile a C program in UNIX environment You will work out a lot of problems base don what you have learned till now. DAY 4 Relational Operators & Conditional Statements In this chapter you will learn about: About relational operators and how to use them Relational expressions Conditional statements Flowcharting of conditional statements Learn C Programming in 13 Days 2 Handbook Guidelines about indenting the code LOGICAL operators and their use You will work out a lot of problems based on the use of relational operators and logical operators and conditional statements. DAY 5 Increment Operator and LOOPING Statements: In this chapter you will learn about: Looping statements Increment operators Flowcharting for looping statements You will learn how to use for and while statements in C You will be writing algorithms and flowcharts and C programs for a lot of problems DAY 6 ARRAY or SUBSCRIPTED variables In the chapter you will learn about: Subscripted variables ( arrays ) How to declare arrays and input data into arrays. You will work out a lot of problems using arrays. You will learn techniques of linear search You will learn about SORTING and implement Bubble sort algorithm You will learn other SORTING techniques like INSERTION SORT and SELECTION SORT You will implement BINARY SEARCH method. DAY 7 MATRICES: 2D ARRAYS In this chapter you will learn about: How to declare a two dimensional array: matrix. How to input data into a matrix How to display the continent of a matrix How to do matrix addition and multiplication and other operations on the matrix. Learn C Programming in 13 Days 3 Handbook DAY 8 User defined Function Subprograms in C In this chapter you will learn about: User defined functions How to write user defined functions. Arguments and return values various types of functions. You will implement a lot of functions DAY 9 String Manipulation In this chapter you will learn about: How strings are stored in the memory How to manipulate them You will use in-built string functions. You will write many string functions. DAY 10 POINTER VARIABLES: In this chapter you will learn about: Meaning of pointers How to declare a pointer variable How to access the address of a variable How to access data if you know the address of a variable. How to allocate memory dynamically Writing functions using pointer variables Character and integer pointers. Passing parameters by REFERENCE. DAY 11 Structures and Unions In this chapter you will learn about: The meaning of RECORDS How to declare record type using struct command How to create data variables of record type. How to input data into a record of struct type. How to create a new record data type using typedef command. You will write a menu driven program to process student information. Tips on debugging programs. Learn C Programming in 13 Days 4 Handbook DAY 12 FILES in C In this chapter you will learn  How to create a file for storing data.  How to open a file for reading data from the file.  How to close a file after the use.  How to store information and read information from files.  How to create RANDOM ACCESS files.  How to write record to files using fwrite() command.  How to read records from a file using fread() command.  How to write a menu driven program to process students’ information system. DAY 13 COMMAND LINE PROGRAMMING In this chapter you will learn to  Write command line programmes by passing parameters at the command line.  You will write many UNIX and DOS type commands which can be executed at the command prompt. Learn C Programming in 13 Days 5 Handbook APPENDICES APPENDIX I VARIABLES: TYPES OF OPERATORS APPENDIX II MATHEMATICAL FUNCTIONS APPENDIX III MACROS and STRING FUNCTIONS APPENDIX IV SCOPE OF VARIABLES APPENDIX V THE PREPROCESSOR APPENDIX VI GRAPHICS APPENDIX VII LINUX COMMANDS APPENDIX VIII vi EDITOR Learn C Programming in 13 Days 6 Handbook Learn C Programming in 13 DAYS DAY 1 Programming Fundamentals: PSEUDOCODE In this chapter you will learn about The meaning of pseudocde Arithmetic and assignment operators Thee initial statements in pseudocode. How to use ASSIGNMENT, INPUT and OUTPUT statements in pseudocode Variables and the conventions in naming them. We speak in various languages. Every language is made up of words- various kinds of words like nouns, verbs, pronouns, conjunctions etc. Words are put together, according rules of grammar and sentences are formed. These sentences convey meaning to us. Many sentences together form paragraphs…and paras put together form an article or even a novel!! As languages are means of communication between persons, so do computer languages are means to interact with computers, they are and a means to instruct computers do required job. There are various kinds of computer languages: There are high level or low level languages. The HIGH level languages give instructions to computers in human- like language, preferably ENGLISH. Whereas LOW LEVEL languages give instructions in binary code or in mnemonics. BASIC, C , COBOL, JAVA etc are examples for High level languages and Assembly language is an example for low level language. In order to learn to give INSTRUCTIONS to a computer, we need to study the vocabulary of computer language. To begin with, in order to help us learn the computer languages we first learn PSEUDOCODE and FLOWCHARTING. Pseudocode is a computer like language, having it’s own vocabulary and set of rules. We use it along with flowcharting to do the analysis of problems. First let us try to learn how pseudocode is written. We shall learn the pseudocode in stages, adding various items as we go along. Like any language pseudocode has it’s own character set and vocabulary, This vocabulary consists of OPERATORS ( verbs) and key words, which are put together to form STATEMENTS ( INSTRUCTIONS). 1. OPERATORS 2. STATEMENTS Learn C Programming in 13 Days 7 Handbook First we shall learn only two sets of OPERATORS. The are: OPERATORS Arithmetic Operators +, -, *, /, % Assignment Operator  Arithmetic operators ( +, -, *, /, % ) help us to do addition, subtraction, multiplication division and modulus. The symbols given above instruct the computer to do respective action on numbers on either side of the operator. These are binary operators. The modulus operator returns the remainder. For example 7 % 2 will be 1 and 4%2 will be 0. The Assignment Operator (  ) is used to assign values to variables. The value ( in the form of a number, variable or a formula) is on the RHS of the operator and it is assigned to a variable on the LHS. Now we shall learn three STATEMENTS which we will be suing often. They are: VARIABLES: 1. ASSIGNMENT STATEMENT Variables are named locations in the memory 2. OUTPUT STATEMENT of the computer. They are declared at the beginning of a computer program, and can 3. INPUT STATEMENT store various kinds of data items like integer numbers, floating numbers, character strings etc. They are receptacles for data storage and come in various types.( Ref. Appendix I) 1. Assignment Statement: The assignment statement is represented as: Variable  value. e.g. A  10 B  20 Here numbers 10 and 20 are assigned to variables A and B respectively. Let us try to understand how children learn addition. Teacher asks them to add two numbers , say 5 and 3. Then teacher tells 5 in right hand and three in left hand…and then the child adds the number counting each of the fingers. What child does is that he/she assigns these Learn C Programming in 13 Days 8 Handbook numbers to two hands. Now the problem becomes complicated. Child has to add ten and 4. Then the teacher uses the trick.. and tells the students “ ten in your mind and 3 in right hand”. Then the child continues the process of addition starting from 10 in the mind. This way the child learns to assign 10 to the memory location in the brain !! While using computers we need to use a lot of numeric and other data values. All these have to be stored in various types of variable. This is done by assigning these values using the ASSIGNMENT operator through the ASSIGNMENT STATEMENT. In mathematics we use a lot of formulae to calculate results of computation. All these formulae can be converted to assignment statements. e.g. To convert the temperature in Centigrade to Farenheight we use the following formula. F= 9 C + 32 5 This has to be converted into corresponding assignment statement in psuedocode as: F = (9.0/5)* C + 32 Here we use operators to convert the mathematical expression to a pseudocode expression. PROBLEMS: Convert the following formulae to pseudocode expressions. 1. Area = Π R 2 2. Area of a triangle = ½ B H 3. Interest = PNR/100 4. S = ut + 1/2at2 5. a = (v-u)/t 6. area= √s(s-a)(s-b)(s-c) 7. Volume of a sphere = 4/3πR3 CONVENTIONS for naming variables 1. Use a continuous sequence of alphabets and digits without any gap. 2. The names of variable should be self explanatory. As far as possible do not use single alphabet for representing variable names. 3. Let the first alphabet of the variable name be in CAPS. e.g Amount, Area 4. If the variable is a compound word then let the first letter of each word be in caps. e.g. AmountPaid, AreaTriangle, BasicPay 5. Variables are declared right at the beginning of a computer program Learn C Programming in 13 Days 9 Handbook DAY 2 The OUTPUT & INPUT STATEMENTS In this chapter you will learn about The OUTPUT statement The INPUT statement and FLOWCHARTING fundamentals. The OUTPUT Statement: The second statement we would like to learn is the OUTPUT STATEMENT. After doing calculation we would like the computer to display the results. To do this we have to give an instruction to the computer to do so. This is done using the OUTPUT STATEMENT as: PRINT ( Variable ) The computer will display the value stored in the variable. e.g. A  10 PRINT (A) In this excerpt of pseudo code the first statement assigns 10 to A and then displays the content of A. 10 will appear on the screen. STRINGS IN OUTPUT STATEMENT Quoted strings in OUTPUT statement will be printed as such. e.g. PRINT ( “ Area of the circle =” ) On execution the output would be: Area of the circle = Suppose the PRINT statement is changed to: Area = 100 PRINT( “Are of the circle =”, Area) : Then the output would be: Area of the Circle = 100 Learn C Programming in 13 Days 10 Handbook 3 The INPUT STATEMENT Often data has to be keyed in using the keyboard. And this data has to be assigned to a set of variables. INPUT statement is used to accept data from the user. The format of the INPUT statement is: INPUT ( Variable) The computer waits for the input whenever it comes across the INPUT statement. Once the data is keyed in, it will be assigned to the variable/s mentioned within the brackets. e.g. Suppose A and B are two variables declared, then the INPUT statement INPUT ( A, B) Will wait for two numbers to be entered from the keyboard, and will assign those values to the variables A and B respectively. Problem: Write a short pseudocode excerpt to input temperature in Centigrade ( C ) and convert it into Farenheight. INPUT ( C ) F = ( 9/5)* C + 32 PRINT(“ The temperature in Farenheight = “, F ) Learn C Programming in 13 Days 11 Handbook FLOWCHARTING: FLOWCHARTING is extensively used for problem analysis. It consists of a few graphical boxes in which the pseudocode is inserted. The following symbols are used: For START/END of a program For variable declaration & processing For INPUT/OUTPUT Let us learn how to use these flowcharting symbols to analyze a problem. Consider this problem. Write flowchart to find out the sum of two numbers. START VAR: A, B, C INPUT(A, B ) ` C A+ B PRINT( C ) END Here we combine pseudocode and flowcharting symbols together. Program starts with declaration of all the variables used ( eg A, B , C). We INPUT two numbers which are stored in variable A and B. Then the sum of the variables is found out by adding A and B Learn C Programming in 13 Days 12 Handbook and assigning the sum to yet another variable C. The sum is displayed using the OUTPUT statement in the flowchart. Workout the following problems: PROBLEMS: Write flowchart & pseudocode for the following. 1. To calculate the area of rectangle given the length and breadth. 2. Calculate the area and circumference of a circle given the radius. 3. Given the initial velocity and acceleration write flowchart to calculate the distance traveled by an object in t minutes. 4. Given the base and height of a triangle write flowchart to calculate its area. 5. Calculate the force exerted by an object of mass m traveling with a initial velocity u, final velocity v in time t. 6. Calculate the interest on a principal amount P, for N number of years with the rate of interest R. I =PNR/100 7. Given the radius of a sphere, calculate the volume of the sphere. Vol = 4/3πR3 8. Calculate the annular area not covered by a smaller circle within another circle of bigger radius. 9. Calculate the volume of water in a cylinder of radius R1 and height H having a sphere of radius R2 immersed in water inside the cylinder. Learn C Programming in 13 Days 13 Handbook DAY 3 OPERATORS and STATEMENTS in C In this chapter you will learn about OPERATORS and STATEMENTS in C. How to name variables in C The format of a C program How to compile a C program in UNIX environment You will work out a lot of problems base don what you have learned till now. Like any language C has its own character set. This character set is made up of alphabets in lower case and upper case and a set of other special characters ( Ref APPENDIX I). This character set is used to form IDENTIFIERS. Identifiers are used to name various elements like variables, functions and keywords in C. Now we discuss about the OPERATORS and STATEMENTS in C corresponding to those mentioned when we studied the Pseudocode. OPERATORS 1. Arithmetic Operators are: + for Addition , - for Subtraction , * for Multiplication, / for Division and % for Modulus operation., ie. to find the remainder. 2. Assignment Operator is: = symbol is used as the DECLARATION OF VARIABLES IN C: assignment operator in C. Right at the beginning of the program it is customer to declare all the variables used in a program. The declaration of the variable is done as: TypeOfVariable VariableName ; For example:. int A, B; // where A and B are integer type float C; // where C is a float type. char Ch; // Ch is character type. char Name ; // will be able to store a string of // 20 characters Note: The same conventions for naming variables to be followed. Learn C Programming in 13 Days 14 Handbook STATEMENTS 1. Assignment Statement: It is used to assign values to a variable. Variable = value ; Every statement in C always ends with a semicolon ( ; ). e.g. A = 10 ; C=A+B; F = (9.0/5.0)* C + 32 ; Area = (22.0/7.0)*R*R ; 2. The OUTPUT Statement: Output statement is used to display information on the CRT. printf(“ FormatSpecifierString”, Variable/s ); The FormatSpecifierString indicates the type of variable. It is “%d” – if the variable is an integer, “ %f” if it is a floating number and “%s” if it is a string- i.e. a sequence of alphabets. Right now let us only use these two types. We shall learn more of them as we go on. e.g. printf( “ Enter two numbers “); printf(“ The sum of two numbers is = %d “, C); printf(“The sum of %d and %d is = “, A, B, C ); 3. The INPUT STATEMENT: The INPUT statement is used to accept data from the keyboard. scanf( ) is used in C. The syntax is given below. scanf( “FormatSpecifierString”, &Variable) ; The control string is akin to the one in printf() statement. suppose A is a integer variable type, then to accept data into A we use the following statement. scanf(“%d”, &A ); Learn C Programming in 13 Days 15 Handbook Suppose there are two variable A & B of integer type, then: scanf(“%d%d”, &A, &B) ; would input data into the variables A and B. Please note the variables have to preceded by “&” symbol. No other strings or prompts are allowed in scanf() statement. Take it for granted for the moment. I shall explain it to you later when you learn about pointers. Your first C program Let us write our first program in C base don the flowchart draw earlier, to add two numbers. During this whole course of study I will be insisting our writing flowchart for most of the programs and convert those flowcharts into equivalent C code. This practice will help you to be a very good programmer. Unfortunately many write flowchart after their write down the code!! – putting cart before the horse!! C program has the following structure: Program Header indicating the name of the programme, explanation of the program, the name of the author and the date on which it is written. Program header is written for the sake of documentation…to make the lives of those who use your program easy !! An example: The program header is followed by inclusion of “header files”. This is equivalent to offering a dictionary to the program to interpret all the in built commands given in the program. Right now we shall add only two libraries as: # include # include These two headers contain the declaration of most of the INPUT/OUTPUT functions being used. After this we start the body of the program with the word main followed by open and close parenthesis followed by the open flower bracket as: Learn C Programming in 13 Days 16 Handbook main( ) { after this all the variables used in the program are declared as: int A, B , C ; This would be followed by processing and the display of result, and finally the programs ends # include START # include main() { VAR: A, B, C int A, B, C; scanf(“%d%d”, &A, &B); INPUT(A, B ) C = A + B; printf( “Sum of two numbers = %d” , C); C A+ B } PRINT( C ) END This program is correct, but insufficient. A person, other than the person who has written this program will be blinking what to do next when you execute this program. Hence it is a very good program habit to make your program “USER FRIENDLY”- i.s. your program should speak to the user…prompt him to enter values ( data ) as and when required etc. There should also be a title displayed when the program urns- just to inform the user what this program is about etc. More the info for the user is better.. such programs are called “USER FRIENDLY” PROGRAMS. Let’s see how we can make the above basic C program into an user friendly program. Learn C Programming in 13 Days 17 Handbook # include main( ) { int A, B , C ; system(“clear”); printf( “ Program to find the sum of TWO Numbers \n”); printf( “Enter two numbers : “); scanf(“%d%d”, &A, &B ); C=A+B; printf( “ the sum of two numbers is = 5.2f\n”, C ); } Please note some important points. See how the code has been INDENTED well. It is always a good habit to leave one tab column after the starting curly bracket and start the code. Try to give as many lines spaces, say after the declaration of variables, after the processing section, just before the results etc. Please remember that your code should be readable. Include comments whenever you have some important algorithms and logic is used. Now keeping all thee points in mind convert the earlier flowcharts ( problems on page 7 ) into corresponding C programs. Learn C Programming in 13 Days 18 Handbook How to execute C programs on UNIX/LINUX environment: 1. Save your code as a test file with an extend C. e.g addnos.c 2. At the LINUX prompt type: $ cc addnos.c - o addnos.exe The C –compiler which comes with LINUX compiles the programme into executable code with the name addnos.exe 3. To run the program type as given below. $./addnos.exe // Please note always add “./ “ before the compiled program name. PROBLEMS: One cannot learn programming unless one does a little hard work. Some of us are very good at memorizing, so much so that we try to memorize programs and appear for exams. C-programs are not to be memorized. It’s important to know how to solve problems, how to write flowchart and pseudocode. That’s why I always insist on writing flowchart and pseudocode for all the programs. Once you are accomplished in doing this, you will be able to write C-programs with out any hassle. Hence I request you to write flowchart with pseudocode, and then the C programs for the following problems. 1. Write flowchart & C program to convert temperature in Centigrade to Fahrenheit using the formula: F = 9/5 C + 32 2. Write flowchart & C program for calculating the circumference and area of a circle given the radius. Please note: You are accustomed to do a lot of mathematics so much so that you think that computer understand all your mathematical symbols and constants. You cannot use п ( PI )in your program !! You will have to use the value of PI= 3.14159 for calculations. And please do not forget ( invariably I am sure that you will forget !! ) to convert mathematical formulations into pseudocode & C statements with appropriate operators ! Learn C Programming in 13 Days 19 Handbook 3. Write flowchart and C program to enter five numbers and find the total and mean of this five numbers. ( Declare five variables as Num1, Num2, etc ) 4. Write flowchart and C program to find the standard deviation of five numbers using the formula given below. Std Dev = √ Σ Xi2/N - ( Σ Xi/N)2 ( This problem sounds high fi- with a very complicated formula. Don’t get alarmed. Σ means summation. Therefore Σ Xi = X1 + X2 + X3 + X4 + X5 and Σ Xi2 = X1*X1 + X2*X2 +... + X5* X5. Please do not fall into the mathematical trap once again !! You cannot define subscripted variables as in Maths. You will have to name them as X1, X2, etc. ) Use SQRT( Num ) in your pseudocode for calculating the square rot of Num. In C you will use a user defined function sqrt( Num ) to calculate the square root. Most of your work has been made easy by someone who has already written many of the mathematical functions for your use. But later you will learn how to write these functions yourself- and even improve them !! To use some of these mathematical function you will have to include math.h header file as: # include and in the LINUX environment you will have to compile your code as: $ cc stddev.c -o stddev.exe -lm 5. Write pseudocode and C program to calculate the sine of an angle in degrees using the formula given below. Sin(X ) = X – X3/3! + X5/5! – X7/7! Where X = 3.14159 * Theta/180.0 Please note: You will not get accurate value for the sine of the angle. Here we have approximated it to just five terms. Input value of Theta. Calculate the value of x and use it in the formula above. Calculate the values of each terms separately and then do the summation. Please remember to declare variable SinX as float or double in C. 6. Write flowchart and pseudocode to calculate the Cos of an angle in degrees. Use the formula given below. Cos( X) = 1- X2/2! + X4/4! – X6/6! As above. 7. Write flowchart and C program to evaluate the following polynomial equation for a given value of x. Y = 5x4 + 3 x3 + 2 x2 + x + 10. Note: Rewrite the equation in such a way that thee are no powers of x involved as: Y = ( ((5*x + 3 )* x + 2 )* x + 1)* x + 10 Learn C Programming in 13 Days 20 Handbook DAY 4 Relational Operators & Conditional Statements In this chapter you will learn about: About relational operators and how to use them Relational expressions Conditional statements Flowcharting of conditional statements Guidelines about indenting the code LOGICAL operators and their use You will work out a lot of problems based on the use of relational operators and logical operators and conditional statements. I always ask this question in the class “What is the difference between a calculator and a computer ?”. Invariable everyone answers saying that computer is different from a calculator because it has memory, high speed etc. All these are valid answers but not the ones which bring out the difference between a computer and a calculator. Computer- unfortunately we are stuck with this terminology- is different because it can DECIDE ! Calculator cannot decide tell you whether one value is greater than the other…or less than the other or even equal. To do that we need computer!! To decide we need a set of OPERATORS. These operators are known as RELATIONAL OPERATORS. They are the ones which help us to compare two data items. In our day to day life, whenever we come across two persons…immediately we judge that one is taller than the other or lighter than the other. How do we do that? In our mind we constantly ask questions using the relational operators- great than, less than, equal , not equal etc- to arrive at an answer.. Let us list the operators in Pseudocode and also in C language.. Relationship Pseudocode C Equal EQ == Not Equal NE != Greater Than GT > Less Than LT < Greater than Equal GE >= Less than Equal LE B ){ printf(“ A is bigger than B”); } else{ printf( “B is bigger than A); PRINT(“A is bigger “) PRINT(“B is bigger “) } } START Of course this is not the ideal program. As mentioned earlier, the code should have enough prompts ( messages ) to make the program user-friendly. The same program could be written in a better way as: Learn C Programming in 13 Days 23 Handbook # include main() { int A, B; system(“clear”); //-----------for LINUX printf(“ Program to find the bigger number \n”); printf(“ Enter two unequal numbers : “); scanf(“%d%d”, &A, &B); if( A > B) { printf( “ A=%d is greater than B=%d\n”, A, B); } else{ printf( “ B=%d is greater than A=%d\n”, B, A ); } } INDENTING OF C CODE INDENTING of C code is very important. See that PROBLEMS: your code starts one tab off the margin, and in the case of conditional statements, the statements Now a set of problems are given. All coming after the if condition and else should be of them graded, starting from easy indented one tab in. That makes you code readable. problems to tougher. Always write Please remember that you are writing code for flowchart first, and then write the C someone else !! program. 1. Write flowchart & C program to input two unequal numbers and display the smaller number. 2. Write flowchart and C program to input a number, and display whether it is divisible by 5. 3. Write flowchart & C program to input a number. Find out whether it is divisible by 5, if not display the next number which is divisible by 5. Learn C Programming in 13 Days 24 Handbook 3. Write flowchart and C program to input two numbers and state which one is bigger. If they are equal, then state they are of equal vale. ( Note: Here you need to use if- else if – else formulation of conditional statement ) 4. Write flowchart and C program to input name, marks in three subjects of a student. Sate whether the student has passes or failed. Condition for a pass is that the student should have secured 35% minimum in each of the subjects and 40% aggregate. ( Note: To do this you have to combine four of the relational expressions and find out the TRUTH value of the compound statement. To do this we need LOGICAL OPERATORS ). ________________________________________________________________________ LOGICAL OPERATORS Logical Operators are the CONJUNCTIONS of our computer language. To find out , say, whether a student has passed in an examination we ask this question whether he/she has obtained pass percentage in each of the subjects, and also has the required aggregate percentage. In case Mk1, Mk2 an dMk3 are the marks obtained in three subjects and Avg is the average in the three subjects we could formulate a compound statement as; If he/she has ( Mk1 GE 35) AND ( Mk2 GE 35 ) AND ( Mk3 GE 35 ) AND (Avg GE 40 ) then we consider the person to have passed. Here AND is the LOGICAL OPERATOR and OR is another LOGICAL OPERATOR. The C equivalents of these operators are && ( AND) and || ( OR ). The above relational expression then becomes: (Mk1 >= 35) && ( Mk2 >= 35) && (Mk3 >= 35) && ( Avg >= 40) Here we add one more set of OPERATORS to our list of Operators. ________________________________________________________________________ 5. Write flow chart & C program to computer the Gross and net salary of an employee Given his name and Basic salary under the conditions given: If the basic salary is less than 5000, DA = 30% f the basic and Tax= 8% of Basic. If the basic pay is great than equal 5000 and less than 10,000, DA= 40% of Basic and Tax= 10% of Basic. If the basic is greater than equal to 10,000 then DA= 50% and Tax=20% of basic. ( Note: here you use if—else if—–else conditional structure ) Learn C Programming in 13 Days 25 Handbook NOTE: How to declare a string variable and how to input and print a string? I have already indicated in the earlier chapter how to declare a string variable. It is done by declaring a array of character type variable. Suppose you want a string variable to store name you can declare it as: char Name ; The meaning of this statement is that there is a string variable with 30 contiguous locations to store a string. You will learn more about it when you study arrays. To input a string into this variable we can either use scanf() function with %s format string or you could also use gets() to accept a string variable. printf() and puts() are used to display the content of a string variable. Examples: main() { char Name; printf(“Enter your name : “); scanf(“%s”, Name ); printf(“Your name is : %s\n”, Name); } You may have noticed a small change in the format of the scanf() command. Usually you use & symbol before the variable name. But whenever you use a string variable you dispense with the & symbol. Explanation for this will be given when you learn pointers, later in your study. Example: main() { char Name; printf(“Ener your name ); gets(Name); printf(“ Your name is : “); puts( Name ): } Learn C Programming in 13 Days 26 Handbook DAY 5 Increment Operator and LOOPING Statements: In this chapter you will learn about: Looping statements Increment operators Flowcharting for looping statements You will learn how to use for and while statements in C You will be writing algorithms and flowcharts and C programs for a lot of problems One of the things a computer has to do is to repeat some jobs again and again. This are repetitive tasks. For example suppose we have on students performance of say 50 students in an exam. Our task is to find the total, average marks obtained, and compute the result base don some criteria. This same task has to be done for all the students. This is repetitive work and we need to have some kind of instruction for the computer to do this job again and again- for a specified number of times. In our day to day language we would say some thing like this: Do the following job 10 times { Job } or say: Do this 10 times { PRINT( “Varun”) } The name Varun will be printed 10 times. How shall we convert this into a PSEUDOCODE statement ? We could reformulate the above statement as: FOR( I 1 to 10 , STEP 1 ){ PRINT( “Varun”) } The flowchart symbol for the looping state is written as given below: FOR( i 1 to 10, step 1) PRINT(“Varun “) Learn C Programming in 13 Days 27 Handbook The flowchart shows the looping construct in which the OUTPUT statement, PRINT(“Varun”) is printed 10 times, starting from the value of i=1 to 10. If there are other statements within this looping structure, they also will be executed the number of times depending on the initial value and the final terminating value of the variable i. Looping statement in C The FOR statement given in the pseudocode takes the following format: for( Counter= InitVal; Termination_Condition ; Increment ){ STATEMENT/S; } e.g. for( i = 1; i EID)); scanf(“%s”, Ptr->Name); scanf(“%f”, &(Ptr->Basic)); printf(“ EID :\n”, Ptr->EID); printf(“ Name :\n”, Ptr->Name); print(“ Basic Salary :\n”, Ptr->Basic): } 3. # include typedef struct EmpType{ int EID; char Name; float Basic; } EMPLOYEE; main() { EMPLOYEE Emp, *Rec; int i; Rec = (EMPLOYEE *)malloc( 3* sizeof(EMPLOYEE)); for( i= 0; i < 3; i++){ printf(“Enter EID \n”); scanf(“%d”, &((Rec+i)->EID) ); printf(“Enter employee name\n”); scanf(“%s”, (Rec+i)->Name); printf(“Enter Basic Salaray :\n”); scanf(“%f”, &((Rec+i)->Basic)); } Learn C Programming in 13 Days 78 Handbook system(“clear”); for( i= 0; i < 3; i++){ printf(“EID : %d\n”, (Rec+i)->EID)); printf(“Employee name : %s \n”, (Rec+i)->Name ) ); printf(“Basic Salaray :%8.2f\n”, (Rec+i)->Basic)); } } Passing structures and structure pointers to a function Whenever we want to pass structures as parameters to a function we can either pass them by value or by reference. Whenever we pass structures by value we cannot modify the contents of the structure, and even if we modify the contents, that will not be reflected in the values of the modified fields of the structure. Hence if we want to have the values changed, we should pass structure pointers as parameters. The following program which deals with complex numbers explains the use of structures as parameters to functions. First a few tips on complex numbers. A complex number is represented by a + ib where I is square root of -1. Suppose we have two complex numbers x = a + ib and y = c + id then some of the operations on these complex numbers are given below. Sum: x + y = (a + ib) + (c + id) = ( a + c) + i( b + d) Difference : x – y = ( a+ib) –( c + id) = ( a-c) + i( b – d) Product : x * y = ( a + ib) *( c +id) = ( ac – bd) + i( ad + bc) Now we shall write the whole program Learn C Programming in 13 Days 79 Handbook # include typedef struct ComplexType{ float Real; float Imag; }COMPLEX; void ReadComplexNumber( COMPLEX *X ); COMPLEX Sum( COMPLEX X, COMPLEX Y); COMPLEX Product( COMPLEX X, COMPLEX Y); void PrintComplexNumber( COMPLEX C ); main() { COMPLEX X, Y, Z; system(“clear”); printf(“Program to Add, Multiply Complex Numbers\n”); printf(“Enter the real and Imaginary parts f the first complex number \n”); ReadComplexNumber( &X); printf(“Enter the real and Imaginary parts of the second complex number \n”); ReadComplexNumber( &Y); system(“clear”); printf(“ The first complex number is:\n”); PrintComplexNumber( X ); printf(“ The second complex number is:\n”); PrintComplexNumber( Y ); Z = Sum( X, Y ); printf(“ The sum of two complex numbers is:\n”); PrintComplexNumber( Z ); } Learn C Programming in 13 Days 80 Handbook void ReadComplexNumber( COMPLEX *X ) { scanf(“%f”, &(X->Real)); COMPLEX Sum( COMPLEX X, COMPLEX Y) { COMPLEX Z; Z.Real = X.Real + Y.Real; Z.Imag = X.Imag + Y.Imag; Return Z; } void PrintComplexNumber( COMPLEX C ) { printf(“%5.2f “, C.Real); if( C.Imag < 0) printf(“-5.2f i\n”, C.Imag); else printf(“+5.2f i\n”, C.Imag); } COMPLEX Product( COMPLEX X, COMPLEX Y) { } Learn C Programming in 13 Days 81 Handbook HomeWork: 1. Write a menu driven program with function sub programs to calculate the sum, difference, product of two complex numbers. Learn C Programming in 13 Days 82 Handbook UNION: In C union is a memory location that I sued by several different variables. Usually of different types. The definition of union is very similar to that of a structure as shown below. union Test{ int A; char Ch; }; In this example test is the tag name. here both the variables A and Ch are allotted the same memory locations. The storage used for a union is large enough to hold the largest number in the member list. In this example suppose the memory location starts at 1000, then A will be assigned two byes, 1000 and 1001, whereas the variable Ch will be allotted only one byte memory starting at 1000. A/Ch 1000 1001 As in the case of structure, a union variable can be declared as: union Test T; The assigning of values can be done as in the case of structures. T.A = 10; T.Ch= ‘B’ ; Example: 1. # include union Test { int A; char Ch; }; main() { union Test X; X.A= 50; printf(“%d”, X.A ); } Learn C Programming in 13 Days 83 Handbook 2. # include union Test{ int A; char Ch; }; main() { union Test X; X.A = 1234; printf(“%d”, X.A); printf(“%d”, X.Ch); printf(“%c”, X.Ch); } OUTPUT: 1234, 4 and ascii charter of 4 Learn C Programming in 13 Days 84 Handbook DAY 12 FILES in C In this chapter you will learn  How to create a file for storing data.  How to open a file for reading data from the file.  How to close a file after the use.  How to store information and read information from files.  How to create RANDOM ACCESS files.  How to write record to files using fwrite() command.  How to read records from a file using fread() command.  How to write a menu driven program to process students’ information system. In the last chapter we entered information of many students. Unfortunately whenever we exited from the program all the data entered was lost, and we had to do it al over again when we used the program subsequently. Hence there should be a way to store data and retrieve it whenever we need. Imagine an office where you have to enter data everyday!!- that would be impossible and also foolish to do so. Every computer language comes with a mechanism to store data and retrieve it whenever we need. This is known as the FILE SYSTEM. Let us see the similarities between the manual filing system and the electronic filing system. Filing systems is used to store information. The first thing one does is to create a file, and then write data to the records and store those records in the file and then close the file. Similar process is followed even in electronic filing system. The steps involved are: Create a file for data input. Write data to the file. Close the file. Or Open an existing file for reading information. Read information from the file. Close the file. We need some commands to do this job. In C first of all we create a file pointer using the statement given below: FILE *fp; Where FILE is the file data type and fp is the file pointer.`` Learn C Programming in 13 Days 85 Handbook Then we open the new file, say Students.dat to store student data as: fp = fopen( “Students.dat”, “w”); This command creates a new file Students.dat and assigns the starting address of the file into the file pointer fp. If fp contains an address, then the command has been successful in creating a new file. In case the command fails to create a new file, a NULL is will be stored in fp. Hence it is always advisable to check whether one has been successful in creating the new file as: FILE *fp; if( ( fp= fopen(“students.dat”, “w”) == NULL){ printf( “ not able to create the file\n”); exit(1); } The second thing you want to do with the file is write some data to the file. This can be easily done using the command fprintf() as given below. Suppose I want to write, say info on five students we could do it as follows. printf( “Enter Student ID and names of 5 students\n”); for( i =1; i = 35 ) S.Result = 1; else S.Result = 0; fwrite( &S, sizeof( STUDENT), 1, fp ); } rewind(fp); system( “clear”); printf(“ Enter the record number to be searched : “); scanf(“%d”, &RecNo ); fseek( fp, (long) ( sizeof( STUDENT) )*( RecNo-1) , 0) fread( &S, sizeof( STUDENT), 1, fp ); printf(“ Student ID : %d\n”, S’SID ); printf( “ Student name : %s\n”, S.Name ); printf( “ Marks in Physics : %d\n”, S.Marks); printf( “ Makrs in Chemistry : %d\n”, S.Marks); printf( “ Makrs in Maths : %d\n”, S.Marks ); if( S.Result == 1) printf( “ RESULT : PASSED \n”); else printf( “ RESULT : FAILED “); fclose( fp ); } PROBLEMS: 1. Convert the program given above into a menu driven program. 2. Write a program using files to automate inventory in a store. 3. Write a program in C using files to automate the functioning of a library. Learn C Programming in 13 Days 91 Handbook DAY 13 COMMAND LINE PROGRAMMING In this chapter you will learn to  Write command line programmes by passing parameters at the command line.  You will write many UNIX and DOS type commands which can be executed at the command prompt. I am sure you are familiar with some of the commands you have executed either at the DOS prompt or the UNIX/LINUX prompt. For example you have used cat command to display the content of a file while working in LINUX. or cpy, type , rename and a host of other commands. C comes with the facility to write such programs which can be used at the command prompt with appropriate arguments or parameters given at the command line or operating system prompt.. For example cat takes one parameter, the name of the file whose content have to be displayed. cpy takes two arguments, where file1 is to be copied on to file2. rename also takes two arguments We will be able to write all such programs. Let us see how we shall write these programs. First of all we need to know more about the main() program. Till now we have written the function main( ) in all our C programs. We did not give any arguments and also did not indicate the return value. The main() function really comes with two arguments, int argc and char * argv[] and a return value either void or int, and could be written as: int main ( int argc, char *argv[] ) { …code } The parameter argc gives the total number of parameters at the command line including the name of the program. In the case of rename program the value of argc would be 3 and in the case of cat the value of argc is 2. The second argument is a character matrix to store the parameters. Learn C Programming in 13 Days 92 Handbook Suppose we have a command line program CopyFile and if we use it as $ CopyFile students.dat studentsnew.dat Then the value of argc would be 3 and argv = CopyFile argv = students.dat argv = studentsnew.dat With this understanding on the parameter passing we shall write our first command line program –typefile < filename> to display the content of a text file. # include int main( int argc, char *argv[] ) { FILE *fp; int Ch; if( argc < 2 ){ printf( “ You have not entered the command properly. Check the syntax\n”); printf( “ SYNTAX : $ typefile \n”); exit(1); } if( ( fp = fopen( argv , “r”) == NULL){ printf(“ file does not exist “); exit(1); } while( (Ch =getc( fp) ) != EOF) putchar( Ch); fclose( fp); return 1; } Learn C Programming in 13 Days 93 Handbook SOME MORE FILE RELATED FUNCTIONS Command: putc( character, FilePtr) Prototype: int putc( int Ch, FILE *fp ) This function is used to write byte data to the file. e.g. do{ Ch = getchar(); putc( Ch, fp); } while( Ch != ‘$’); Command: getc( FilePtr ) Prototype: int getc( FILE *fp) This function is used to read data from a text file byte by byte. e.g. FILE *fp; int Ch; fp = fopen(“test.dat”, “r”); while(( Ch =getc( fp) ) != EOF ) putchar Ch); Command : feof( FilePtr) Prototype: int feof( FILE * fp) This function is used to find out whether the file pointer point to the end of file. Returns 0 if not. e.g. while( !feof( fp)){ Ch = getc( fp); putchar(Ch); } PROBLEMS: 1. Write a command line program to copy the content one file on to another. Syntax: FileCopy < file2> To prepare duplicate copy of file1 as file2. 2. Write command line program to rename a file. Syntax: Rename TiP: Open a file for writing with the new file name. Copy the contents of the old file to this one. close the old file and using remove(filename) delete the old file. 3. Write a command line program to change the case to upper case. Syntax: filetoupper Learn C Programming in 13 Days 94 Handbook 4. Write command line program to convert a decimal number to number in some other base. Syntax : dectobase 5. Write a command line program to convert a number in any base to decimal. Syntax: anybasetodec 6. Write a command line program to convert hexadecimal number to decimal equivalent. Syntax: hextodec 7. Write a command line program to append one file to another. Syntax: appendfile < file2> Learn C Programming in 13 Days 95 Handbook APPENDIX I The basic elements which are sued to construct C statements are known as C character set. IDENTIFIERS and keywords, data types, constants, variables and arrays are constructed using the character set which is given below. CHARACTER SET The Character Set in C consists of lower case letters a to z, the upper case letter A to Z and certain special characters given in the table below. Symbol Name Symbol Name , comma _ underscore. period * Asterisk ; Semicolon + Plus sign : Colon - Minus sign ? Question mark < Less than sign ‘ Apostrophe > Greater than sign “ Quotation mark ( Left parenthesis $ Dollar sign ) Right parenthesis % Percentage { Left brace # Number sign } Right brace & Ampersand [ Left bracket ^ Caret ] Right bracket ! Exclamatory mark / Slash | Vertical bar \ Back slash IDENTIFIERS and KEYWORDS Various program elements like variables, keywords, functions and arrays are given names using identifiers. The first letter of an identifier must be a letter, while the other characters may be either letters or digits. The underscore ( _ ) character can also be used We usually follow some good conventions such as keeping the first letter of an identifier in upper case while naming identifiers. Also note that C is case sensitive, and hence a variable like Amount and amount are two different identifiers. The following set of words which are known as keywords in C cannot be used to represent variables. These keywords have predefined meanings in C. Learn C Programming in 13 Days 96 Handbook auto break case char const continue do double else enum extern float for goto if int long register return short signed sizeof static switch typedef union struct void volatile while unsigned DATA TYPES C language is rich in data types. It has several different data types. These data types are used to identify various types of data. The following table illustrates some of these data types. Data type Description int Inter quantity char Single character float Floating point number double Double precision floating point CONSTANTS There are four types of constants in C. They are: Integer constants Floating point constants Character constants and String constants. The value of a constant is not altered during the execution of a program. Numbers are represented by the integer and floating point constants. While representing numbers one should remember that no comma, blank space can be within the constant. The constant may be preceded by a minus sign and the value of the constant should be within the minimum and maximum range of a given data type. a. Integer Constant An integer-valued number is known as an integer constant. It may be a decimal, octal or hexadecimal number. e.g. 1 5 200 875 are examples for decimal integer constants. 01, 045, 05376 are examples for octal integer constants. A leading 0 indicates that it is an octal number. He digits of an octal number are a combination of digits from 0 to 7. Where as a Learn C Programming in 13 Days 97 Handbook hexadecimal integer constant is formed by the combination of 0 to 9 and a to f, leading with 0x or 0X. 0x4 0Xfff are examples of hexadecimal integer constants. b. Unsigned and Long Integer constants Unsigned integer constants are non-negative numbers and they exceed the ordinary integer constant range by a factor of 2. Long integer constants have higher range and need more memory space to store the integer constant. Fro a particular computer using w-bit word, the range of an ordinary integer constant varies from -2w-1 to +2w-1 -1. The range of the unsigned integer constant for the same w-bit word would be 0 to 2w-1. For a short and long integer we substitute the value of w by w/2 and 2w. c. Floating Point constants A floating point number is a decimal number with a decimal point or an exponent. Some of the valid floating point numbers are given below. 0.1 0.15 387.56 1.87e+5 0.045e-4 d. Character constants A single character enclosed in apostrophe is known as a character constant. E.g. ‘a’ ‘C’ ‘7’ etc are character constants. e. String Constants A sequence of characters enclose din double quotes, where characters may be numbers, letters, special characters or blank spaces is known as a string constant. E.g. “St Aloysius College”, “2005”, “5+7”, “Y” are string constants. VARIABLES: An identifier which is used to store a data value is known as a variable. Rules to coin variable name: 1. Maximum 30 characters 2. First character should be a letter ( Can be underscore in some special cases ) 3. Key words should not be used. 4. No special characters except underscore. 5. It’s a good habit to have the first letter in caps, and if the variable is a compound name, then the starting of every word should be in caps. E.g AmountPaid 6. Use variable names which are very representative of the values it represents. Learn C Programming in 13 Days 98 Handbook Types of variables and memory allocation: Var type Bytes Sign Range char 1 Yes -128 to 127 unsigned char 1 No 0 to 255 int 2 Yes -215 to 215-1( -32768 to 32767) unsigned int 2 No 0 to 216-1 ( 0 to 65535) short 1 Yes -128 to 127 unsigned short 1 No 0 to 255 long 4 Yes -231 to 231-1 ( -2147483648 to 2147483647) unsigned long 4 No 0 to 232 -1 ( 4294967295 ) float 4 Yes 3.4E -38 to 3.4E+38 double 8 Yes 1.7E-308 to 1.7E+308 Long double Yes 3.4E-4932 to 1.1E+4932 char: char variables store ASCII values up to 127 int : Numbers are store in pure binary system. There is no such difference between integer and character type. For character type only 1 byte is reserved where as for the integer type 2 bytes are reserved. The maximum value that can be stored in a interg type is 32767. If we try to store a number greater than its range, the number is divided by 32767 and the remainder is stored. Negative integers are stored in two’s compliment. float : For float type 4 bytes are allotted. The values are stores in floating point format. 22+ 1 ( sign bit ) = 23 bits for mantissa 8 + 1 ( sign bit ) = 9 bits for exponent double : Eight bytes are allocated to store double type. 52 + 1( sing bit) = 53 bits of the mantissa 10 + 1 (sign bit) = 11 bits for the exponent Learn C Programming in 13 Days 99 Handbook WHITE SPACE CHARACTERS CONSTANT EXPLANATION \n Line feed \t Tab \v Vertical tab \b Back space \r Return \\ Backslash \f Form feed \” Double quote \’ Single apostrophe \0 NULL BITWISE OPERATORS C supports a full complement of bitwise operators. Bitwise operation refers to testing, setting or shifting the actual bits in a byte or word. OPERATOR MEANING & AND >> RIGHT SHIFT > ) 6. LEFT SHIFT ( > 1 10 Left to right < >= Left to right == != Left to right & Left to right ^ Left to right | Left to right && Left to right || Left to right ? : Right to left = += -= Right to left. Left to right TERNARY OPERATOR if-then-else ( ? : ) The ternary if-then-else ( ? : ) operator has three operands, of which the first one is a Boolean expression, the second and the third expression compute to a value. The syntax of the statement is given below. BooleanExpression ? Expression1 : Expression2 In this statement, if the BooleanExpression is true then the Expression1 will be executed, else Expression2 with be executed. The whole statement can be used in an assignment statement as: Value = BoolenaExpression ? Expression1 : Expression2 Learn C Programming in 13 Days 101 Handbook Let us take a simple example and learnt the functioning of this statement. Big = A > B ? A : B Suppose A = 20 and B = 40 , result in Big = 40. Ternary operators are mostly used in #define statement to define macros. PROBLEMS: 1. Write a program in C using ternary operator to convert upper case to lowe case and vice versa. main() { char Ch; while( (Ch =getchar())!= ‘\n’) putchar(( Ch >=’A’ && Ch = ‘a’ && Ch = ‘0’ && Ch 0) printf(“%s is greater than %s\n”, Name1, Name2); else print(“%s is lesser than %s\n”, Name1, Name2); } strchr() Prototype : char *strchr( char *s, int c ) Purpose : strchr returns a pointer to the first( last) occurrence of character c in string or return NULL pointer s. Example:1 main() { char Country[]={“United States”}; printf(“%s”, strchr( Country, ‘ ‘); } OUTPUT: States Example 2: main() { char Country[] ={“United States of America”}; printf(“%s”, strchr(Country, ‘ ‘); } OUTPUT: America strstr() Prototype: char *strstr( char *s, char * t) Purpose : This function returns a pointer to the first occurrence in the string to in string pointed to by s; return null pointer if no match is found. Example: #include main() { char *str1=”Borland International”, *str2=”nation”, *ptr; ptr= strstr( str1, str2); printf(“The substring is =%s\n”, ptr); } OUTPUT: The substring is = national Learn C Programming in 13 Days 110 Handbook strlwr() Prototype : char * strlwr( char *s ) Purpose : To convert all the characters of the string s from uppercase to lower case. Example: printf(“%s”, strlwr(“ANANDAN”)); OUTPUT: anandan strupr() Prototype : char *strupr( char *s ) Purpose : To convert all the characters of the string s from lower case to upper case. Example : printf(“%s”, strupr(“sholan”)); OUTPUT: SHOLAN strrev() Prototype : char *strrev( char *s ) Purpose : This function reverses the string s. Example: printf(“%s”, strrev(“MANGALORE”)); OUTPUT: EROLAGNAM strset() Prototype : char * strset( char *s, char c ) Purpose : This function is used to assign one particular character to whole of the string s. Example: char Hline; strset(Hline, ‘-’); printf(“%s”, Hline); OUTPUT: 80 hyphens will be displayed on the screen. Learn C Programming in 13 Days 111 Handbook APPENDIX IV SCOPE OF VARIABLES Variables in C can be classified into four different scopes: 1. Automatic variables 2. Static variables 3. External variables and 4. Register variables. The scope of a variable determines over what part of the program a variable is actually available for use. By default all the variables declared without the scope specification are treated as auto, whose presence will be within { and }. The variable are also classified depending on the place of their declaration as: local ( internal) or global (external). Local variables are those declared within a particular function, whereas global variables are declared outside of any functions, before the main(). 1. AUTOMATIC VARIABLES: The scope of the automatic variable is limited to the function in which it is declared. i.e. they have values that are ‘local’ to the function. The ones declared in the main() are very much private and no other function has access direct access to them. Similarly, all the variables declared inside functions are also local to the function and exit only when the function is invoked and disappear when the function is exited. # include int AddNums( int X, int Y); main( ) { auto int X = 10, Y= 25, Z; system(“clear”); Z= X + Y ; printf( “ Z = %d\n”, Z); Z = AddNums( X, Y); printf( “Z = %d\n”, Z); } int AddNums( int X, int Y) { int Z; Z= X + Y; Return Z; } OUTPUT: Z = 35 Z = 35 Learn C Programming in 13 Days 112 Handbook In the example sited above we note that we can declare and use the same variable name in different functions in the same program. 2. STATIC VARIABLES Static variables can be either internal or external. They are declared by prefixing the keyword static when declaring the variable. These variables do not lose their storage locations and their values when the control ;eaves the functions or blocks wherein they are defined. In C static variables retain their values between invocations. The initial value assigned to a static variable must be a constant or an expression involving constants. By default static variables are initialized to 0. main() { int a = 10, b; b= Incr( a ); pritnf(“%d \n”, b); b = Incr( a ); printf(“%d \n”, b); } int Incr( int a) { static int C = 15; C = C + a; Return C; } OUTPUT: 25 35 Here we note that the variable C which is declared as static in the function Incr() retains the value after the first invocation and is not initialized to 15. 3. REGISTER VARIABLES : The keyword register prefixed to a declaration of a variable indicates to the complier that the variable declared will be used heavily. The register variables are place din the machine registers, and enhance the speed of computation. main ( ) { register long i, Sum =0; for(i=1; i Some of the macro definitions are listed below. a) Simple macro substitution b) Macro substitution with arguments. c) Nested macro substitution. a) Simple Macro Substitutions These are commonly used to define constants. For example: # define PI 3.14159 Whenever the constant PI occurs in a given program it will be replaced by 3.14159. A macro definition can also include more than a simple constant value. It can also include an expression. # define twoPI 2.0* 3.14159 # define SIZE sizeof( int) * 5 Learn C Programming in 13 Days 115 Handbook b) Macros with arguments: Macros can be defined with arguments. They are similar to functions. The difference is that the source code of the macro is substituted at the time of compiling. Example. #define Max( X, Y ) (X > Y ) ? X : Y #define Vol_Cuboid( X, Y, Z ) X*Y*Z #define Square( X ) X* X One needs to be careful while using macros. Suppose you have an expression whose Square value you want to calculate, and suppose you use it in the above macro definition you’ll end up in wrong value. Fro example. Value = Square ( x + 2 ) This would return Value = x+ 2 * x + 2 = 3x + 2 which is not what you wanted. Hence the macro declaration has to be modified as. #define Square( X ) (X)* ( X) or #define Vol_Cuboid( X, Y, Z ) (X)*(Y)*(Z) It is also possible to use one macro in the definition of another macro. This is known as nesting macros. For example: #define Square( x) (x)*(x) # define Cube( x) (Square( x ) * (x) ) 2. File Inclusion: It is possible to include external files containing functions and macro definitions. This enables us to use functions which need not be rewritten. This is done by the preprocessor directive. One more advantage of this is that the same file containing functions and macros can be included in as many programs as needed. #include “filename” Where filename is the file containing the required functions and other definitions. When the file is included in double quotes, the search for the file is made first in the current directory and then in the standard directories. 3. Compiler Control Directives It is possible to compile conditionally by using some conditionals like #if, #else, #elif ,#endif, #ifdef or #ifndef etc. Compiler also can be made to bypass any portion of the source code by using these directives. Learn C Programming in 13 Days 116 Handbook For example 1: #if( sizeof( int)==4) typedef int Fact; #elif (sizeof(int)== 2) typedef long Fact; #else CallHelp() #endif Example 2: #ifdef PII #define WORD_SIZE 32 #else #ifdef PIII #define WORD-SIZE 64 #endif Learn C Programming in 13 Days 117 Handbook APPENDIX VI GRAPHICS Till now we have been using the CRT screen to display only textual matter. We can use the computer to display 2D and 3D graphics images. To do this. first we have to switch over to GRAPHICS MODE. This is done by setting the adapter to a graphics mode using the function intigraph() whose prototype is given below. void initgraph( int *graphdriver, int *graphmode, char *BGIpath ) e.g. int driver, mode; driver = CGA; mode = CGAC0; initgraph( &driver, &mode, “C:\\tc\\bgi”); This command initialized the screen to particular graphmode. The number of pixels horizontally axis and the vertical axis depend on the graph mode. Screen modes for various Video Adapters Driver Equivalent Mode-MACRO Equivalent Resolution CGA 1 CGAC0 0 320 x 200 CGA1 1 320 x 200 CGAHI 4 640 x 200 MCGA 2 MCGAC0 0 320 x 200 MCGAMED 4 640 x 200 MCGAHI 5 640x 480 EGA 3 EGALO 0 640 x 200 EGAHI 1 640 x 350 VGA 9 VGALO 0 640 x 200 VGAMED 1 640 x 350 VGAHI 2 640 x 480 In TURBO C all the prototypes of graphics functions are located in the file graphics.h hence this file must be included with the program tat uses graphics functions. Microsoft C uses GRAPH.H as the header file for graphics prototypes. Learn C Programming in 13 Days 118 Handbook You can also use the function detectgraph() to detect graph mode and the driver. The prototype of this function is given below. void detectgraph( int * graphdriver, int *graphmode) You can also detect the graphics mode using a macro DETECT as below. # include # include main() { int Driver, Mode; Driver = DETECT; intigraph( &Driver, &Mode, “ “);.. …. } At the end of a graphics session is terminated using function closegraph(). This function restores the screen to the text screen. THE BASIC PLOTTING FUNCTIONS: The most fundamental graphics functions are those that draw a point, a line and a circle. In Turbo C these functions are : putpixel(), line(),circle() and rectangle(). The prototypes of these functions given below. void putpixel( int x, int y, int colour ); void line( int StartX, int StartY, int EndX, int EndY); void circle( int x, int y, int Radius ); void rectangle( int left, int top, int right, int bottom); Learn C Programming in 13 Days 119 Handbook The following program demonstrates the use of these functions. #include #include main() { int driver, mode; int i; driver =VGA; mode= VGAMED; initgraph(&driver, &mode, “ “); line( 0, 0, 250, 200); line( 100, 50, 250, 150 ); circle( 100, 100, 50); circle( 150, 100, 40); rectangle( 0,0, 639, 349); rectangle( 100, 100, 300, 200); getch(); } The Cartesian coordinates in the graphics mode are set in such a way that the coordinate (0,0) is assigned to the left, top corner. The X- coordinate vales increase along the X-axis, and the Y-coordinates will increase along the Y-axis. The maximum value of the X-coordinate and the Y-coordinate depends on the graphics mode. The functions getmaxx() and getmaxy() can be used to find out the maximum values for the total number of pixel on X and Y axes. The function setviewport() can be used to display the graphics images only within the viewport defined by this function. The prototype of this function is: void setviewport( int left, int top, int right, int bottom, int clipflag ); Learn C Programming in 13 Days 120 Handbook If the clipflag is zero, then Turbo C will not clip the output that overruns the viewport boundaries, otherwise it will clip to prevent overrunning the boundary. #include #include #include main() { int driver, mode; int i,X, startX, startY, endX, endY; float Xval, Yval; float Height; driver= VGA; mode =VGAMED; initgraph(&driver, &mode, "C:\\tc\\bgi"); rectangle( 20,20, 500, 325); //draw a rectangle setviewport(20,20, 500, 325, 1); // set that as the viewport line(0, 150, 500, 150); Height = 150; startX=0; startY=150; for( X= 0; X 325) XA = -1; if( x < 5) XA = 1; if( y > 175) YA = -1; if( y < 5) YA = 1; putimage( x, y, buffer, OR_PUT); putimage( x, y, buffer, XOR_PUT); x = x + XA; y = y + YA; putimage( x,y, buffer, OR_PUT); for( i=0; i

Use Quizgecko on...
Browser
Browser