Beginner’s Guide To C

Transcription

Beginner’s Guide to C

Beginners’ Guide to CFIRST EDITION December 2014Copyright Information 2014 All rights reserved.Author SoniP a g e 2 65

Dedicated to my Parents, my Family, my Lecturers and Teachers

About the AuthorSoni a former teacher and is now a technical writer. She holds a degree in commerceand a post graduate degree in computer application. She has hands on experience inprogramming language and worked as a programmer too. She also has written bookson Java that are used by school teachers. She has designed curriculum for onlinecomputer courses on programming languages such as Java, C, and C .ForewordThis book contains information which will help you to start working with C. Structures,Union and Pointers that are part of C programming language will be covered in the nextedition of the book.You can mail your feedback to gayathrimanoharlal@yahoo.co.in; soni0618@gmail.com

PrefaceThis book provides information on Programming with C. It has all the informationfrom the basics that will help a beginner to start working with C programminglanguage. As you all are aware that C is the basic programming language that willenhance and build your capability before learning and working with otherprogramming languages. In addition the book gives you simple examples that willhelp you to work with the programming language.

ContentsIntroduction to Programming Languages. 8Introduction to C Language . 10Software programs required for a C program . 10Structure of a C program. 12Compile & Execute C Program . 14Data types. 15The void Type . 15Variables . 16Variable Initialization. 17Keywords. 18Constants . 18Character constants. 19String Constants . 19Defining Constants . 19The const Keyword . 20Escape Sequence . 22Operators. 24Arithmetic Operators . 26Relational Operators . 28Logical Operators . 30The Conditional operator . 32Loops and Conditions. 36Conditional constructs . 36The if construct. 37The if.else construct . 38Switch construct . 39

Beginners’ Guide to CLoop Constructs . 43The while loop . 43The do while loop. 46The for loop . 48Arrays . 52Character Arrays. 54Library Functions . 57Mathematical Functions . 57String Function . 60The gets and puts Function . 60P a g e 7 65

Beginners’ Guide to CIntroduction to Programming LanguagesA computer requires instructions to perform a task. Such instructions are includedin a programming language. Collection of such program is software. The procedureof developing software is programming. There are different programminglanguages. A Computer can be given instructions in any programming language. Allcomputer languages follow a set of rules called syntax. Each programming languageuses its own set of syntax.The 3 main categories in programming languages are, machine language, assemblylanguage and high level language.Machine LanguageSequence of instructions written in binary form is a Machine Language. Machinelanguages use 0 and 1 to write instructions. The program written in a machinelanguage execute faster than program written in any other language.Assembly LanguageIt is an easy language, as special symbols like special characters, letters, or digits areused to write the program. Computers do not understand the Assembly Languagehence the code written in Assembly Language has to be translated to a MachineLanguage. The Assembler performs the task of translation. After translation of aAssembly Language to a Machine Language the resultant output is an object code inthe form of 0 and 1.High Level LanguageHigh level languages are easier to understand as English language is used to specifycommands. Examples of High Level Language are: C, C , Java, COBOL, and PASCAL.The High Level Language has to be translated to a machine readable language. Acompiler translates the High Level Language. The resultant output is an object code.P a g e 8 65

Beginners’ Guide to CThe Hierarchy of programming language is:High Level LanguageOutputOutput of Programare easilyunderstandableAssembly LanguageOutputBinary Codeunderstandable byMachine LanguageMachineA programming Language conversion to machine understandable language happensthe way it is illustrated below:High Level LanguageCompiler translatesProgramAssembly LanguageAssembler translatesMachine LanguageP a g e 9 65

Beginners’ Guide to CIntroduction to C LanguageC is a general purpose, high level programming language and is a widely usedlanguage. This language has facilities for structured programming and allows toefficiently provide machine instructions. Hence, the language is used for codingassembly language too. The system software like Unix operating system has beencoded using C. C is a procedural language. It was designed to be compiled using arelatively straightforward compiler, to provide low-level access to memory, toprovide language constructs that map efficiently to machine instructions, and tohave a have need of minimal run-time support. C is useful for many applicationsthat had formerly been coded in assembly language, such as in systemprogramming.Software programs required for a C programAs no computer can understand C, you need several programs that help thecomputer understand the instructions. The programs are: Editor Compiler Linker LoaderHere Turbo C editor is used for C programming.The table below explains the purpose of the various programs.P a g e 10 65

Beginners’ Guide to CProgramEditorPurposeUsed to write and alter the content of the program (sourcecode).CompilerUsed to convert the program to machine language.LinkerUsed to link the header file with the main program beforeexecution.LoaderUsed to load the program to the computer memory forexecution.The basics of a C programming language needs an understanding of the basicNoteCompiler is used to check for errors in the program. Thecomplier stores the translated machine language code with.obj extension and is called as object code.building blocks of the programming language, the bare minimum C programcontains the following parts: Preprocessor Commands Functions Variables Statements & Expressions CommentsEvery C program consists of one or more functions, one of which must be main().Let us look at a simple code that would print the words "My First Program in C"followed by an explanation of the various parts of the C program:P a g e 11 65

Beginners’ Guide to C#include stdio.h void main(){/* My first program in C */printf("My Frist Program in C \n");}Structure of a C programThe various parts of the program given above are explained below:Preprocessor Commands1. #include stdio.h Start writing a C program with a preprocessor command #include stdio.h .This informs a C compiler to include a header file stdio.h before compiling theprogram. # is a preprocessor command. Include instructs the C compiler to include the header file libraryfunction. The header file contains the instruction for standard input andoutput. stdio.h - All the header file library functions are written within openand close angular brackets, . The expansion of stdio.h is “standard input and output header file. .h is the extension of the library function file identified by the compilerwith .h extension. All the library functions included in a C program are written as#include header file name.h Refer Library Functions to know about the list of other library functions that can beincluded in a C program.2. main() functionThe next line int main() is the main function where program execution begins.P a g e 12 65

Beginners’ Guide to CNoteIn C, semicolon (;) indicates the end of statement.#include statement does not end with a semicolon.All programs in C should have a main() function. There are two variations of main().They are void main() and int main(). void main() denotes a function does not returna value, int main() denotes a function that is of a numeric return type.3. Starting BraceAll C program start with a left brace {.and the program code always ends with aclosing brace - }.4. StatementsComment StatementThe next line /*.*/ will be ignored by the compiler and it has been put to addadditional comments in the program. So such lines are called comments in theprogram. You can give a brief description about the program within the /* .*/comment line statements.Input and Output statementsOutput statementprintf(.)The next line printf(.) is another function available in C which causes the message"My First Program in C” to be displayed on the screen. All the statements that youwant to display on the screen should start with theprintf( ) function.Input Statementscanf(“%d”, &a);The data type of the input is specified within double quotes, if it is of integer typethen it is % d and &a represents a variable data item.scanf( .) function can be used to enter any combination of numerical values, singlecharacters and strings.P a g e 13 65

Beginners’ Guide to CCompile & Execute C ProgramLet’s look at how to save the source code in a file, and how to compile and run it.Following are the simple steps:1. Open a text editor and add the above-mentioned code.2. Save the file as First.c in the TC\Bin directory. The directory where you havethe C compiler.3. Open a command prompt and go to the directory where you saved the file.4. Type TC First.c and press enter.5. This opens up the First.c program in the Turbo C window.6. To compile your code press Alt F9 key simultaneously.7. If there are no errors there will be no error message.8. You have to execute the file to view the output. To execute the file pressCtrl F9 keys simultaneously.9. You will be able to see "My First Program in C" printed on the screen.Output screen of First.cC uses structured programming with variables and recursive statements. In C, allexecutable code is contained within "functions" All C program use the semicolon asa statement terminator and curly braces({ }) for grouping blocks of statements.The following are the key points of C language: Uses preset keywords Includes flow of control structures for, if/else, while, switch, and do/while. A large number of arithmetical and logical operators are used. Statements are used to specify actions. Common statements are input,output and an expression statement. The expression statement consists ofan expression to be evaluated, followed by a semicolon;.P a g e 14 65

Beginners’ Guide to C Functions and procedures may be called and Variables may be assigned new values.The basic characters that are included in a program are: Lowercase and uppercase letters: a–z A–Z Decimal digits: 0–9 Graphic characters: ! " # % & ' ( ) * , - . / : ; ? [ \ ] { } Newline indicates the end of a text line; it need not correspond to an actualsingle character, although for convenience C treats it as one.Data typesC supports different types of data, the basic C data types are as listed below:S.No. DataTypeint1.DescriptionValue RangeThe numericinteger dataStorageSize2 or 4bytes2.CharSingle character1 byte-128 to 127 or 0 to 2553.FloatFloating pointnumber4 byte4.DoubleDouble-precisionfloating pointnumber8 byte-32,768 to 32,767 or 2,147,483,648 to2,147,483,6471.2E-38 to 3.4E 38(Precision up to 6 decimalplaces)2.3E-308 to 1.7E 308 (Precision up to 15 decimalplaces)The array types and structure types are referred to collectively as the aggregatetypes. The type of a function specifies the type of the function's return value. Wewill see basic types in the following section.The void TypeThe void type specifies that no value is available. It is used in the following kinds ofsituations:1. When a function does not return a value.2. For empty set of values.P a g e 15 65

Beginners’ Guide to CVariablesVariables store values and they are used to perform calculations and evaluateconditions. A variable refers to values that are not fixed, they keep changing. Cprogramming language also allows defining various other types of variables, otherthan those defined in the following type:VariableTypeIntegerDescriptionA variable, which can have onlyintegers, is called integer variable.Integer variables are used to storewhole numbers. A fractional valuecannot be stored in an integervariable.Exampleint v 10;int is the data typev is the variable 10 is thevalueCharacter A variable, which can store onlycharacters, is called charactervariable. Character constantsstored in these variables should beenclosed within single quotes.char str;;Floatfloat marks 66.78;where, float is the data typemarks is the variable 66.78 isthe value assigned to thevariable.Variables, which are used to storedecimal values, are called floatvariables. They can store bothinteger part (to the left of decimalpoint) and fractional part (to theright of decimal point).char str ‘A’;where, char is the data typestr is the variable , ‘A’ isvalue. The char data typevalues should be providedwithin single quotes.P a g e 16 65

Beginners’ Guide to CVariable Definition in CA variable definition means to tell the compiler where and how much to create thestorage for the variable. A variable definition specifies a data type and contains a listof one or more variables of a specific data type.Variable InitializationAssigning value to the variable is called Variable Initialization. A variable can beinitialized at the place where the variable is declared.Syntaxdata type variable name value;int x 15;float p 17.1;char z ’ p ’;In the following example variables have been declared, but they have been definedand initialized inside the main function:ExampleCODE#include stdio.h int main (){/* variable definition: */int a, b,c;float f 3.2, g;/* actual initialization */a 15;b 20;c a b;g f * (b/a);printf("Value of c : %d \n", c);printf("Value of g:\ %f", g);}P a g e 17 65

Beginners’ Guide to CResult- Output ScreenNoteA variable can be initialized anywhere in the program. To viewthe output as float use %f f type conversion.KeywordsThe keywords are used in program for specifying an instruction, they are reservedwords and they are as fwhiledoifstaticConstantsConstants refer to fixed values assigned to a variable in a program. Constants arealso called as literals. C has four basic types of constants. They are integer, floatingpoint, character and string constants. The integer and floating point constants areused to represent numeric values and they are collectively called numeric-typeconstants.P a g e 18 65

Beginners’ Guide to CCharacter constantsA character constant is a single character and is enclosed in single quotes, e.g., 'x'and can be stored in a simple variable of char type.A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'),or a universal character (e.g., '\u02C0').String ConstantsString literals or constants are enclosed in double quotes "". A string containscharacters that are similar to character literals: plain characters, escape sequences,and universal characters.You can break a long line into multiple lines using string literals and separate themusing whitespaces.Defining ConstantsThere are two simple ways in C to define constants:1. Using #define preprocessor.2. Using const keyword.The #define PreprocessorFollowing is the form to use #define preprocessor to define a constant:#define identifier valueP a g e 19 65

Beginners’ Guide to CExampleCODE#include stdio.h #define LENGTH 12#define WIDTH6int main(){int area;area LENGTH * WIDTH;printf("The area is: %d", area);}RESULT- Output ScreenThe const KeywordYou can use const prefix to declare constants with a specific type as follows:const type variable value;P a g e 20 65

Beginners’ Guide to CExampleCODE#include stdio.h int main(){const intLENGTH 12;const intWIDTH 6;int area;area LENGTH * WIDTH;printf("The area is: %d", area);}RESULT – Output ScreenNoteIt is a good programming practice to define constants inCAPITALS.P a g e 21 65

Beginners’ Guide to CEscape SequenceThere are certain characters in C when they are preceded by a backslash they willhave special meaning and they are used to represent like newline (\n) or tab (\t).Given below ere, some of escape sequence codes:Escape sequenceMeaning\\\ character\'' character\"" character\? character\aAlert or bell\bBackspace\fForm feed\nNewline\rCarriage return\tHorizontal tab\vVertical tabFollowing is the example to show few escape sequence characters:P a g e 22 65

Beginners’ Guide to CExampleCODE#include stdio.h void main(){printf("My First\t Program in C\n\n");printf(“\n New Line Escape Sequence”);printf(“\n Places the cursor at the first character \r”);}RESULT – Output ScreenIn the above example the \n , \t and \r escape sequences are used to: Display text in a Newline Place text with a Tab space To position the cursor at the first characterThe text is displayed in the next line but the cursor is positioned at the first character.Normally, the cursor is placed at the next line after the text within “” is displayed,but when \r escape sequence is used the cursor is positioned at the first character.P a g e 23 65

Beginners’ Guide to COperatorsAn operator is a symbol that tells the compiler to perform specific mathematical orlogical manipulations. Operators and operands together form an expression. Csupports set of operators, which are symbols used within an expression to specifythe manipulations to be performed while evaluating that expression. C operatorsare classified into Unary, Binary and Ternary operators.Operators that use only one operand are termed as unary operators, operators thatuse two operands to evaluate an expression are termed binary operators andoperator that uses three operands are termed ternary operators.Expression Examplea b c;In a b cb and c Operands OperatorUnary OperatorsThe unary operators are used to either increment the value of a variable ordecrement it, hence the operators are Increment and Decrement operators. is an Increment Operator-- is a Decrement OperatorUnary operators use only one operand. The Unary operators can be used as Postfixand Prefix operators.Postfix OperatorsThe Postfix operator follows the variable. Example: X ; Y--;Prefix OperatorsThe Prefix operator precedes the variable. Example: X; --Y;P a g e 24 65

Beginners’ Guide to CExampleCODE#include stdio.h void main(){int x 3, y 4;printf(“The value of X post incrementing the value is:\t%d\n”, x );printf(“The value of X post decrementing\t%d\n”, x--);the value is:printf(“The value of Y by using the prefix operator is:\t%d”, y);}RESULT – Output ScreenIn the above given example code the statement y, increments the value of y andthen prints the value. But when a post fix operator is used the value of the variableis displayed and then the value is incremented.C operators are as follows: Arithmetic Operators Relational Operators Logical Operators Assignment OperatorsP a g e 25 65

Beginners’ Guide to COperator TypeArithmeticDescriptionOperatorsArithmetic operators are used to perform , -, *, /, %mathematicaloperationslikeaddition,subtraction, multiplication and division.ArithmeticAssignment operators along with Arithmetic , , - ,Assignmentoperators allot value to an operand* , / , % ,& , , , , LogicalLogical operators are used to combine two or !, &&, more expressions.Conditional OperatorThe conditional operator is used to evaluate ?:an expression.Relational operatorsRelational operator are used to compare , ! , , ,values. It evaluates whether the given , expression is TRUE or FALSE.The following table details the operators with examples.Arithmetic OperatorsExample when A 10 and B 20OperatorDescriptionExample Adds two operandsA B will give 30-Subtracts second operand from the firstA - B will give 10*Multiplies both operandsA * B will give 200/Divides numerator by de-numeratorB / A will give 2P a g e 26 65

Beginners’ Guide to COperator%DescriptionExampleModulus Operator and remainder of after B % A will give 0an integer division Increments operator increases integer A will give 11value by one--Decrements operator decreases integer A-- will give 9value by oneExampleCODE#include stdio.h main(){int a 18,b 3;printf(“The sum of a and b is:\t%d\n”, a b);printf(“The remainder is:\t%d”, a%b);}RESULT – Output ScreenP a g e 27 65

Beginners’ Guide to CCode#include stdio.h main(){int a 2, y 2;a ; y;printf(“The incremented value of a is: %d\t\n”, a);printf(“The incremented value of y is :%d\t\n”, y);}RESULT – Output ScreenRelational OperatorsIn the following table an example is used to explain all the relational operator, whereA 10 and B 30.Operator DescriptionChecks if the values of two operands areequal or not, if yes then conditionExample(A B) is not true, hencethe result will be 0.becomes true.! Checks if the values of two operands are (A ! B) is true, hence theequal or not, if values are not equal then result of this statementcondition becomes true.will be 1Checks if the value of left operand isgreater than the value of right operand,(A B) is not true and theresult will be 0.if yes then condition becomes true.P a g e 28 65

Beginners’ Guide to COperator DescriptionChecks if the value of left operand is lessthan the value of right operand, if yesExample(A B) is true and theresult will be 1.then condition becomes true. Checks if the value of left operand isgreater than or equal to the value of right(A B) is not true, hencethe result will be 0.operand, if yes then condition becomestrue. Checks if the value of left operand is lessthan or equal to the value of right(A B) is true, hence theresult will be 1.operand, if yes then condition becomestrue.ExampleCODE#include stdio.h main(){int x 20;int y 65;int result 0;result x y;printf (“\n The result of the expression x y is: %d”,result);result x y;printf (“\n The result of the expression x y is: %d”,result);}P a g e 29 65

Beginners’ Guide to CRESULT – Output ScreenLogical OperatorsIn the following table an example is used to explain all the logical operator, whereA 10 and B 30.Operator&& DescriptionExampleCalled Logical AND operator. If both the operandsare non-zero, then condition becomes true.(A && B) isfalse.Called Logical OR Operator. If any of the twooperands is non-zero, then condition becomes true.!Called Logical NOT Operator. Use to reverses thelogical state of its operand. If a condition is true then(A B) istrue.!(A && B) istrue.Logical NOT operator will make false.ExampleCODE#include stdio.h main(){int x 1010;int result;result (x 1) && (x 1000);P a g e 30 65

Beginners’ Guide to Cprintf (“\n The result is :%d”, result);}RESULT – Output ScreenArithmetic Assignment OperatorsThe Arithmetic Assignment operator uses the arithmetic operators ( , -, *, /, %)along with the assignment operator to form an expression. There are manyassignment operators; here a few of them are detailed. In the following table thearithmetic assignment operators are detailed with an example where the values ofA, B and C are, 10, 20 and 0.Operator DescriptionExampleSimple assignment operator, Assigns C A B will assign value ofvalues from right side operands to left A B into C, hence C 30side operand Add and assignment operator, It adds C A is equivalent to C Cright operand to the left operand and A, hence the resultantassign the result to left operand- value of C will be 0 10 10Subtract and assignment operator, It C - A is equivalent to C Csubtracts right operand from the left– A, hence the resultantoperand and assign the result to left value of C will be 0-10 -10operandP a g e 31 65

Beginners’ Guide to COperator* DescriptionMultiply and assignment operator, Itmultiplies right operand with the leftoperand and assign the result to leftExampleC * A is equivalent to C C * A, hence the resultantvalue of C will be 0 *10 0operand/ % Divide and assignment operator, It C / A is equivalent to C Cdivides left operand with the right / A, hence the resultantoperand and assign the result to left value of C will be 0/10 0operandModulus and assignment operator, It C % A is equivalent to C Ctakes modulus using two operands and % A, hence the resultantassign the result to left operandvalue of C will be 0%10 0The Conditional operatorThe conditional operator ? : Operator is used to evaluate an expression.Syntaxvariable (conditional expression) ? TRUE: FALSEExamplex (y z)?y:zCODE#include stdio.h main(){int mark;char grade;printf(“Enter the mark: \n”);scanf(“%d”, &mark);grade (mark 75)?‘A’:‘B’;printf(“The grade is %c\t\n”, grade);}RESULT – Output ScreenP a g e 32 65

Beginners’ Guide to COperators Precedence in COperator precedence determines the grouping of terms in an expression. Thisaffects how an expression is evaluated. Certain operators have higher precedencethan others; for example, the multiplication operator has higher precedence thanthe addition operator. For example a 8 3 * 5; here, a is assigned 23, not 55because operator * has higher precedence than , so it first the multiplicationoperation is performed 3 * 5 and then adds with 8.P a g e 33 65

Beginners’ Guide to CEXERCISE1. What will be the output of the program?#include stdio.h main(){int a 10, b, c 0;printf(“Enter the first number: \n”);scanf(“%d”, &a);printf(“Enter the second number: \n”);scanf(“%d”, &b);c a%b;printf(“The resultant value stored in C is:\n%d”, c);}2. Write a program to accept the marks of a student in English, Maths andScience and display them.3. Write a program to accept a character and an integer. Format the inputsuch that only a maximum of 3 digits is accepted. Print the two values inthe same line.4. Write a program to accept three float values from the user. Format theoutput such that the values are printed with five digits after the decimalpoint.5. Write a program to accept the radius of a circle and print its area andcircumference.6. Write a program to do the following:a) Declare four variables n1, n2, r1 and r2.b) Accept a number from the user and store it in n1.c) Assign n1 to num2.P a g e 34 65

Beginners’ Guide to Cd) Increment n1 using the postfix increment operator and assign it to r1.e) Increment n2 using the prefix increment operator and assign it to r2.f) Print the values of r1 and r2.g) Compare the values of r1 and r2 using the “equal to” relational operator.h) Print the result of the comparison.7. Write a program to accept a number and check if it is divisible by 2 anddisplay the result.8.

Beginners’ Guide to C P a g e 10 65 Introduction to C Language C is a general purpose, high level programming language and is a widely used language. This language has facilities for structured programming and allows to efficiently provide machine instructions. Henc