Subject Overview Sr. no. Units % Weightage 1 Introduction to computer and programming 11 % 2 Fundamentals of C 9 % 3 Control structure in C 11 % 4 Array & String 13 % 5 Functions 11 % 6 Recursion 9 % 7 Pointers 9 % 8 Structure 9 % 9 Dynamic memory allocation 9 % 10 File management 9 % Reference books: 1. Programming in ANSI C by Balagurusamy 2. C Programming: Test Your Skills, 1/e by Ashok Kamthane 3. Programming With Ansi And Turbo C book : Ashok Kamthane ... 4. Programming in C Ansi standard, by Yashwant Kanetkar
UNIT-2 Fundamentals of C
Topics to be covered Introduction Features of ‘C’ Structure of C Program Comments Header files Data types in C Constants in C Variable Keywords
INTRODUCTION The C programming language was designed by Dennis Ritchie at Bell Laboratories in the early 1970s C is a general-purpose programming language that is extremely popular, simple and flexible. It is machine-independent, structured programming language which is used extensively in various applications.
Features of ‘C’ Simple: C uses English language to write the code. Also the syntax used in C coding are simple which can be easily understood by programmer. 2) Structured programming language: C is a structured programming language in the sense that we can break the program into parts using functions Middle level Language: C combines the features of both high-level language and middle level language. C is near to machine as well as human understandable language and also uses English language while coding. 4) Platform dependent: C language is said to be platform dependent whenever the program is execute in the same operating system where that was developed and compiled but not run and execute on other operating system. C is platform dependent programming language.
Features of ‘C’ 5) Portability: It is the concept of carrying the instruction from one system to another system. When we write and compile any C program on window operating system that program easily run on other window based system. 6) Powerful: C is a very powerful programming language, it have a wide verity of data types, functions, control statements, decision making statements, etc. 7) Case Sensitive: Case Sensitive is another features of C Language. It is a case sensitive programming language. In C programming ‘int and INT' both are different. It is also main feature of C Language. 8) Compiler Based: C is a compiler based programming language that means without compilation no C program can be executed. First we need compiler to compile our program and then execute.
Structure of C Program
Comments Comments are used in program to improve readability and understanding Comments are not executed. It generally help the programmer to understand the various operations. C supports two types of comments: Single line comment: Single line comment starts with the double forward slash // and it will continue up till the end of the line. For example: // this code is for addition 2. Multiline comment: Multiline comment starts with /* and ends with */ For example: /* program name: addition date: 12-12-2020 author: Dennis Ritchie */
Header files Header files contain set of predefined library functions that we can include in our program. In C libraries are available for various inbuilt functions. Example: #include<stdio.h> stdio means for Standard input output functions. printf () Syntax: printf (“Control string”); scanf () Syntax: scanf (“control string”,&variable name);
Header files #include<math.h> This header file is used for mathematical functions like, sqrt(), pow ( ), sin ( ) , etc …. #include It is a preprocessor directives. The #include directive tells the C preprocessor to include the contents of the file specified in the input stream to the compiler and then continue with the rest of the original file.
Data types in C A data type is a classification of various types of data, as floating-point, integer, or string. C is rich in its data types to allow programmer to select appropriate type of data type. The type of a variable determines how much space it occupies in storage. Data types in C Primary Data type (int, char, float, double) Secondary Data type Derived data type (array, pointer, etc..) User defined data types (structure, union, enum ) Fig: Data types in C
Primary data types Primary data types are built in data types. They are directly supported by machine. They are also known as fundamental data types. int int is integer which is whole number without fraction part. Its range is machine dependent values. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. signed signed unsigned unsigned Format specifier size (bit) size (byte) Range Format specifier size (bit) size (byte) Range short int % hd 8 1 -128 to 127 %hu 8 1 0 to 255 int %d 16 2 -32768 to 32767 %u 16 2 0 to 65535 long int % ld 32 4 -2,14,74,83,648 to 2,14,74,83,647 % lu 32 4 0 to 4,29,49,67,295
2) char char data type can store single character of alphabet or digit or special symbol. Each character is assigned some integer value which is known as ASCII values. 3) float float data type can store floating point number which represents a real number with decimal point and fractional part. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which consumes 80 bits of memory space. signed signed unsigned unsigned Format specifier size (bit) size (byte) Range Format specifier size (bit) size (byte) Range char %c 8 1 -128 to 127 %c 8 1 0 to 255 Format specifier size (bit) size (byte) Range float %f 32 4 1.2 e-38 to 3.4 e+38 double % lf 64 8 1.7e-308 to 1.7e+308 long float % Lf 80 10 3.4E-4932 to 1.1E+4932
Secondary data types Secondary data types are not directly supported by the machine. It is combination of primary data types to handle real life data in more convenient way. It can be further divided in two categories: Derived data type Derived data type is extension of primary data type. It is built-in system and its structure cannot be changed. Examples: Array, Pointer, etc … User defined data types User defined data type can be created by programmer using combination of primary data type and/or derived data type. Use can design it as per special requirements. Examples: Structure, Union, enum , etc …
Constants in C Constants are the terms that can't be changed during the execution of a program. For example: 1, 2.5, "Programming is easy." etc. or Constant is something whose value does not change throughout the program. In C, constants can be classified as: Constants Numeric constant Nonnumeric constant Single character constant String constant Fig: Types of Constant Integer constant real constant
Constants in C integer constants: Integer constant is a number without decimal point and fractional part There are three types of integers constant: Decimal integer: Decimal integer consist of a set of digits, 0 to 9 having optional – or + sign. No other characters are allowed like space, commas, and non-digit characters. Ex: 123, -321, 0, +78 Octal integer: Octal integer consists of any combination of digits from the set 0 to 7. Octal numbers are always preceded by 0. Ex: 037, 0, 0551 Hexadecimal integer: Hexadecimal integer consists of any combination of digits from the set 0 to 9 and A to F alphabets. It always starts with 0x or 0X. A represents 10, B represents 11… F represents 15. Ex: 0X2A, 0x95, 0xA47C.
Octal example: int a =012; printf (“given octal number : % o”,a ); printf ( “given octal number in decimal: % d”,a ); Output: given octal number : 12 given octal number in decimal: 10
Constants in C real constant: The number containing the fractional part is called real number. Ex: 0.0083, -0.75, +247.0, -0.75. A real number may also be expressed in exponential notation. The general form is: mantissa e exponent, ex: 215.65 can be written as 2.1565e2. In exponential form, e2 means multiply by 102. Single character constant: It contains single character enclosed within a pair of single quote mark. Ex: ‘5’, ‘A’, ‘;’, ‘ ‘ String constant: A string constant is a sequence of characters enclosed within a double inverted comma. The characters may be le ter , number, special character, blank space, etc … Ex: “DIET”, “1988”, “?A.B,!”, “5+3”, etc … ‘A’ is character but “A” is string.
Variable Variables are memory location in computer's memory to store data. To indicate the memory location, each variable should be given a unique name called identifier. Identifiers are used for naming variables, functions and arrays. Variable names are just the symbolic representation of a memory location. Examples of variable name: sum, car_no , count etc. int num ; float a,b ; char a ; Rules to define variable name: An identifier can be composed of letters (both uppercase and lowercase letters), digits and underscore '_' only. The first letter of identifier should be either a letter or an underscore. They must not begin with a digit. They can be of any of length however the first 8 characters are treated as significant by the C compiler. Reserved keywords can not be used as a variable.
Keywords Keywords are the reserved words used in programming. Each keywords has fixed meaning and that cannot be changed by user. For example:
OPERATORS
OPERATORS An operator is a symbol that tells the compiler to perform certain mathematical or logical operation. C has rich set of operators as below: Arithmetic Operators Relational Operators Logical Operators Assignment Operators Increment and Decrement Operators Conditional Operator Bitwise Operators Special Operators
1. Arithmetic Operators Arithmetic operators are used for mathematical calculation. C supports following arithmetic operators Sr.no Operator Meaning Explaination 1 + Addition or unary plus a+ b (addition), +7 (unary plus) 2 - Subtraction or unary minus a – b (subtraction), -8 (unary minus) 3 * Multiplication a * b 4 / Division a / b 5 % Modulo division a % b (this operator can be used with only integer data type)
2. Relational Operators Relational operators are used to compare two numbers and taking decisions based on their relation. Relational expressions are used in decision statements such as if, for, while, etc … Sr.no Operator Meaning 1 < less than 2 <= less than or equal to 3 > greater than 4 >= greater than or equal to 5 == is equal to 6 != is not equal to
3. Logical Operators Logical operators are used to test more than one condition and make decisions Sr.no Operator Meaning 1 && logical AND (Both non zero then true, either is zero then false) 2 || logical OR (Both zero then false, either is non zero then true) 3 ! logical NOT (non zero then false, zero then true) a b a&&b a||b 1 1 1 1 1 1 1 1
3. Logical Operators
3. Logical Operators
4. Assignment Operators Assignment operators are used to assign the result of an expression to a variable. C also supports shorthand assignment operators which simplify operation with assignment Sr.no Operator Meaning 1 = Assigns value of right side to left side 2 += a += 1 is same as a = a + 1 3 -= a -= 1 is same as a = a - 1 4 *= a *= 1 is same as a = a * 1 5 /= a /= 1 is same as a = a / 1 6 %= a %= 1 is same as a = a % 1
5. Increment and Decrement Operators These are special operators in C which are generally not found in other languages. Sr.no Operator Meaning 1 ++ Increments value by 1. a++ is postfix, the expression is evaluated first and then the value is incremented. 2 -- Decrements value by 1. a-- is postfix, the expression is evaluated first and then the value is decremented.
Write output of the following code. #include< stdio.h > #include< conio.h > void main() { int x=4,y=5; x = ++x * ++y; y = y++ * x++; printf (“ x = %d \n y = %d”, x,y ); getch (); }
Write output of the following code. #include< stdio.h > #include< conio.h > void main() { int x=4,y=5; printf (“value of x = %d”, x++); printf (“\ nvalue of x = %d”, x); printf (“\n value of ++y = %d”, ++y); printf (“value of y++ = %d”, y); getch () } OUTPUT: value of x =4 value of x =5 value of ++y =6 value of y++ =6
6. Conditional Operator Ternary operator is known as Conditional Operator. A ternary operator pair “ ? :” is available in c to construct conditional expressions of the form: exp1?exp2:exp3 Where exp1, exp2,exp3 are expression. The operator ?:works as follows: exp1 is evaluated first. if it is true, then the expression exp2 evaluated and becomes the value of the expression. If exp1 is false , exp3 is evaluated and its value becomes the value of the expression. a = 10; b = 15; X = (a>b) ? a : b;
7. Bitwise Operators Bitwise operators are used to perform operation bit by bit. Bitwise operators may not be applied to float or double. Sr.no Operator Meaning 1 & bitwise AND 2 | bitwise OR 3 ^ bitwise exclusive OR 4 << shift left ( shift left means multiply by 2) 5 >> shift right ( shift right means divide by 2)
8. Special Operators C supports some special operators of interest such as comma operator , sizeof operator, pointer operator (& and *) (discuss in unit 6 pointer) and member selection operators (. and - >). Sr.no Operator Meaning 1 & Address operator, it is used to determine address of the variable. 2 * Pointer operator, it is used to declare pointer variable and to get value from it. 3 , Comma operator. It is used to link the related expressions together. 4 sizeof It returns the number of bytes the operand occupies. 5 . member selection operator, used in structure. 6 - > member selection operator, used in pointer to structure.
expressions
Arithmetic expression An arithmetic expression is a combination of variables , constants and operators arranged as per the syntax of the language. We have used a number of simple expressions in the examples discussed so far. C can handle any complex mathematical expressions. Some of the examples e.g. C expressions are shown in next slide. Remember that C does not have an operator for exponentiation.
Expressions Algebraic Expression C Expression a b -c a*b-c (m+n)(x+y) (m+n)*(x+y) (ab/c) (a*b)/c x/y + c (x/y)+c a b -c a*b-c
EVALUATION OF expressions
EVALUATION OF expressions Expressions are evaluated using an assignment statement of the form: Variable=Expression Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first and the result then replaces the previous value of the variable on the left-hand side. All variables used in the expression must be assigned values before evaluation is attempted. Example of evaluation statement are: X= a*b-c; Y=b/c*a; Z=a-b/ c+d ; When these statement are used in a program, the variables a,b,c and d must be defined before they are used in the expressions.
Type Conversion
Type Conversion or Type Casting When an operator has operands of different types, they are converted to a common type, this is known as type casting or type conversion. Typecasting is making a variable of one data type to act like another data type such as an int to float. There are two types of type casting: Implicit Type Casting. Explicit Type Casting.
Implicit Type Casting When complier automatically convert data type of the data then it is called as a implicit type conversion. Explicit Type Casting When type casting forcefully converts the value of one type into another type then it is called as a explicit type conversion. Syntax : (type)expression;
Example: #include< stdio.h > #include< conio.h > void main() { int sum=47, n=10; float avg ; avg=sum / n; printf (“Result of Implicit Type Casting: %f”, avg ); avg =(float)sum / (float)n; printf (“Result of Explicit Type Casting: %f”, avg ); } // implicit type casting will print 4.0000 // explicit type casting will print 4.7000
Program to illustrate Type casting
Precedence & Associativity
Each of the C operators have a precedence or hierarchy associated to it that decides among the set of operators which is to be evaluated first or which should precede the other. There are distinct levels of precedence. The operators of same precedence are evaluated either from left to right or right to left, depending on the level. This is called associativity of operators.
Precedence of an operator is its priority in an expression for evaluation. Operator precedence is why the expression 5 + 3 * 2 is calculated as 5 + (3 * 2), giving 11, and not as (5 + 3) * 2, giving 16. We say that the multiplication operator (*) has higher "precedence" or "priority" than the addition operator (+), so the multiplication must be performed first. Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence. Operator associativity is why the expression 8 - 3 - 2 is calculated as (8 - 3) - 2, giving 3, and and not as 8 - (3 - 2), giving 7. We say that the subtraction operator (-) is "left associative", so the left subtraction must be performed first. When we can't decide by operator precedence alone in which order to calculate an expression, we must use associativity.
Following table provides a complete list of operator, their precedence level, and their rule of association. Rank 1 indicates highest precedence level and 15 is the lowest.