CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING HISTORY OF ‘C’ : • The root of all modern Languages is ALGOL in 1960, this language uses structural programming and popular in Europe. • Martin Richards developed a language called BCPL (Basic Combined Programming Language) in 1967, BCPL is developed for system software. • Ken Thompson created new language in 1970 called B Language at Bell Laboratories, this language is created for UNIX. • Dennis Ritchie created new language in 1972 called C language at Bell Laboratories, it was developed along with the UNIX OS. Year Language By whom 1960 ALGOL International Group 1967 BCPL Martin Richards 1970 B Ken Thompson 1972 Traditional C Dennis Ritchie 1978 K&RC Kernighan & Dennis Ritchie 1989 ANSI C ANSI Committee 1990 ANSI/ISO C ISO committee 1999 c99 Standard committee COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING IMPORTANCE OF ‘C’ : 1. C is a robust language and has a rich set of built-in functions, data types, and operators which can be used to write any complex program(s). 2. Programs written in C are efficient due to the availability of several data types and operators. 3. C has the capabilities of an assembly language (low-level features) with the feature(s) of highlevel language so it is well suited for writing both system software and application software. 4. C is a highly portable language that means code written in one machine can be moved to other which is a very important and powerful feature. 5. C supports low-level features like bit-level programming and direct access to memory using pointer which is very useful for managing resources efficiently. 6. C has high-level constructs and it is more user-friendly as its syntax approaches to English like language. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING ADVANTAGES OF ‘C’ : 1. Building Block for Many Other Programming Languages C is considered to be the most fundamental language that needs to be studied if you are beginning with any programming language. Many programming languages such as Python, C++, Java, etc are built with the base of the C language. 2. Powerful and Efficient Language C is a robust language as it contains many data types and operators to give you a vast platform to perform all kinds of operations. 3. Portable Language C is very flexible, or we can say machine-independent that helps you to run your code on any machine without making any change or just a few changes in the code. 4. Built-in Functions There are only 32 keywords in ANSI C, having many built-in functions. These functions are helpful when building a program in C. 5. Quality to Extend Itself Another crucial ability of C is to extend itself. We have already studied that the C language has its own set of functions in the C library. So, it becomes easy to use these functions. We can add our own functions to the C Standard Library and make code simpler. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING ADVANTAGES OF ‘C’ : 6. Structured Programming Language C is structure-based. It means that the issues or complex problems are divided into smaller blocks or functions. This modular structure helps in easier and simpler testing and maintenance. 7. Middle-level Language C is a middle-level programming language that means it supports high-level programming as well as low-level programming. It supports the use of kernels and drivers in low-level programming and also supports system software applications in the high-level programming language. 8. Implementation of Algorithms and Data Structures The use of algorithms and data structures in C has made program computations very fast and smooth. Thus, the C language can be used in complex calculations and operations such as MATLAB. 9. Procedural Programming Language C follows a proper procedure for its functions and subroutines. As it uses procedural programming, it becomes easier for C to identify code structure and to solve any problem in a specific series of codes. In procedural programming C variables and functions are declared before use. 10.Dynamic Memory Allocation C provides dynamic memory allocation that means you are free to allocate memory at run time. For example, if you don’t know how much memory is required by objects in your program, you can still run a program in C and assign the memory at the same time. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING BASIC STRUCTURE OF ‘C’ : • C Program can be viewed as group of building blocks called functions. • A function includes one or more statements designed to perform a specific task. • A C program may contain one or more section as shown below : Documentation Section Link Section Definition Section Global Declaration section Main() section { Declaration Part Executable Part } Sub program Section Function1() { Function1 Body } Function2() { Function2 Body } } COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING BASIC STRUCTURE OF ‘C’ : 1. DOCUMENTATION SECTION : This Section consists of set of comment lines giving the name of the programmer, date and the other details about the program. The documentation section helps anyone to get an overview of the program. Comments may appear anywhere within a program. The text between /* And */ appears as a comments in C. Example, /* This is Comment */ 2. LINK SECTION : • This section consist of instructions to be given to the compiler to link functions from the system library such as using the #include directive. • # is a preprocessor directive as the C program provides a lot of inbuilt pre processor directives that are handled by the pre-processor before the compiler starts execution. • In this section we include header file from the respected library files such as stdio.h is one of the header file. • Header files contain function declaration and library file contains function definition. • Header files can be read by human but library file couldn’t. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING BASIC STRUCTURE OF ‘C’ : 3. DEFINITION SECTION : • This section defines all the symbolic constants for example PI=3.14. • By defining symbolic constant one can use those symbolic constant instead of constant value. • Example #define PI 3.14 4. GLOBAL DECLARATION SECTION : This section contains the declaration of variables which are used by more then one function of the program. 5. main() SECTION : • The main function is the entry point in the C program. All C programs begin execution by calling the main () function. When the main function returns, your program terminates execution and control passes back to the operating system. • Every C program must have one and only one main function. • The next line consists of a single curly brace ({ ) which signifies the start of main() function. declaration of variables (int age; ) • The first line of code inside function main () is a declaration of variables. In C, all variables must be declared before they are used. • Closing curly brace ( } ) which signifies the end of main () function. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING BASIC STRUCTURE OF ‘C’ : 6. SUB PROGRAM OR SUB FUNCTION SECTION : They are the code section which are define outside the boundary of main() function, this function can be called from any point or anywhere from the program. CHARACTER SET : • As every language contains a set of characters used to construct words, statements, etc., C language also has a set of characters that include alphabets, digits, and special symbols. C language supports a total of 256 characters. • Every C program contains statements. These statements are constructed using words and these words are constructed using characters from C character set. C language character set contains the following set of characters. 1. Alphabets: C language supports all the alphabets from the English language. Lower and upper case letters together support 52 alphabets. lower case letters - a to z and UPPER CASE LETTERS - A to Z 2. Digits: C language supports 10 digits which are used to construct numerical values in C language. Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. 3. Special Symbols: C language supports a rich set of special symbols that include symbols to perform mathematical operations, to check conditions, white spaces, backspaces, and other special symbols. Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ and many others. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING CHARACTER SET : TRI-GRAPH CHARACTERS : • • • • Some keyboard do not support all the character of C. A tri graph sequence is a combination of three standard characters that will be available in all keywords. With the help of tri graph sequence, we use the characters that are not available in all keywords. Tri graph Sequence consist of two ‘?’ character followed by some special character. Tri graph Sequence Equivalent Character Meaning ??= # Number Sign ??( [ Left Square Bracket ??) ] Right Square Bracket ??< { Left curled bracket ??< } Right Curled bracket ??! | Vertical Bar(Pipe) ??/ \ Back Slash ??’ ^ Caret ??- ~ Tile COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING C TOKEN : Tokens are the smallest elements of a program, which are meaningful to the compiler. The following are the types of tokens: Keywords, Identifiers, Constant, Strings, Operators, etc. 1. KEYWORDS : Keywords are predefined, reserved words in C and each of which is associated with specific features. These words help us to use the functionality of C language. They have special meaning to the compilers. There is total 32 keywords in C. auto double int struct break else long switch case enum register typedef char extern return union continue for signed void do if static while default goto sizeof volatile const float short unsigned COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING C TOKEN : 2. IDENTIFIER : Each program element in C programming is known as an identifier. They are used for the naming of variables, functions, array etc. These are user-defined names that consist of alphabets, numbers, underscore ‘_’. The identifier’s name should not be the same as other identifiers or the same as keywords. Keywords are not used as identifiers. Rules for naming C identifiers • It must begin with alphabets or underscore. • Only alphabets, numbers, underscore can be used, no other special characters, punctuations are allowed. • It must not contain white-space(s). • It should not be a keyword and up to 31 characters long. 3. CONSTANTS : It is represent a value that can be stored in the memory and can not be changed during the execution of the program. There are two types of constants. 1. Numeric Constants : It is used in Mathematical digits and created with the help of 0 to 9. There are two types of numeric constants. 1. Integer Constants : Used only 10 digits (0 to 9), never use fractional numbers and dot(.) operator. 2. Real Constants : also known as floating point numbers, and shows the fractional numbers with dot(.) operator. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING C TOKEN : 3. CONSTANTS : 2. Character Constants : It is an alphabet or group of alphabets, as ‘S’, “Computer”, there are two types of character constants, Single Constant and String Constants. 1. Single Character Constants : Individual Alphabets and represents in single quotes (‘ ’). 2. String Character Constants : Group of characters that specifies some meaning, represented in double quotes (“ ”). 4. STRING : • The strings in C always get represented in the form of an array of characters. We have a ‘\0′ null character at the end of any string- thus, this null character represents the end of that string. • In C language, double quotes enclose the strings, while the characters get enclosed typically within various single characters. • The number of characters in a string decides the size of that string. • There are different ways in which we can describe a string: • char x[8] = “computer’; // Here, the compiler allocates a total of 9 bytes to the ‘x’ array. • char x[] = ‘computer’; // Here, the compiler performs allocation of memory during the run time. • char x[8] = {‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’\0′}; // Here, we are representing the string in the form of the individual characters that it has. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING C TOKEN : 5. SPECIAL CHARACTERS : All of them hold a special meaning that we cannot use for any other purpose. 1. () Simple brackets – We use these during function calling as well as during function declaration. For instance, the function printf() is pre-defined. 2. [ ] Square brackets – The closing and opening brackets represent the multidimensional and single subscripts. 3. (,) Comma – We use the comma for separating more than one statement, separating the function parameters used in a function call, and for separating various variables when we print the value of multiple variables using only one printf statement. 4. { } Curly braces – We use it during the closing as well as opening of any code. We also use the curly braces during the closing and opening of the loops. 5. (*) Asterisk – We use this symbol for representing the pointers and we also use this symbol as a type of operator for multiplication. 6. (#) Hash/preprocessor – We use it for the preprocessor directive. This processor basically denotes that the user is utilizing the header file. 7. (.) Period – We use the period symbol for accessing a member of a union or a structure. 8. (~) Tilde – We use this special character in the form of a destructor for free memory. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING C TOKEN : 6. OPERATORS : The operators in C are the special symbols that we use for performing various functions. Operands are those data items on which we apply the operators. We apply the operators in between various operands. On the basis of the total number of operands, here is how we classify the operators: 1. Unary Operator 2. Binary Operator 3. Ternary Operator 1. Unary Operator The unary operator in c is a type of operator that gets applied to one single operand, for example: (–) decrement operator, (++) increment operator, (type)*, sizeof, etc. 2. Binary Operator Binary operators are the types of operators that we apply between two of the operands. Here is a list of all the binary operators that we have in the C language: 1. Relational Operators 2. Arithmetic Operators 3. Logical Operators 4. Conditional Operators 5. Bitwise Operators 6. Assignment Operator COMPUTER/IT DEPARTMENT 7. Special Operator CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING DATA TYPE : • Data types is useful in programming language to instruct compiler that which kind of value can be contained in the variable. • Whatever it can be integer, floating point or character. • Each type of value required different amount of memory space. • Data type is a container which is used to store value with it is range. • Data type classified into three group, 1. Primary/Basic/Fundamental Data type 2. Derived Data type 3. User defined Data type 1. PRIMARY/BASIC/FUNDAMENTAL DATA TYPE Basic data types are used to store values in integer and decimal forms. It supports both signed and unsigned literals. There are four basic data types, in both signed and unsigned forms: 1. Integer 2. Floating point 3. Character 4. Void The memory size of these data types can change depending on the operating system (32-bit or 64bit). Here is the table showing the data types commonly used in C programming with their storage size and value range, according to the 32-bit architecture. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING DATA TYPE : 1. PRIMARY/BASIC/FUNDAMENTAL DATA TYPE 1. INTEGER DATA TYPE • • • 1. 2. This category of data type represents numeric value without any decimal point. It is used to represent whole number. There are two types Signed : By default data type value as it contains both positive and negative values. Unsigned : contains only positive values. Data Type Size Range Format Specifier Short integer/Signed Short Integer 1 Byte (8 bits) -128 to 127 %hd Integer/signed integer 2 Byte (16 bits) -32768 to 32767 %d Long integer/ signed long integer 4 Byte (32 bits) -2147483648 to 2147483647 %ld Unsigned short Integer 1 Byte (8 bits) 0 to 255 %hu Unsigned integer 2 Byte (16 bits) 0 to 65535 %u 4 Bytes (32 bits) 0 to 4294967295 %ld Unsigned long integer COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING DATA TYPE : 1. PRIMARY/BASIC/FUNDAMENTAL DATA TYPE 2. FLOATING POINT DATA TYPE The floating-point data type allows a user to store decimal values in a variable, there are three types as below, 1. Float (%f) : Floating point numbers are stored in 32 bits with 6 digit of precision and the range will be from 3.4E-38 to 3.4E+32. 2. Double (%f) : This numbers are stored in 64 bits with 14 digits of precision and the range will be from 1.7E308 to 1.7E+308. 3. Long Double (%lf) : This numbers are stored in 80 bits and the range will be from 3.4E-4932 to 1.1E+4932. 3. CHARACTER DATA TYPE A single character can be defined as a character(char) type data, and the size of this data type is 8 bits (1 Byte) and range is between -128 to 127 and for unsigned characters the size is 8 bits (1 Byte) and the range is 0 to 255. 4. VOID • Void has not values. • The type of a function is said to be void when it does not return any value to the calling function. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING DATA TYPE : 2. DERIVED DATA TYPE : Derived data types allow you to combine the basic data types and store multiple values in a single variable. Derived data types are defined by the user itself, which means that you can aggregate as many elements of similar data types as required. There are four types of derived data types: 1. Array : An array is a collection of similar data-type elements stored in a contiguous memory location. 2. Pointer : Pointer is a variable used to store the address of another variable. 3. Structure : a structure is a user-defined data type, which is a group of items used to store the values of similar or different data types. 4. Union : Union is also a collection of elements with similar or different data types, but the memory location is the same for all the elements. 3. USER DEFINED DATA TYPE : The User-Defined Data Type is a typical data type that we can derive out of any existing data type in a program. We can utilise them for extending those built-in types that are already available in a program, and then you can create various customized data types of your own. Below are some user defined data types. 1. ENUMERATED DATA TYPE • It is used to define more than one integer symbolic constants. Syntax : enum identifier(value1, value2 ….. valueN); • It allow us to create our own symbolic names for a list of related constants. • If we do not explicitly assign values to enum names, the compiler assign value starting from 0 by default. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING DATA TYPE : 3. USER DEFINED DATA TYPE : 2. TYPEDEF DATA TYPE : • Used to create a new name for an existing data type. Syntax : typedef existing_type new_datatype; COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING TYPE CASTING : • Type casting is to convert value from one data type to another data type. • There are two types of type casting 1. IMPLICIT TYPE CASTING : • C Compiler performs automatic type casting which is known a implicit type casting. • When C expression is evaluated, the resulting value has a particular data type, if all the variable in the expression are the same type, then the resulting type is same. • But if variables in the expression have different type then variable with the largest size data type is applied to the other variables in the expression from smallest to the largest data types with respect to size as per following sequence. Char integer long float double • For example, expression containing integer and float evaluates to float or and expression contains char and integer, It evaluates integer. 2. EXPLICIT TYPE CASTING : • When we want to convert expression or sub-expression from one type into another type then write data type within parentheses to indicate that the casting is exlicit. • Syntax : (data type) expression; • In the above format value in the expression is to be converted into the data type given in the round brackets. COMPUTER/IT DEPARTMENT CHAPTER – 2 BASICS OF ‘C’ PROGRAMMING TYPE CASTING : IMPLICIT TYPE CASTING/TYPE CONVERSION EXPLICIT TYPE CASTING/TYPE CASTING It is performed by Compiler It is performed by User It is performed automatically when value of one type is assigned to a variable or while evaluating expression that contains variable of different type. It is performed explicitly by user when user wants to convert variable of one type to another type. #include<stdio.h> Void main() { Int n; Float k,sum; Printf(“Enter Two Numbers : ”); Scanf(“%d %f ”, &n,&k); Sum = n+k; Printf(“Sum = %f”,sum); } Output : Enter two number : 4 5.6 Sum : 9.6 #include<stdio.h> Void main() { Int a,b,total; Float avg; Printf(“Enter Two Numbers : ”); Scanf(“%d %d ”, &a,&b); total = a+b; Avg = (float) total/2; Printf(“average = %f”,avg); } Output : Enter two number : 4 5 Sum : 4.500000 COMPUTER/IT DEPARTMENT