UNIT - I 1.C Language Introduction C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and Portable Low-level Memory Access Fast Speed Clean Syntax These features make the C language suitable for system programming like an operating system or compiler development. Writing the First Program in C // Simple C program to display "Hello World" // Header file for input output functions #include <stdio.h> // main function // where the execution of program begins int main() { // prints hello world printf("Hello World"); return 0; } 2.Structure Of C program 1. Header Files Inclusion – Line 1 [#include <stdio.h>] The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. All lines that start with # are processed by a preprocessor which is a program invoked by the compiler 2. Main Method Declaration – Line 2 [int main()] The next part of a C program is to declare the main() function. It is the entry point of a C program and the execution typically begins with the first line of the main(). The empty brackets indicate that the main doesn’t take any parameter 3. Body of Main Method – Line 3 to Line 6 [enclosed in {}] The body of a function in the C program refers to statements that are a part of that function. It can be anything like manipulations, searching, sorting, printing, etc. A pair of curly brackets define the body of a function. All functions must start and end with curly brackets. 4. Statement – Line 4 [printf(“Hello World”);] Statements are the instructions given to the compiler. In C, a statement is always terminated by a semicolon (;). In this particular case, we use printf() function to instruct the compiler to display “Hello World” text on the screen. 5. Return Statement – Line 5 [return 0;] The last part of any C function is the return statement. The return statement refers to the return values from a function. This return statement and return value depend upon the return type of the function. The return statement in our program returns the value from main(). 3.Executing C Program The C programs are executed in a system. This is basically the compilation process of a C program. The following diagram will show how a C Source Code can be executed. C Code − This is the code that you have written. This code is sent to the Preprocessors section. Preprocessing − In this section the preprocessor files are attached with our code. We have use different header files like stdio.h, math.h etc. These files are attached with the C Source code and the final C Source generates. (‘#include’, ‘#define’ These are Preprocessor Directives.) Compiler − After generating the preprocessed source code, it moves to the compiler and the compiler generates the assembly level code after compiling the whole program. Assembler − This part takes the assembly level language from compiler and generates the Object code, this code is quite similar to the machine code (set of binary digits). Linker − Linker is another important part of the compilation process. It takes the object code and link it with other library files, these library files are not the part of our code, but it helps to execute the total program. After linking the Linker generates the final Machine code which is ready to execute. Loader − A program, will not be executed until it is not loaded in to Primary memory. Loader helps to load the machine code to RAM and helps to execute it. While executing the program is named as Process. So process is (Program in execution). 4.DataTypes Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. Sr.No . 1 Types & Description Basic Types They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types. 2 Enumerated types They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program. 3 The type void The type specifier void indicates that no value is available. 4 Derived types They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types. 4.1 Integer Types The following table provides the details of standard integer types with their storage sizes and value ranges − Type Storage size Value range char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 8 bytes or (4bytes for 32 bit OS) -9223372036854775808 to 9223372036854775807 unsigned long 8 bytes 0 to 18446744073709551615 4.2 Floating-Point Types The following table provide the details of standard floating-point types with storage sizes and value ranges and their precision − Type Storage size Value range Precision float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places 4.3 Character Data Type Character data type allows its variable to store only a single character. The size of the character is 1 byte. It is the most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers. Range: (-128 to 127) or (0 to 255) Size: 1 byte Format Specifier: %c 4.4 Void Data Type The void data type in C is used to specify that no value is present. It does not provide a result value to its caller. It has no values and no operations. It is used to represent nothing. Void is used in multiple ways as function return type, function arguments as void, and pointers to void . 5.Comments in C Comments can be used to explain code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments can be singled-lined or multi-lined. Single-line Comments - Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by the compiler (will not be executed). Example // This is a comment printf("Hello World!"); C Multi-line Comments - Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored by the compiler Example /* The code below will print the words Hello World! to the screen, and it is amazing */ printf("Hello World!"); 6. Tokens Tokens in C as the smallest individual elements in a program that is meaningful to the functioning of a compiler. A token is the smallest unit used in a C program. Each and every punctuation and word that you come across in a C program is token. Types of Tokens Types of Tokens o o o o o o Keywords in C Identifiers in C Strings in C Operators in C Constant in C Special Characters in C 6.1 Keywords in C Keywords in C can be defined as the pre-defined or the reserved words having its own importance, and each keyword has its own functionality. Since keywords are the pre-defined words used by the compiler, so they cannot be used as the variable names. If the keywords are used as the variable names, it means that we are assigning a different meaning to the keyword, which is not allowed. C language supports 32 keywords given below: auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while 6.2 Identifiers in C Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the user-defined words. It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the starting letter should be either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in C are given below: o The first character of an identifier should be either an alphabet or an underscore, and then it can be followed by any of the character, digit, or underscore. o It should not begin with any numerical digit. o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case sensitive. o Commas or blank spaces cannot be specified within an identifier. o Keywords cannot be represented as an identifier. o The length of the identifiers should not be more than 31 characters. o Identifiers should be written in such a way that it is meaningful, short, and easy to read. 6.3 Strings in C Strings in C are always represented as an array of characters having null character '\0' at the end of the string. This null character denotes the end of the string. Strings in C are enclosed within double quotes, while characters are enclosed within single characters. The size of a string is a number of characters that the string contains. char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array. 6.4 Operators in C Operators in C is a special symbol used to perform the functions. The data items on which the operators are applied are known as operands. Operators are applied between the operands. Unary Operator A unary operator is an operator applied to the single operand. For example: increment operator (++), decrement operator (--), sizeof, (type)*. Binary Operator The binary operator is an operator applied between two operands. The following is the list of the binary operators: o o o o o o o o Arithmetic Operators Relational Operators Shift Operators Logical Operators Bitwise Operators Conditional Operators Assignment Operator Misc Operator 6.5 Constants in C A constant is a value assigned to the variable which will remain the same throughout the program, i.e., the constant value cannot be changed. Types of constants in C Constant Example Integer constant 10, 11, 34, etc. Floating-point constant 45.6, 67.8, 11.2, etc. Octal constant 011, 088, 022, etc. Hexadecimal constant 0x1a, 0x4b, 0x6b, etc. Character constant 'a', 'b', 'c', etc. String constant "java", "c++", ".net", etc. 6.6 Special characters in C Some special characters are used in C, and they have a special meaning which cannot be used for another purpose. o Square brackets [ ]: The opening and closing brackets represent the single and multidimensional subscripts. o Simple brackets ( ): It is used in function declaration and function calling. For example, printf() is a pre-defined function. o Curly braces { }: It is used in the opening and closing of the code. It is used in the opening and closing of the loops. o Comma (,): It is used for separating for more than one statement and for example, separating function parameters in a function call, separating the variable when printing the value of more than one variable using a single printf statement. o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that we are using the header file. o Asterisk (*): This symbol is used to represent pointers and also used as an operator for multiplication. o Tilde (~): It is used as a destructor to free memory. o Period (.): It is used to access a member of a structure or a union. 7. Variables in C A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be reused many times.It is a way to represent memory location through symbol so that it can be easily identified. Syntax to declare a variable: type variable_list; Example int a; float b; char c; int a=10,b=20;//declaring 2 variable of integer type float f=20.8; char c='A'; Rules for defining variables o A variable can have alphabets, digits, and underscore. o A variable name can start with the alphabet, and underscore only. It can't start with a digit. o No whitespace is allowed within the variable name. o A variable name must not be any reserved word or keyword, e.g. int, float, etc. Valid variable names: inta; int_ab; inta30; Invalid variable names: int2; intab; intlong; 7.1 Assiging Values to Variables To assign a value to a variable is that assignment expression. Assignment expressions assign a value to the left operand. The left operand must be a modifiable lvalue. An lvalue is an expression representing a data object that can be examined and altered. Syntax typevariableName=value; Example int myNum = 15; A volatile keyword in C is just a qualifier used by the programmer when declaring a variable in source code. It tells the compiler that the variable value can be modified at any point without needing any task from the source code. Example volatile int x = 0; // declare a volatile integer variable. 8. Operators C Operators are symbols that represent operations to be performed on one or more operands. C provides a wide range of operators, which can be classified into different categories based on their functionality. Operators are used for performing operations on variables and values. Types of Operators in C C has many built-in operators and can be classified into 6 types: 1. 2. 3. 4. 5. 6. Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Other Operators 8.1 C Arithmetic Operators An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables). Operator Meaning of Operator + addition or unary plus - subtraction or unary minus * multiplication / division % remainder after division (modulo division) Example 1: Arithmetic Operators // Working of arithmetic operators #include <stdio.h> int main() { int a = 9,b = 4, c; c = a+b; printf("a+b = %d \n",c); c = a-b; printf("a-b = %d \n",c); c = a*b; printf("a*b = %d \n",c); c = a/b; printf("a/b = %d \n",c); c = a%b; printf("Remainder when a divided by b = %d \n",c); return 0; } a+b = 13 a-b = 5 a*b = 36 a/b = 2 Remainder when a divided by b=1 8.2 C Increment and Decrement Operators C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand. Example 2: Increment and Decrement Operators // Working of increment and decrement operators #include <stdio.h> int main() { int a = 10, b = 100; float c = 10.5, d = 100.5; printf("++a = %d \n", ++a); printf("--b = %d \n", --b); printf("++c = %f \n", ++c); printf("--d = %f \n", --d); return 0; } Output ++a = 11 --b = 99 ++c = 11.500000 --d = 99.500000 8.3 Increment ++ and Decrement -- Operator as Prefix and Postfix In programming (C) the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1. a=5 ++a; // a becomes 6 a++; // a becomes 7 --a; // a becomes 6 a--; // a becomes 5 8.4 C Assignment Operators An assignment operator is used for assigning a value to a variable. The most common assignment operator is = Operator Example Same as = a=b a=b += a += b a = a+b -= a -= b a = a-b *= a *= b a = a*b /= a /= b a = a/b %= a %= b a = a%b Example 3: Assignment Operators // Working of assignment operators #include <stdio.h> int main() { int a = 5, c; c = a; // c is 5 printf("c = %d\n", c); c += a; // c is 10 printf("c = %d\n", c); c -= a; // c is 5 printf("c = %d\n", c); c *= a; // c is 25 printf("c = %d\n", c); c /= a; // c is 5 printf("c = %d\n", c); c %= a; // c = 0 printf("c = %d\n", c); return 0; } Run Code Output c=5 c = 10 c=5 c = 25 c=5 c=0 8.5 C Relational Operators A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0. Relational operators are used in decision making and loops. Operator Meaning of Operator Example == Equal to 5 == 3 is evaluated to 0 > Greater than 5 > 3 is evaluated to 1 < Less than 5 < 3 is evaluated to 0 != Not equal to 5 != 3 is evaluated to 1 >= Greater than or equal to 5 >= 3 is evaluated to 1 <= Less than or equal to 5 <= 3 is evaluated to 0 Example 4: Relational Operators // Working of relational operators #include <stdio.h> int main() { int a = 5, b = 5, c = 10; printf("%d == %d is %d \n", a, b, a == b); printf("%d == %d is %d \n", a, c, a == c); printf("%d > %d is %d \n", a, b, a > b); printf("%d > %d is %d \n", a, c, a > c); printf("%d < %d is %d \n", a, b, a < b); printf("%d < %d is %d \n", a, c, a < c); printf("%d != %d is %d \n", a, b, a != b); printf("%d != %d is %d \n", a, c, a != c); printf("%d >= %d is %d \n", a, b, a >= b); printf("%d >= %d is %d \n", a, c, a >= c); printf("%d <= %d is %d \n", a, b, a <= b); printf("%d <= %d is %d \n", a, c, a <= c); return 0; } Run Code Output 5 == 5 is 1 5 == 10 is 0 5 > 5 is 0 5 > 10 is 0 5 < 5 is 0 5 < 10 is 1 5 != 5 is 0 5 != 10 is 1 5 >= 5 is 1 5 >= 10 is 0 5 <= 5 is 1 5 <= 10 is 1 8.6 C Logical Operators An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. Operator Meaning Example && Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0. || Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1. ! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(c==5) equals to 0. Example 5: Logical Operators // Working of logical operators #include <stdio.h> int main() { int a = 5, b = 5, c = 10, result; result = (a == b) && (c > b); printf("(a == b) && (c > b) is %d \n", result); result = (a == b) && (c < b); printf("(a == b) && (c < b) is %d \n", result); result = (a == b) || (c < b); printf("(a == b) || (c < b) is %d \n", result); result = (a != b) || (c < b); printf("(a != b) || (c < b) is %d \n", result); result = !(a != b); printf("!(a != b) is %d \n", result); result = !(a == b); printf("!(a == b) is %d \n", result); return 0; } Run Code Output (a == b) && (c > b) is 1 (a == b) && (c < b) is 0 (a == b) || (c < b) is 1 (a != b) || (c < b) is 0 !(a != b) is 1 !(a == b) is 0 Explanation of logical operator program (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true). (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false). (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true). (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false). !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true). !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false). 8.7 C Bitwise Operators During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power. Bitwise operators are used in C programming to perform bit-level operations. Operators Meaning of operators & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR ~ Bitwise complement << Shift left >> Shift right 8.8 Comma Operator Comma operators are used to link related expressions together. For example: int a, c = 5, d; 8.9 The sizeof operator The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc). Example 6: sizeof Operator #include <stdio.h> int main() { int a; float b; double c; char d; printf("Size of int=%lu bytes\n",sizeof(a)); printf("Size of float=%lu bytes\n",sizeof(b)); printf("Size of double=%lu bytes\n",sizeof(c)); printf("Size of char=%lu byte\n",sizeof(d)); return 0; } Run Code Output Size of int = 4 bytes Size of float = 4 bytes Size of double = 8 bytes Size of char = 1 byte 8.10 C Ternary Operator The ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote"); Syntax of Ternary Operator The syntax of ternary operator is : testCondition ? expression1 : expression 2; The testCondition is a boolean expression that results in either true or false. If the condition is true - expression1 (before the colon) is executed false - expression2 (after the colon) is executed Example: C Ternary Operator #include <stdio.h> int main() { int age; // take input from users printf("Enter your age: "); scanf("%d", &age); // ternary operator to find if a person can vote or not (age >= 18) ? printf("You can vote") : printf("You cannot vote"); return 0; } Run Code Output 1 Enter your age: 12 You cannot vote 9.Operator Precedence Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Category Operator Associativity Postfix () [] -> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left Multiplicative */% Left to right Additive +- Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left Comma , Left to right Example #include <stdio.h> main() { int a = 20; int b = 10; int c = 15; int d = 5; int e; e = (a + b) * c / d; // ( 30 * 15 ) / 5 printf("Value of (a + b) * c / d is : %d\n", e ); e = ((a + b) * c) / d; // (30 * 15 ) / 5 printf("Value of ((a + b) * c) / d is : %d\n" , e ); e = (a + b) * (c / d); // (30) * (15/5) printf("Value of (a + b) * (c / d) is : %d\n", e ); e = a + (b * c) / d; // 20 + (150/5) printf("Value of a + (b * c) / d is : %d\n" , e ); return 0; } When you compile and execute the above program, it produces the following result − Value of (a + b) * c / d is : 90 Value of ((a + b) * c) / d is : 90 Value of (a + b) * (c / d) is : 90 Value of a + (b * c) / d is : 50 10. Expression An expression is a combination of operators and operands which reduces to a single value. An operation is performed on a data item which is called an operand. An operator indicates an operation to be performed on data. For example, z = 3+2*1 z=5 Primary expressions − It is an operand which can be a name, a constant or any parenthesized expression. Example − c = a+ (5*b); Postfix expressions − In a postfix expression, the operator will be after the operand. Example − ab+ Prefix expressions − n a prefix expression, the operator is before the operand. Example − +ab Unary expression − It contains one operator and one operand. Example − a++, --b Binary expression − t contains two operands and one operator. Example − a+b, c-d Ternary expression − It contains three operands and one operator. For Example, Exp1? Exp2 − Exp3. If Exp1 is true, Exp2 is executed. Otherwise, Exp3 is executed.