C programming | Class 8 | III Term


Published on

Published in: Education
  • thanx si
    Are you sure you want to  Yes  No
    Your message goes here
  • Thanks sir for this. Very helpful
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

C programming | Class 8 | III Term

  1. 1. Introduction to C Programming Class : 8The C programming language is a popular and widely used programming language forcreating computer programs. Dennis Ritchie at AT & T Bell Laboratories developed theC language three decades ago. It is an efficient, flexible and portable language.Portability refers to the case in which a unit of software written on one computer may bemoved to another computer without any or little modification.C has a wide diversity of operators and commands. C can be effectively utilized fordevelopment of system software like, operating systems, compilers, text processors,and database management systems. C is well suited for developing applicationprograms too.The C language is composed of the following basic types of elements: keywords,Constants, Identifiers, operators & punctuation. These elements are collectivelyknown as tokens. A token is a source program text that the compiler does not breakdown into component elements.Character SetThe characters used in C language are grouped into three classes.  Alphabetic characters (a, b, c, …., z) (A, B, C, ….., Z)  Numeric characters 0 through 9  Special charactersConstantsA constant is of numeric or non-numeric type. It can be a number, a character or acharacter string that can be used as a value in a program. As the name implies, thevalue of a constant cannot be modified. Numeric data is primarily made up of numbersand can include decimal points. Non-numeric data may be composed of numbers,letters, blanks and any special characters supported by the system.Numeric constants are of three types:  integer constant  floating-point constant  character constantInteger ConstantAn integer constant is a decimal number (base 10) that represents an integral value (thewhole number). It comprises of the digits 0 to 9. Integer constants are positive unlessthey are preceded by a minus sign and hence –18 is also a valid integer constant.Special characters are not allowed in an integer constant. The constant 2,345 is aninvalid integer constant because it contains the special character.Floating - point ConstantA floating-point constant is a signed real number. It includes integer portion, a decimalpoint, fractional portion and an exponent. While representing a floating point constant,either the digits before the decimal point (the integer portion) or the digits after thedecimal point (the fractional portion) can be omitted but not both. The decimal point canbe omitted if an exponent is included. An exponent is represented in powers of 10 indecimal system. Example: 58.64 is a valid floating-point (real) constant.Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 1
  2. 2. Character ConstantA character is a letter, numeral or special symbol, which can be handled by thecomputer system. These available symbols define the system’s character set. Enclosinga single character from the system’s character set within single quotation marks form acharacter constant.Example: ‘1’, ‘a’, ‘+’, and ‘-‘ are the valid character constants.Escape SequencesCharacter combinations consisting of a backslash followed by a letter is called escapesequence. An escape sequence may be used to represent a single quote as a characterconstant. Similarly some nonprintable characters are represented using escapesequence characters.Examples:‘a’ Bell (beep)‘b’ Backspace‘f’ Form feed‘r’ Carriage return‘n’ New line‘0’ null characterString LiteralA string literal or a string constant is a sequence of characters from the system’scharacter set, enclosed in double quotes. By default, the null character ‘0’ is assumedas the last character in a string literal. “hello” is a valid string literal. The actual numberof characters in this string literal is 6 including the null character at the last. The nullcharacter is invisible here. Six bytes are required to store this string in memory.However, the physical length of this string is 5 characters.IdentifiersIdentifiers are the names that are to be given to the variables, functions, data types andlabels in a program.The valid variable names are:X length x_value y_value a123Rules to name a variable:  The name of a variable can consist of alphabets (letters) and numbers.  Other characters are not allowed in the name of a variable.  An underscore character can be used as a valid character in the variable name.  The variable name starts with an alphabet and its length may vary from one character to 32 characters.  The first character in a variable’s name should be an alphabet, ie., a number is not allowed as a first character in the variable name.  Keywords (which have special meaning in C) cannot be used as identifiers.Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 2
  3. 3. Fundamental Data TypesData is one of the most commonly used terms in programming. Data can be defined asthe raw information input to the computer. Data is differentiated into various types in C.There are three numeric data types that comprise the fundamental or primary datatypes. The fundamental data types are: int, float and char. They are also called as pre-defined primitive types associated with the C compiler. The C compiler knows aboutthese types and the operations that can be performed on the values of these types. Thefollowing are the declaration statements of variables of different types:int x;float f;char ch;We know already that an integer is a whole number, a float is a real number and acharacter is represented within single quotes.Example:1 is an integer (whole number)1.0 is a real number (floating point number)‘1’ is a character constant“1” is a string literalAn integer requires 2 bytes of memory to store its value, a float requires 4 bytes ofmemory and a character requires 1 byte of memory.OperatorsC has rich set of operators. An operator is defined as a symbol that specifies anoperation to be performed. Operators inform the computer what tasks it has to performas well as the order in which to perform them. The order in which operations areperformed is called the order of precedence. It is also called hierarchy. The directionin which operations are carried out is called associativity.There are three types of operators in C.  Unary operators  Binary operators  Ternary operatorUnary OperatorsOrder of precedence is high for the unary operators and they have only one operand.The order of evaluation (associativity) is from right to left.The increment (++) or decrement (--) operator is used to increase or to decrease thecurrent value of a variable by 1. Generally the unary operators appear before theoperand.There are two forms:Postfix increment or decrementPrefix increment or decrementClass 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 3
  4. 4. The unary operators ++ and -- are called prefix increment or decrement operators whenthey appear before the operand. The unary operators ++ and -- are called postfixincrement or decrement operators when they appear after the operand.Binary OperatorsArithmetic OperatorsThe arithmetic operators +, -, *, /, and % are binary operators as they have twooperands. All the arithmetic operators observe left to right associativity.The arithmetic operators can be used with integers and float values. The modulusoperator works with integers only and it gives the remainder value after division.Relational OperatorsThe relational or Boolean operators are binary operators as they always have twooperands. All the relational operators observe left to right associativity, that is, they areevaluated from left to right.Logical OperatorsThe logical operators “&&” and “||” are used to connect two or more relationalexpressions. The “&&” operator is the logical AND operator and it returns a value of trueif both of its operands evaluate to true. A value of false is returned if one or both of itsoperands evaluate to false.The logical OR operator “||” returns a value of true when one or both of its operandsevaluates to true and a value of false when both of its operands evaluate to false.Assignment OperatorsThe assignment operator (=) assigns the value of the right-hand operand to theleft-hand operand. C has arithmetic-assignment operators too.They are +=, - =, *=, /= and %=.Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 4
  5. 5. Consider the following statement: i = i + 1;Here, the old value of the variable i is incremented by 1 and the incremented value isstored as the new value of i. The above statement can be represented in the followingways. Using the arithematic - assignment operator, i += 1;In the above statement, the operator += is used to increment the old value of i by oneand the new value is stored in the variable I itself. Similarly, the statement i *= 2;represents that the old value of i is multiplied by 2 and the new value is stored in i itself.The order of evaluationUsing the precedence of operators, we will see how to evaluate an expression. Thebracketed expression should be evaluated first. Consider the following expression 5 * 2 + 8 + (3 – 2) * 5 It will be evaluated as follows: 5*2+8+1*5 (bracketed expression is evaluated first) 10 + 8 + 5 (multiplication has higher precedence over addition) 23 (the value of the expression is 23)Ternary OperatorC has one ternary operator, which is a conditional operator. The symbol used for thisoperator is ?: and it has three operands.The syntax of the conditional operator is as follows:conditional expression? expression 1 : expression 2;If the conditional expression is true, expression 1 is evaluated.If the conditional expression is false, expression 2 is evaluated.Example :The following example show the uses of conditional operator: c = (a > b) ? a : b;If a is greater than b, the value of a is assigned to c else the value of b is assigned to c.PunctuationsC’s punctuation symbols and their uses are listed as follows:[] - used to represent array index (square brackets){} - used to cover the body of the function (curly braces)() - used to represent a function, to group items and to group expressions (simple parentheses)<> - used to enclose a header file in a preprocessor statement (angular brackets)““ - used to represent string literals (double quotes)‘‘ - used to represent a character constant (single quotes)Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 5
  6. 6. /* */ - used to represent a comment; - used as a statement terminator, - used to separate itemsblank and white space – used to improve readability of the program.Structure of C ProgramA program is defined as a set of instructions to be executed sequentially to obtain thedesired result. A function is a program, which is being used to carry out some smalltask. C programs can be very small. C programs are made up of functions. A programcannot be written without a function. A function may be pre-defined or user-defined.# include <stdio.h>main(){ printf(“Welcome to C Programming”);}This program, upon execution, will display the message Welcome to C Programmingon the screen. The user has to define the main() function to provide necessary code.When a C program runs, the control is transferred to this function. This is called theprogram’s entry point. The program has two functions, one is the user-defined main()function which is the entry point and the other one is printf() function which ispre-defined and used to display the results on the standard output (screen or monitor).Simple parentheses () are used to represent a function. Here main() is the callingfunction and printf() is the called function.The first line in the program # include <stdio.h> is a preprocessor statement. #includeis a preprocessor directive. The preprocessor is a software program that will expand thesource code while the program is compiled. The #include <stdio.h> statement includesthe contents of the stdio.h file (standard input and output header file) globally, that is,prior to the main() function. The contents of the stdio.h file are the function declarationstatements of the pre-defined output and input functions like printf() and scanf() etc.StatementsEach and every line of a C program can be considered as a statement. There aregenerally four types of statements. They are:  Preprocessor statement  Function header statement  Declaration statement  Executable statementAs you know already, the preprocessor statement is used to expand the source code byincluding the function declaration statements from the specified header files. Thefunction header statement is used as a first line in the definition of a function. Thedeclaration statements are further classified into variable declaration statements andfunction declaration statements.Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 6
  7. 7. Input and Output StatementsThe function printf() is used to display the results on the standard output (screen). Wehave seen the use of printf() to display the string on the monitor. Actually, the firstparameter of the printf() function is a string which is used to control the output and,hence it can be called as “control string”. This parameter is used to format the outputfor display and hence we can also call it as a “formatting string”.Example:To print a value of an integer:int n; /* variable n is declared as integer*/n = 10;printf(“%d”, n);In the above example, ‘%d’ is used as a formatting character within the control string ofprintf() function to display the value of an integer. The control string of printf() functioncan take three types of characters.  Ordinary characters  Formatting characters  Escape sequence charactersOrdinary characters within the control string are displayed as such. In the case ofprintf(“hello”); statement, the control string has ordinary characters only. They aredisplayed as such on the screen. The following table lists the formatting characters usedto display the values of various types.Input from keyboardTo read a value from the keyboard (standard input), the function scanf() is used. Thecode segment to read a value for an integer variable x is given below:int x;scanf(“%d”, &x);While the scanf() function is being executed, the system waits for the user’s input. Theuser has to provide data through keyboard. The data will be placed in the location of xonly after “Enter” key is pressed in the keyboard. The second parameter of the abovescanf() function is &x, which represents the address of x. & is the address of operatorand when it is being used with a variable, it provides the address of that variable.Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 7
  8. 8. Lab Exercises1. Write a C program to display a message “Welcome to C programming”. # include <stdio.h> # include <conio.h> main() { clrscr(); printf(“Welcome to C programming”); getch(); }2. Write a C program to find the sum of 2 numbers. # include <stdio.h> # include <conio.h> main() { int a,b,c; printf(“nEnter any 2 numbers:”); scanf(“%d %d”,&a,&b); c=a+b; printf(“nSum of 2 nos=%d”,c); getch(); }3. Write a C program to find the area of rectangle. # include <stdio.h> # include <conio.h> main() { float a,l,b; printf(“nEnter Length & Breadth:”); scanf(“%f %f”,&l,&b); a=l*b; printf(“nArea of Rectangle=%f”,a); getch(); }Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 8
  9. 9. 4. Write a C program to calculate simple interest. # include <stdio.h> # include <conio.h> main() { float p,n,r,si; printf(“nEnter values of P,N & R:”); scanf(“%f %f %f”,&p,&n,&r); si=(p*n*r)/100; printf(“nSimple Interest=%f”,si); getch(); }5. Write a C program to find the area of triangle. # include <stdio.h> # include <conio.h> main() { float a,b,h; printf(“nEnter Base & Height:”); scanf(“%f %f”,&b,&h); a=0.5*b*h; printf(“nArea of Triangle=%f”,a); getch(); } Question Bank2 mark questions:1. Write a short note on C Programming.2. What are tokens ? Name them.3. Write a note on Character Set.4. Define constants.5. What are the types of constants ?6. What do you mean by integer constants ?7. Write a note on floating point constants.8. What are character constants ?Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 9
  10. 10. 9. Define escape sequence.10. Write a note on String literal.11. Define identifiers.12. Define operator in C.13. What is hierarchy ?14. Define associativity.15. What are the types of operators ?16. Write a note on Unary operators.17. Write a note on Arithmetic operators in C.18. What are the relational operators in C.19. Write a note on logical operators.20. What is the purpose of Assignment operator in C.21. What are the types of statements used in C.22. Write a C program to display a message “Welcome to C programming”.23. List down the formatting characters used to display the values of various types.5 mark questions:1. What are the features of C language ?2. Write a note on escape sequences in C language.3. List down the rules to name a variable in C.4. Explain the fundamental data types in C programming.5. Explain the order of evaluation in C with an example.6. Explain conditional operator with an example.7. Explain printf statement in C language.8. How do you input data from keyboard ?9. Write a C program to find the sum of 2 numbers.10. Write a C program to find the area of rectangle.11. Write a C program to calculate simple interest.12. Write a C program to find the area of triangle.8 mark questions:1. Explain the types of constants in C language.2. Explain Binary operators in C.3. Explain the structure of C program.4. Explain the punctuation symbols used in C language. *************************Class 8 | C programming | III Term | R. Andrew, M.Sc[IT], M.C.A, M.Phil 10