Introduction to C Programming Language PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides an introduction to C programming, covering its history, types, features and structure. It explains how to communicate with computers using a programming language like C, and highlights its use in various applications.
Full Transcript
Unit 2 INTRODUCTION TO C Programming Language: As we know, to communicate with a person, we need a specific language, similarly to communicate with computers, programmers also need a language is called Programming language. programming language is a computer language that is...
Unit 2 INTRODUCTION TO C Programming Language: As we know, to communicate with a person, we need a specific language, similarly to communicate with computers, programmers also need a language is called Programming language. programming language is a computer language that is used by programmers (developers) to communicate with computers. It is a set of instructions written in any specific language ( C, C++, Java, Python) to perform a specific task. programming language is mainly used to develop desktop applications, websites, and mobile applications. INTRODUCTION TO C Types of programming language: 1. Low-level programming language(machine- dependent, eg: Machine Language, Assembly Language) 2. High-level programming language(user- friendly,eg: Python, Java, JavaScript, PHP, C#, C++, Objective C) 3. Middle-level programming language(Example: C, C++) INTRODUCTION TO C HISTORY OF C C is a high level programming language. C language is derived from two languages BCPL & B in 1960 at Cambridge University. C language is developed at Bell Laboratories in 1972. Dennis Ritchie invented C language. C Language mainly evolved from ALGOL, BCPL and B. It inherits many features of previous languages such as B and BCPL. It was developed to overcome the problems of previous languages such as B, BCPL, etc. C is developed for programming in OS called UNIX. INTRODUCTION TO C FEATURES OF “C” LANGUAGE C is a Structured Programming Language and powerful language. C is a Mother language C is a versatile Language (i.e.,) it has features of both Low Level Languages and High Level Languages. It is used in system programming. Compilers, packages, Operating System are written using C. C is a highly portable language. Source Program written in one computer can be compiled, executed and run on another computer with less modification. Users can develop program quickly with few mistakes. INTRODUCTION TO C It increases the readability of Program. Program can be modified without affecting the other parts of a program. C is a Case Sensitive Language. It differentiates both Upper Case and Lower Case separately. Every statement in C ends with semicolon. Programmers can write additional functions of their own. C language has a C Compiler. C language has the ability to extend itself. C is also a free form language, because each group of statements can be placed together on one line. C language is used for developing software packages, system software, database systems, graphics packages, spread sheets, CAD/CAM applications, word processors, office automation, scientific and engineering applications. INTRODUCTION TO C INTRODUCTION TO C Simple: C is a simple language in the sense that it provides a structured approach (to break the problem into parts), the rich set of library functions, data types, etc. Machine Independent or Portable: Unlike assembly language, c programs can be executed on different machines with some machine specific changes. Therefore, C is a machine independent language. Mid-level programming language: Although, C is intended to do low-level programming. It is used to develop system applications such as kernel, driver, etc. It also supports the features of a high- level language. That is why it is known as mid-level language. INTRODUCTION TO C Structured programming language: C is a structured programming language in the sense that we can break the program into parts using functions. So, it is easy to understand and modify. Functions also provide code reusability. Rich Library: C provides a lot of inbuilt functions that make the development fast. Memory Management: It supports the feature of dynamic memory allocation. In C language, we can free the allocated memory at any time by calling the free() function. INTRODUCTION TO C Speed: The compilation and execution time of C language is fast since there are lesser inbuilt functions and hence the lesser overhead. Pointer: C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can use pointers for memory, structures, functions, array, etc. Recursion: In C, we can call the function within the function. It provides code reusability for every function. Recursion enables us to use the approach of backtracking. Extensible: C language is extensible because it can easily adopt new features. INTRODUCTION TO C Where is C used? Key Applications: ‘C’ language is widely used in embedded systems. It is used for developing system applications. It is widely used for developing desktop applications. Most of the applications by Adobe are developed using ‘C’ programming language. It is used for developing browsers and their extensions. Google’s Chromium is built using ‘C’ programming language. It is used to develop databases. MySQL is the most popular database software which is built using ‘C’. It is used in developing an operating system. Operating systems such as Apple’s OS X, Microsoft’s Windows, and Symbian are developed using ‘C’ language. It is used for developing desktop as well as mobile phone’s operating system. It is used for compiler production. It is widely used in IOT applications. INTRODUCTION TO C Why learn C Language? As we studied earlier, ‘C’ is a base language for many programming languages. So, learning ‘C’ as the main language will play an important role while studying other programming languages. It shares the same concepts such as data types, operators, control statements and many more. ‘C’ can be used widely in various applications. It is a simple language and provides faster execution. There are many jobs available for a ‘C’ developer in the current market. ‘C’ is a structured programming language in which program is divided into various modules. Each module can be written separately and together it forms a single ‘C’ program. This structure makes it easy for testing, maintaining and debugging processes. ‘C’ contains 32 keywords, various data types and a set of powerful built-in functions that make programming very efficient. Another feature of ‘C’ programming is that it can extend itself. A ‘C’ program contains various functions which are part of a library. We can add our features and functions to the library. We can access and use these functions anytime we want in our program. This feature makes it simple while working with complex programming. Various compilers are available in the market that can be used for executing programs written in this language. It is a highly portable language which means programs written in ‘C’ language can run on other machines. This feature is essential if we wish to use or execute the code on another computer. STRUCTURE OF C PROGRAM The structure of a C program means the specific structure to start the programming in the C language. Without a proper structure, it becomes difficult to analyze the problem and the solution. It also gives us a reference to write more complex programs. Sometimes, when we begin with a new programming language, we are not aware about the basic structure of a program. The structure of a program usually get shuffled and the chance of omission of error rises. The structure of a language gives us a basic idea of the order of the sections in a program. We get to know when and where to use a particular statement, variable, function, curly braces, parentheses, etc. Thus, the structure helps us analyze the format to write a program for the least errors. It gives better clarity and the concept of a program. STRUCTURE OF C PROGRAM STRUCTURE OF C PROGRAM STRUCTURE OF C PROGRAM Documentation Section Header File Section / Link Section/Preprocessor Definition Section Global (Variable) Declaration Section main() { Declaration(local variable) part Executable part } sub program section(User defined functions) function 1 function 2 ‘ ‘ Function n STRUCTURE OF C PROGRAM Documentation Section Documentation section consists of set of command lines. It is included in the first line of a C program. It consists of comments. It includes the statement specified at the beginning of a program, such as a program's name, date, description, and title. There are two types of comments. They are Single line Comments and Multi line comments. Comments are used to give a meaningful name to a C Program. Single line comments are specified with two backslash //. Eg: //name of a program Multi line comments are specified by a backslash ( / ) followed by an asterisk ( * ) symbol and ended with asterisk symbol ( * ) followed by Backslash ( / ). Eg: Note: 1. There is no space between (*) and slash (/) 2. Every (end) STRUCTURE OF C PROGRAM Link section/Header File section (#include Directive(or)preprocessor) In this section we can declare the header files of the program. Header file consists of predefined function(built-in,readymade) functions) definitions for frequently used functions. It informs the system to link the header files to the system libraries. Some of the functions in C programs was already and written, executed and stored in the header files. Standard header files are provided with each compiler and cover a range of areas like string handling, mathematical functions, data conversion, printing, and reading of variables. Whenever we need to use the particular function, we should simply mention the name in the link section. Link section provides instructions to compiler to link functions from system library. Eg: stdio.h header file enables the program to perform basic input and output operations and allows the program to accept input from the keyboard and display output on the screen. STRUCTURE OF C PROGRAM #include #include # include. Note: 1. Lines that start with the # sign are preprocessor directives 2. The angled-bracket pair indicates that the specified library file is the standard library directory. For example, to use the printf() function in a program, which is used to display anything on the screen, the line #include is required because the header file stdio.h contains the printf() function. All header files will have an extension.h STRUCTURE OF C PROGRAM Definition Section It is used to define symbolic constants. The define section comprises of different constants declared using the define keyword. It is given by: #define a = 2 Global declaration section Used to declare functions, variables or symbolic constants globally. Two types of declaration are allowed in C Language. They are (1) Static variable and (2) Global variable. If a variable is specified within main function then it is local variable. Local variable cannot be used outside the main function. If a variable is specified outside the main function then it is global variable. Global variable can be used inside and outside or anywhere within the program. Variables must be declared before being used in a C program. clrscr() statement is used after variable declaration and before the beginning of control statements. Declaration helps to define a variable and use it in a Program. Sub program contains user defined function. Eg: int a = 5; STRUCTURE OF C PROGRAM main( ) section The execution of C program starts from the main function. The instructions contained within this function's definition will always be the first ones to be executed in any C program. The word main is followed in the code by a pair of parentheses () These parentheses may enclose a list of parameters within them. Every C program must have a main function. It contains two parts. They are declaration part and executable part. Declaration part and executable part must appear between opening ‘ { ' and closing braces ‘ }’. Opening brace specifies the beginning of C program and close brace specifies the logical end of C program. What is contained within these braces is what the function does when it is executed. The main function is declared as: main() The void main() specifies that the program will not return any value. The int main() specifies that the program can return integer type data. STRUCTURE OF C PROGRAM Format: data type function_name (parameters) { variable; C statement; } Eg: void main () { Statement; Statement; …………..; …………..; } STRUCTURE OF C PROGRAM Declaration part Declaration part is used to declare variables. Every variable must be declared before using it in C program. Every variable are specified with their data type followed by a name. If there are more variables of same data type then they must be separated by commas. local declarations, statements, and expressions. Local declarations: The variable that is declared inside a given function or block refers to as local declarations. main() { int i = 2; i++; } STRUCTURE OF C PROGRAM Statements: The statements refers to if, else, while, do, for, etc. used in a program within the main function. Expressions: An expression is a type of formula where operands are linked with each other by the use of operators. It is given by: a - b; a +b; STRUCTURE OF C PROGRAM Execution part Execution part contains program statements. There may or may not be a declaration part but there must be an execution part. It includes input and output statements. Sub program section Sub program section consists of all user-defined functions. The user defined functions specified the functions specified as per the requirements of the user. For example, color(), sum(), division(), etc. It is called from the main function. It is placed before or after the main function. But generally placed after the main function. STRUCTURE OF C PROGRAM Return function is generally the last section of a code. But, it is not necessary to include. It is used when we want to return a value. The return function returns a value when the return type other than the void is specified with the function. Return type ends the execution of the function. It further returns control to the specified calling function. It is given by:return; Eg:return 0; STRUCTURE OF C PROGRAM Example 1: To find the sum of two numbers given by the user Program: #include int main() { int a, b, sum; printf("Enter two numbers to be added "); scanf("%d %d", &a, &b); // calculating sum sum = a + b; printf("%d + %d = %d", a, b, sum); return 0; // return the integer value in the sum } Output: It is the comment section. Any statement described in it is not considered as a code. It is a part of the description section in a code. The comment line is optional. It can be in a separate line or part of an executable line. #include It is the standard input-output header file. It is a command of the preprocessor section. int main() main() is the first function to be executed in every program. We have used int with the main() in order to return an integer value. {… The curly braces mark the beginning and end of a } function. It is mandatory in all the functions. printf() The printf() prints text on the screen. It is a function for displaying constant or variables data. Here, 'Enter two numbers to be added' is the parameter passed to it. scanf() It reads data from the standard input stream and writes the result into the specified arguments. sum = a + b The addition of the specified two numbers will be passed to the sum parameter in the output. return 0 A program can also run without a return 0 function. It simply states that a program is free from error and can be successfully exited. documentation section #include Header File section void main () main( ) section { int miles = 26; int yards; Variable Declaration Section float kilometers; kilometers = 1.609 *(miles+yards/1760.0); printf(“\n A marathon is %f kms”,kilometers); } 1 2 3 STRUCTURE OF C PROGRAM STRUCTURE OF C PROGRAM Very important: The C language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Execution or Flow of C Program Execution or Flow of C Program 1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates an expanded source code. 2) Expanded source code is sent to compiler which compiles the code and converts it into assembly code. 3) The assembly code is sent to assembler which assembles the code and converts it into object code. Now a simple.obj file is generated. 4) The object code is sent to linker which links it to the library such as header files. Then it is converted into executable code. A simple.exe file is generated. 5) The executable code is sent to loader which loads it into memory and then it is executed. After execution, output is sent to console. Execution or Flow of C Program First C Program and its Structure: program for printing "Hello World" in C language. #include int main() { printf("Hello World"); return 0; } Output: Hello, World C CHARACTER SET Characters are used in forming either words or numbers or even expressions in C programming. Characters combine to form variables. Characters in C are grouped into Letters, Digits, Special characters and White spaces. Compiler generally ignores white space when it is not a part of string constant. White Space may be used to separate words, but not used between characters of keywords or identifiers. The character set in C Language can be grouped into the following categories. 1. Letters 2. Digits 3. Special Characters 4. White Spaces C CHARACTER SET Letters (Alphabets):In C programming, we can use both uppercase and lowercase letters of English language. Digits: We can use decimal digits from 0 to 9. Letters Letters Digits Upper Case A Lower Case a 0 to 9 to Z to z C CHARACTER SET White Space Characters: It is used together with input and output statements. It has no meaning but it has the control to decide the way an input has to be displayed. 1. Blank Space \b 2. Horizontal Tab \t 3. Carriage Return \r 4. New line \n 5. Form Feed \f 6. Vertical tab \v C CHARACTER SET Special Characters: &.Ampersand #.Number Sign '.Apostrophe <.Opening Angle (Less than sign) *.Asterisk..Period ( Dot ) @ At symbol %.Percentage Sign \.Backslash +.Plus Sign ^.Caret ?.Question Mark >.Closing Angle (Greater ".Quotation Marks than sign) :.Colon }.Right Flower Brace ,.Comma ).Right Parenthesis $.Dollar Sign ].Right Bracket.= Equal to ;.Semicolon !.Exclamation Mark /.Slash (.Left Parenthesis ~.Tilde [.Left Bracket _.Underscore {.Left Flower Brace |.Vertical Bar TOKENS TOKENS Tokens in C is the most important element to be used in creating a program in C. For `example, we cannot create a sentence without using words; similarly, we cannot create a program in C without using tokens in C. Therefore, we can say that tokens in C is the building block or the basic component for creating a program in C language. Among the group of text, individual word, punctuation marks are called Tokens. It is a smallest individual unit in a C program. C has 6 types of Tokens. They are Keyword Identifier Special symbols Constant String Operators. Keywords Keywords 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. ANSI C supports 32 keywords. All keywords have fixed meanings and you can not change its meanings. Keywords The following are the Keyword set of C language. 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 Identifiers Identifiers Identifier is a name given to program elements such as variables, functions, procedure, arrays and soon. These are user defined names. Identifier consists of sequence of letters, digits or combination of both. First character must be an Alphabet or Underscore. Both uppercase and lowercase letters are permitted to make the identifier but generally lowercase letters are used to make the variable. Identifiers cannot be used as keywords. Identifiers Rules for Identifier First character must be an Alphabet or Underscore( _ ) and then it can be followed by any of the character, digit, or underscore. It should not begin with any numerical digit. Special characters and embedded commas are not allowed. he length of the identifiers should not be more than 31 characters. First 31 characters are given high priority or preference. Keyword cannot be used as Identifier. There should not be any white space. Both uppercase and lowercase letters are permitted. The underscore character is also permitted in identifiers. Identifiers should be written in such a way that it is meaningful, short, and easy to read. CONSTANT CONSTANT: 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. Constant is a fixed value does not change during the execution of a program. It remains same throughout the program. Its value cannot be altered or modified in a program. A variable is declared by the Keyword const. Eg: const int a,b,c; CONSTANT Constant is classified into three main types. They are described as follows. 1. Numeric Constant 2. Character Constant and 3. Symbolic Constant. CONSTANT NUMERIC CONSTANT: Numeric Constant is further classified into two main types. They are (i) Integer Constants and (ii) Real Constants Integer Constants Integer constant consist of sequence of digit without decimal point. It is normally a whole number. Eg: Integer constant 10, 11, 34, etc. Real Constants Real Constants are otherwise known as Floating Point Constants. Real Constant consists of decimal number, exponent or combination of both. Real constant consist of two forms. They are Fractional form and Exponential form. Eg: Floating-point constant 45.6, 67.8, 11.2, etc. Octal constant 011, 088, 022, etc. Hexadecimal constant 0x1a, 0x4b, 0x6b, etc. CONSTANT CHARACTER CONSTANT Character Constant is also known as single character constant. The Character constant is mainly classified into three types. They are i. Single character constants Single character constant is also known as character constant. It contains single character or number enclosed within a pair of single quotes. If number specified within single quotes it is considered as character constant. It cannot be used with arithmetic expression. Strings are stored in memory as ASCII codes of characters. Each character is stored in one byte or length of single character constant is one. E.g:- Valid ‘A’ ‘m’ ‘ ’ ‘3’ Invalid “W” “ma” CONSTANT Chara M Y ” a g e i s cter # ASCII 77 121 34 97 103 101 35 105 115 Code Chara % 2 blank ( t w o ) @ cter ASCII 37 50 32 40 116 119 41 41 64 Code CONSTANT ii. String constant String constant consist of sequence of characters enclosed with double quotes. The character may be letters, numbers, special characters and blank space. The end of string is marked with NULL character ‘\0’. It uses two bytes. One for ASCII code and other for NULL character. Rules for String constant : String constant must be a single alphabet, special character or sequence of alphabets or digits enclosed in double quotes. Every string constant ends with NULL character. It is automatically assigned. E.g:- Valid “Manakula Vinayagar institute of Technology” “java", "c++", ".net", etc. Invalid ‘school’ CONSTANT iii. Backslash Character constant. Backslash Character constant starts with backslash ‘\’. It may consist of single or two characters. Back slash character constant are also knownMEANING CONSTANT as Escape sequences. CONSTANT MEANING \a Audible alert. \r Carriage return. \b Back space. \t Horizontal tab. \f Form feed. \v Vertical tab. \n New line. \\ Back slash. \’ Single quote \’’ Double quote. \? Question mark. \0 Null. CONSTANT SYMBOLIC CONSTANT It represent numeric/character string constant. It is defined as follows. #define. Here scname stands for Symbolic Constant name and sctext stands for Symbolic Constant text. scname is usually written in capital letters. Example :-#define PI 3.14 const int pi=3.14 TOKENS Types of constants in C constant Example Integer constant 10, 11, 34, etc. Floating-point 45.6, 67.8, 11.2, etc. constant Octal constant 011, 088, 022, etc. Hexadecimal 0x1a, 0x4b, 0x6b, constant etc. Character 'a', 'b', 'c', etc. constant String constant "java", "c++", ".net", etc. VARIABLE VARIABLE: 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. Let's see the syntax to declare a variable: data type variable_list; (or) datatype v1, v2, v3, ……….. vn where v1, v2, v3 are variable names. Variables are separated by commas. A declaration statement must end with a semicolon. example : int a; float b; char c; int sum; double average; a, b, c are variables. The int, float, char are the data types. VARIABLE VARIABLE ASSIGNMENT: It is another format of variable declaration. The general form is data-type variable name [=value]; Here data type refers to the type of value used in the C program. Variable name is a valid name. Square brackets [ ] denotes that the value may or may not be used or specified within the program. Eg: int a; (or) int a=10; Here if the value of a is assigned 10 the value remains the same throughout the program. If no value is specified then the value keeps on changing. VARIABLE Rules for defining variables: A variable can have alphabets, digits, and underscore. A variable name can start with the alphabet, and underscore only. It can't start with a digit. No whitespace is allowed within the variable name. A variable name must not be any reserved word or keyword, e.g. int, float, etc. VARIABLE SIMPLE VARIABLE ASSIGNMENT: To assign a single value to a variable ‘=’ equality operator is used. The syntax is variable-name = value; Eg: X=10; y=30; COMPOUND VARIABLE ASSIGNMENT: variable-name = expression This type of variable declaration can be used together with combination of characters, numbers or an expression. Here ‘=’ equality operator is used. Eg: Y=x+5; Z=((x+1)(y-2)*x) VARIABLE Declaring a variable as constant: Variable is declared as constant by using the keyword or qualifier ‘const’ before the variable name. This can be done at the time of initialization. Eg: Const int class_size = 40; Volatile Variable: A variable is volatile if the value gets changed at any time by some of the external sources. Eg: volatile int num; when we declare a variable as volatile the compiler will examine the value of the variable each time it is encountered to see if an external factor has changed the value. VARIABLE Local Variable: A variable that is declared inside the function or block is called a local variable. It must be declared at the start of the block. void function1() { int x=10;//local variable } You must have to initialize the local variable before it is used. VARIABLE Global Variable: A variable that is declared outside the function or block is called a global variable. Any function can change the value of the global variable. It is available to all the functions. It must be declared at the start of the block. int value=20;//global variable void function1() { int x=10;//local variable } Static Variable: A variable that is declared with the static keyword is called static variable. It retains its value between multiple function calls. void function1(){ int x=10;//local variable static int y=10;//static variable x=x+1; y=y+1; printf("%d,%d",x,y); } If you call this function many times, the local variable will print the same value for each function call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in each function call, e.g. 11, 12, 13 and so on. DATA TYPES Data Type is used to define the type of value to be used in a Program. Based on the type of value specified in the program specified amount of required Bytes will be allocated to the variables used in the program. Data types are broadly classified into three main types. They are as follows. Primary data type ( Fundamental Data Types) Derived data type User defined data type. DATA TYPES DATA TYPES Primary Data Type: Integers are represented as int, character are represented as char, floating point value are represented as float, double precision floating point are represented as double and finally void are primary data types. Primary data type offers extended data types. longint, long double are extended data types. The memory size of the basic data types may change according to 32 or 64-bit operating system. Integer Data Type: Integer data type can store only the whole numbers. according Name to 32-bit architecture. C Representation Size( bytes Range Format Delimite ) r Integer int 2 -32768 to 32767 %d Short Integer short int / short 2 -32768 to 32767 %d Long Integer long int / long 4 -2147483648 to %ld 2147483647 Signed Integer signed int 2 -32768 to 32767 %u Unsigned unsigned int 2 0 to 65535 %d Integer Signed Short unsigned short int / 2 -32768 to 32767 %d Integer short Unsigned Short unsigned short int / 2 0 to 65535 %u Integer short Signed Long signed long int / 4 -2147483648 to %ld Integer long 2147483647 Unsigned Long unsigned long int / 4 0 to 4294967295 %lu Integer long Floating Point Data Type: Floating Point data types are also known as Real Numbers. It can store only the real numbers (decimal numbers) with 6 digits precision. Name C Si Range For Represent ze mat ation (b Deli yt mit es er ) Float float 4 3.4 e-38 to %f 3.4 e+38 Double double 8 1.7e-308 to %f 1.7e+308 Long long 10 3.4 e-4932 to %lf Double double 3.4 e+4932 DATA TYPES Character Data Type: Normally a single character is defined as char data type. It is specified by the keyword char. Char data type uses 8 bits for storage. Char may be signed char or unsigned char. Name C Size( Range Format Representatio bytes Delimit n ) er Character char 1 -128 to 127 %c Signed signed char 1 -128 to 127 %c Character Unsigned unsigned char 1 0 to 255 %c Character DATA TYPES Empty Data Type: VOID is the empty data type. This data type is used before main function in a C Language. The word void refers no return data type. It is used before the main function to specify the type of function. If a function is of type void it does not return any value to the calling function. DATA TYPES Declaration of primary datatypes with variable: After taking suitable variable names, they need to be assigned with a data type. This is how the data types are used along with variables Eg: int age; char letter; float height, width; Derived data type: Data types that are derived from fundamental data types are called derived data types. Derived data types do not create new data types. Instead, they add some functionality to the existing data types. Derived data types are derived from the primitive data types by adding some extra relationships with the various elements of the primary data types. The derived data type can be used to represent Data a single value or multiple values. Description Types Arrays Arrays are sequences of data items having homogeneous values. They have adjacent memory locations to store values. Reference Function pointers allow referencing functions with a s particular signature. Pointers These are powerful C features which are used to access the memory and deal with their addresses. DATA TYPES Array: It’s the collection of homogeneous data types that are stored in contiguous memory cells and locations. Example: int a It has 7 memory cells to store the 7 data elements as a, a, a, a, a, a and a. Here, above integer array is derived from the basic data type ‘int’. DATA TYPES Structure: It’s the collection of non- homogeneous data types. It is very popular as it stores all the properties of an element. Example: struct product { char name; int pnum; char consumer; int cnum; } Above example is the collection of basic data types like char and int. DATA TYPES Union: This data type is very similar to the structure as this one too stores non- homogeneous data types. Example: union product { char name; int pnum; char consumer; int cnum; } DATA TYPES pointers: A pointer is a special type of variable used to hold the address of another variable. Functions: A function is a self- contained block of one or more statements with a name. DATA TYPES difference between structure and union in C? They are different in terms of storage. In structure, each member has its own memory location, whereas all the members of a union share the same memory locations. DATA TYPES User Defined Data types: Using user-defined data types, the programmer can invent his/her own data types in C programming. It does not necessary to use basic data types to create user-defined data types in C. Example for User Defined Data Types in C: typedef (type definition), enum (enumerated data type) Data type and variable declaration in c #include int main() { int a = 4000; // positive integer data type float b = 5.2324; // float data type char c = 'Z'; // char data type long d = 41657; // long positive integer data type long e = -21556; // long -ve integer data type int f = -185; // -ve integer data type short g = 130; // short +ve integer data type short h = -130; // short -ve integer data type double i = 4.1234567890; // double float data type float j = -3.55; // float data type } DATA TYPES The storage representation and machine instructions differ from machine to machine. sizeof operator can use to get the exact size of a type or a variable on a particular platform. DATA TYPES Eg: #include #include int main() { printf("Storage size for int is: %d \n", sizeof(int)); printf("Storage size for char is: %d \n", sizeof(char)); return 0; } OPERATORS OPERATORS: Operator is a Symbol that tells or instructs the Compiler to perform certain Mathematical or Logical manipulations (Calculations). Operators are used in a program to work on data and variables. Operators in general form a part of Mathematical or Logical expression. Operators are generally classified into different types. They are described one below another as follows. 1.Arithmetic Operators 2.Relational Operators 3.Logical Operators 4.Assignment Operators 5.Conditional Operators 6.Special Operators 7.Bitwise operators 8.Increment and decrement operators 9.Unary operators 10.Equality operators ARITHMETIC OPERATORS: Arithmetic operators are used to perform Arithmetic operations. They form a part of program. Programs can be written with or without operators. But calculations are performed only using operators. Operators act along Operand to produce result. eg:Assume variable A holds 10 and variable B holds 20 Operator Meaning Details + Addition Performs addition on A + B = 30 integer numbers, floating point numbers. The variable name which is used is the operand and the symbol is operator. - Subtraction Subtracts one A − B = -10 number from another. * Multiplication Used to perform A * B = 200 multiplication / Division It produces the B/A=2 Quotient value as OPERATORS Examples of arithmetic operators are x+y x-y x*y x/y x %y Here x, y are known as operands. The modulus operator is a special operator in C language that evaluates the remainder of the OPERATORS #include void main() { int i=3,j=7,k; k=i+j; printf("sum of two numbers is %d\n", k); } Program Output: #include int main() { int a, b, add, sub, mul, div, rem; printf("Enter a, b values : "); scanf("%d%d",&a,&b); // Reading two values add=a+b; // Addition Operator sub=a-b; // Subtraction Operator mul=a*b; // Multiplication Operator div=a/b; // Division Operator rem=a%b; // Remainder (Modulo) Operator printf("Result of addition is=%d\n", add); printf("Result of subtraction=%d\n", sub); printf("Result of multiplication is=%d\n", mul); printf("Result of division is=%d\n", div); printf("Result of remainder=%d\n",rem); return 0; } The binary + and - operators have the same precedence, which is lower than the precedence of *, / and %, which is in turn lower than unary + and -. Arithmetic operators associate left to right. OPERATORS RELATIONAL OPERATOR: Relational Operators are used to compare two same quantities. There are six relational operators. They are mentioned one below another as follows. Operator Meaning Operator Meaning < is less than >= is greater than or equal to is greater than != is not equal to OPERATORS The general form is: (exp1 relational operator exp2) where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. Given below is a list of examples of relational expressions and evaluated values. 6.5 0 FALSE 10 < 7 + 5 TRUE Relational expressions are used in decision making statements of C language such as if, while and for statements to decide the course of action of a running program. Assume variable A holds 10 and variable B holds 20 then Operator Description Example == Checks if the values of two (A == B) is not true. operands are equal or not. If yes, then the condition becomes true. != Checks if the values of two (A != B) is true. operands are equal or not. If the values are not equal, then the condition becomes true. > Checks if the value of left operand (A > B) is not true. is greater than the value of right operand. If yes, then the condition becomes true. < Checks if the value of left operand (A < B) is true. is less than the value of right operand. If yes, then the condition becomes true. >= Checks if the value of left operand (A >= B) is not true. is greater than or equal to the value of right operand. If yes, then the condition becomes true. = value of a is %d", a>=b); printf("\n The == value of a is %d", a==b); printf("\n The != value of a is %d", a!=b); } The relational operators are > >= < b && x = = 10 The expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10. Truth table of the Logical AND (&&) operator: A B A && B 1 1 1 1 0 0 0 1 0 0 0 0 Eg program1: #include #include int main () { // declare variable int n = 20; // use Logical AND (&&) operator to check the condition printf (" %d \n", (n == 20 && n >= 8)); // condition is true, therefore it returns 1 printf (" %d \n", (n >= 1 && n >= 20)); printf (" %d \n", (n == 10 && n >= 0)); printf (" %d \n", (n >= 20 && n = 13 && age = y && x >= z ) { printf (" %d is the largest number of all. ", x); } else if ( y >= x && y >= z) { printf (" %d is the largest number of all. ", y); } else { printf ( " %d is the largest number of all. ", z); } return 0; } Output: Enter the first number: 20 Enter the second number: 10 Enter the third number: 50 50 is the largest number of all Logical OR ( || ): Logical OR is denoted by double pipe characters (||). it is used to check the combinations of more than one conditions. If any of the operand's values is non- zero (true), Logical OR (||) operator returns 1 ("true"), it returns 0 ("false") if all operand's values are 0 (false). Syntax of Logical OR operator: condition1 || condition2 Eg: a < m || a < n It evaluates to true if a is less than either m or n and when a is less than both m and n. Truth table of logical OR operator: C examples of Logical OR (||) operator: #include int main() { int num =10; //printing result with OR (||) operator printf("%d\n",(num==10 || num>=5)); printf("%d\n",(num>=5 || num=5)); printf("%d\n",(num>=20 || num!=10)); return 0; } Output 1 1 1 0 Example 2:Input an integer number and check whether it is divisible by 9 or 7. // Input an integer number and check whether // it is divisible by 9 or 7. #include int main() { int num; //input number printf("Enter an integer number: "); scanf("%d", &num); //check the condition if(num%9==0 || num%7==0) printf("%d is divisible by 9 or 7\n",num); else printf("%d is not divisible by 9 or 7\n",num); return 0; } Output: Enter an integer number: 27 27 is divisible by 9 or 7 Enter an integer number: 49 49 is divisible by 9 or 7 Enter an integer number: 25 25 is not divisible by 9 or 7 OPERATORS Logical NOT ( ! ): It acts upon single value. The logical NOT operator is represented as the '!' symbol, which is used to reverse the result of any given expression or condition. If the value is true result will be false and if the condition is false the result will be true. The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. syntax of the logical NOT operator ! (condition); Eg (!a) truth table of the logical NOT operator: condition !(condition) 1 0 0 1 #include #include int main () { // declare an initialize x variable int x = 5; // display the result generated using the NOT (!) operator printf (" The return value = %d \n", ! (x == 5)); printf (" The return value = %d \n", ! (x != 5)); printf (" The return value = %d \n", ! (x >= 3)); printf (" The return value = %d \n", ! (x < 3)); return 0; } Output: The return value = 0 The return value = 1 The return value = 0 The return value = 1 In the above program, we use the NOT (!) operator to reverse the result of the various expression, such as the condition of the variable x is equal to 5, which is true. Still, the NOT operator reverses the result and returns 0. Similarly, we defined the condition (x!=5), but the logical operator changed its result and returned 1 and so on. Example 2: Program to input a number to perform the logical NOT operator: #include #include int main () { // declare an initialize x variable int x, n; printf (" Enter the number: "); scanf ("%d", &x); n = !x; // use logical not operator to reverse the condition printf (" The result of x: %d", n); // display the result return 0; } Output: Enter the number: 7 The result of x: 0 OPERATORS Example/ Operators Description (x>5)&&(y=10)||(y>=10) It returns true || (logical OR) when at-least one of the condition is true !((x>5)&&(y5) && (y5) && (y>= z &= Assign bitwise AND y = y&x y&=x |= Assign bitwise OR ^= Assign bitwise X - OR z = z^y z^=y CONDITIONAL OPERATORS Conditional Operator is also known as “Ternary operator”. The general form of Conditional Operator is As conditional operator works on three operands, so it is also known as the ternary operator. (exp1)?(exp2):(exp3); OPERATORS In the above syntax, the expression1 is a Boolean condition that can be either true or false value. If the expression1 results into a true value, then the expression2 will execute. If the expression1 returns false value then the expression3 will execute. #include int main() { int age; // variable declaration printf("Enter your age"); scanf("%d",&age); // taking user input for age variable (age>=18)? (printf("eligible for voting")) : (printf("not eligible f or voting")); // conditional operator return 0; } In the above code, we are taking input as the 'age' of the user. After taking input, we have applied the condition by using a conditional operator. In this condition, we are checking the age of the user. If the age of the user is greater than or equal to 18, then the statement1 will execute, i.e., (printf("eligible for voting")) otherwise, statement2 will execute, i.e., (printf("not eligible for voting")). If we provide the age of user below 18, then the output would be: If we provide the age of user above 18, then the output would be: #include int main() { int a=5,b; // variable declaration b=((a==5)?(3):(2)); // conditional operator printf("The value of 'b' variable is : %d",b); return 0; } In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to the 'a' variable. After the declaration, we are assigning value to the 'b' variable by using the conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value otherwise 2. The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is equal to 5. As we know that the behavior of conditional operator and 'if-else' is similar but they have some differences. Let's look at their differences. A conditional operator is a single programming statement, while the 'if-else' statement is a programming block in which statements come under the parenthesis. A conditional operator can also be used for assigning a value to the variable, whereas the 'if-else' statement cannot be used for the assignment purpose. It is not useful for executing the statements when the statements are multiple, whereas the 'if-else' statement proves more suitable when executing multiple statements. The nested ternary operator is more complex and cannot be easily debugged, while the nested 'if-else' statement is easy to read and maintain. OPERATORS SPECIAL OPERATORS Special operators are known as separators or punctuators. Special operators are Ampersand ( & ) Braces ( { } ) Colon ( : ) Ellipsis (…) Asterisk ( * ) Brackets ( [] ) Comma ( , ) Hash ( # ) Parenthesis ( () ) Semicolon ( ; ) Ampersand ( & ): It is also known as addresss operator. It is specified before the identifier name. i.e., variable name. It indicates memory location of the identifier. OPERATORS Asterisk ( * ): Asterisk ( * ) is also known as indirection operator. It is specified before identifier name. It indicates creation of pointer variable. It is also a unary operator. Example : * a where, * is pointer to the variable a. Braces ( { } ): The opening brace ( { ) and closing brace ( } ) specify the start and end of compound statement in a function. Here semicolon ( ; ) is not necessary. Semicolon ( ; ) is used only in structure declaration. Brackets: Brackets [] also referred as array subscript operator. It is used to indicate single and multi dimensional arrays. Eg: int x;float l; OPERATORS Comma Operator ( , ) It is used to link expressions together. It is used together with variables to separate one variable from another. It is used in for loop. It has the lowest precedence among operators Eg: for(n=1,m=10;n Right shift ^ Bit wise x-or Let's look at the truth table of the bitwise operators. X Y X&Y X|Y X^Y 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 Bitwise AND operator: Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0. For example, We have two variables a and b. a =6; b=14; The binary representation of the above two variables are given below : 8421 a = 0110 b = 1110 a&b =0110 When we apply the bitwise AND operation in the above two variables, i.e., a&b, the output would be: Result = 0110.(the value=6) As we can observe from the above result that bits of both the variables are compared one by one. If the bit of both the variables is 1 then the output would be 1, otherwise 0. Let's understand the bitwise AND operator through the program. #include int main() { int a=6, b=14; // variable declarations printf("The output of the Bitwise AND operator a&b i s %d",a&b); return 0; } Output: ( a AND b = 0110 && 1110 = 0110 ) Bitwise OR operator: The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides of the (|) symbol. The result of Bitwise OR operator is 1, If the corresponding bits of two operands are opposite. otherwise 0. We consider two variables, a = 23; b = 10; The binary representation of the above two variables would be: 128 64 32 16 8 4 2 1 a= 0 0 0 1 0 1 1 1 b= 0 0 0 0 1 0 1 0 a|b= 0 0 0 1 1 1 1 1 When we apply the bitwise OR operator in the above two v ariables, i.e., a|b , then the output would be: Result = 0001 1111 As we can observe from the above result that the bits of both the operands are compared one by one; if the value of either bit is 1, then the output would be 1 otherwise 0. Let's understand the bitwise OR operator through a program. #include int main() { int a=23,b=10; // variable declarations printf("The output of the Bitwise OR operator a|b is %d",a|b); return 0; } Output: Bitwise exclusive OR operator: Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0. We consider two variables a and b, a = 12; b = 10; The binary representation of the above two variables would be: a = 0000 1100 b = 0000 1010 When we apply the bitwise exclusive OR operator in the above tw o variables (a^b), then the result would be: Result = 0000 0110 (6) Let's understand the bitwise exclusive OR operator through a program. #include int main() { int a=12,b=10; // variable declarations printf("The output of the Bitwise exclusi ve OR operator a^b is %d",a^b); return 0; } Output: One’s Complement Operator ( ~ ) One’s Complement makes the bits of operand inverted. Here one becomes zero and zero becomes one. Eg: x=7 i.e., x = 0000 0111 One’s complement of x is ( i.e., ~x = 1111 1000 = 248 ) Ans: One’s complement of x is 248 Let's understand the complement operator through a program. #include int main() { int a=8; // variable declarations printf("The output of the Bitwise complem ent operator ~a is %d",~a); return 0; } Output : Bitwise shift operators: Two types of bitwise shift operators exist in C programming. The bitwise shift operators will shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise shift operator is divided into two categories: Left-shift operator Right-shift operator Left shift Operator ( >2); return 0; } Output: Increment and decrement operators: Increment Operator: Increment Operators are the unary operators used to increment or add 1 to the operand value. The Increment operand is denoted by the double plus symbol (++). It has two types, Pre Increment and Post Increment Operators. Pre-increment Operator: The pre-increment operator is used to increase the original value of the operand by 1 before assigning it to the expression. B = ++A; In the above syntax, the value of operand 'A' is increased by 1, and then a new value is assigned to the variable 'B'. Example 1: Program to use the pre-increment operator in C #include #include int main () { // declare integer variables int x, y, z; printf (" Input the value of X: "); scanf (" %d", &x); printf (" Input the value of Y: "); scanf (" %d", &y); printf (" Input the value of Z: "); scanf (" %d", &z); // use pre increment operator to update the value by 1 A=++x; B=++y; C=++z; printf (" \n The updated value of the X: %d ", A); printf (" \n The updated value of the Y: %d ", B); printf (" \n The updated value of the Z: %d ", C); return 0; } Output: Input the value of X: 10 Input the value of Y: 15 Input the value of Z: 20 The updated value of the X: 11 The updated value of the Y: 16 The updated value of the Z: 21 Post increment Operator: The post-increment operator is used to increment the original value of the operand by 1 after assigning it to the expression. Syntax: X = A++; In the above syntax, the value of operand 'A' is assigned to the variable 'X'. After that, the value of variable 'A' is incremented by 1. Program to use the post-increment operator in C #include #include int main () { // declare integer variables int x, y, z, a, b, c; printf (" Input the value of X: "); scanf (" %d", &x); printf (" Input the value of Y: "); scanf (" %d", &y); printf (" Input the value of Z: "); scanf (" %d", &z); // use post-increment operator to update the value by 1 a = x++; b = y++; c = z++; printf (" \n The original value of a: %d", a); printf (" \n The original value of b: %d", b); printf (" \n The original value of c: %d", c); printf (" \n\n The updated value of the X: %d ", x); printf (" \n The updated value of the Y: %d ", y); printf (" \n The updated value of the Z: %d ", z); return 0; } Output: Input the value of X: 10 Input the value of Y: 15 Input the value of Z: 20 The original value of a: 10 The original value of b: 15 The original value of c: 20 The updated value of the X: 11 The updated value of the Y: 16 The updated value of the Z: 21 Decrement Operator: Decrement Operator is the unary operator, which is used to decrease the original value of the operand by 1. The decrement operator is represented as the double minus symbol (--). It has two types, Pre Decrement and Post Decrement operators. Pre Decrement Operator: The Pre Decrement Operator decreases the operand value by 1 before assigning it to the mathematical expression. In other words, the original value of the operand is first decreases, and then a new value is assigned to the other variable. Syntax B = --A; In the above syntax, the value of operand 'A' is decreased by 1, and then a new value is assigned to the variable 'B'. Post decrement Operator: Post decrement operator is used to decrease the original value of the operand by 1 after assigning to the expression. Syntax B = A--; In the above syntax, the value of operand 'A' is assigned to the variable 'B', and then the value of A is decreased by 1. UNARY OPERATORS: Unary operators act on single operand to produce new value. It proceeds with operands. Unary minus denotes subtraction. Subtraction operators require two operands but unary minus require one operand. The operand used with this operator must be a single variable. Types of the Unary Operator: Following are the types of the unary operators in the C programming language. Unary Minus (-) Unary Plus (+) Increment (++) Decrement (--) Logical Negation (!) Address Operator (&) Sizeof() operator Unary Minus (-): The Unary Minus operator is represented using the symbol (-). The unary operator is used to change the sign of any positive value to a negative value. It means it changes the positive number to the negative, and a negative number becomes the positive number using the unary minus operator. Syntax int a = 2; int b = -(a); Unary plus (+): The unary plus operator is represented as the "+" symbol, and it does not change to the operand value. Unary Increment Operator (++): It is the unary increment operator, which is denoted by the "++" symbol. The "++" symbol represents the operand's value is increased by 1. It can be used in two ways, as the post-increment and the pre-increment. Pre Increment: The pre-increment operator is represented as (++a), which means the value of variable 'a' is increment by 1 before using operand to the expression. for example: x = 10; A = ++x; The initial value of x is 10, and using the pre-increment operator (++x) increases the operand value by 1 before assigning it to the variable 'A'. Post Increment: The (a++) symbol represents the post- increment operator, which means the value of 'a' is incremented by 1 after assigning the original value to the expression or another variable. For example: x = 10; A = x++; Here the initial value of the x variable is 10 and using the post-increment operator (x++) to assign increment value of the 'x' to the variable 'A'. Unary Decrement Operator (--): The unary decrement operator is opposite to the unary increment operator. The Unary decrement operator is represented by the double minus (--) symbol, and it is used to decrease the operand value by 1 according to the decrement's types. The Unary decrement operator is of two types: the Pre decrement operator and the Post Decrement operator. Pre Decrement: The pre decrement operator is denoted as (--a) symbol, meaning the operand value is decreased by 1 before assigning to another variable or expression. Syntax int pre = --a; Post Decrement: The Post decrement operator is denoted as (a--) symbol, which means the original value is decreased by 1 after assigning to another variable or expression. Syntax int post = a--; OPERATORS Unary Sizeof() Operator: The sizeof is a keyword used to find the size of different data types or operands like int, float, char, double, etc. The syntax is sizeof(variable-name); Eg: #include void main() { int x; clrscr(); printf(“The value of x is %d”,sizeof(x)); getch(); } Output: The value of x is 2 Operator Precedence Operator precedence determines which operator is performed first in an expression with more than one operators with different 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. another example 10 + 20 * 30 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30 Operator precedence in C tells you which operator is performed first, next, and so on in an expression with more than one operator with different precedence. This plays a crucial role while we are performing day to day arithmetic operations. Operator precedence in C is used to determine the order of the operators to calculate the accurate output. Parenthesis has the highest precedence whereas comma has the lowest precedence in C. Why this Precedence Concept Come into Picture? Let’s suppose we have addition, multiplication, division, subtraction, etc. in a single statement. If we do not have this precedence concept than I have simply started calculating from left to right or right to left. But this is not correct because there is sometimes addition, multiplication, and division at starting of the statement, etc. So the user may or may not follow proper order for these operators. So to make a unique solution for calculating original outcome developers have introduced this precedence. Every Operator have their own precedence because without operator precedence a complier will conflict with data when performing mathematical calculations. Eg: 1+4*10/2; Calculate Left to Right then output 25. Calculate Right to Left then output 21. Now calculate based on precedence first *, followed by /,+. 4*10=40 40/2=20 20+1=21 What Happens if the same Precedence Operators come in Single statement? If we get 2 same precedences appearing in an expression, then it is said to be “Associativity”. Now, in this case, we can calculate this statement either from Left to right or right to left because both are having the same precedence. Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”. Operators Precedence and Associativity are two characteristics of operators that determine the evaluation order of sub-expressions in absence of brackets. C Operator Precedence Table C operators are listed in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied. precedence Operator Description Associativity () Parentheses: grouping or function call left-to-right 1 [] Brackets (array subscript). Member selection via object name -> Member selection via pointer ++ -- Postfix increment/decrement ++ -- Prefix increment/decrement right-to-left +- Unary plus/minus !~ Logical negation/bitwise complement 2 (type) Cast (convert value to temporary value of type) * Dereference & Address (of operand) sizeof Determine size in bytes on this implementation 3 */ % Multiplication/division/modulus left-to-right 4 + - Addition/subtraction left-to-right 5 > Bitwise shift left, Bitwise shift right left-to-right 6 < >= Relational greater than/greater than or equal to 7 == != Relational is equal to/is not equal to left-to-right 8 & Bitwise AND left-to-right 9 ^ Bitwise exclusive OR left-to-right 10 | Bitwise inclusive OR left-to-right 11 && Logical AND left-to-right 12 || Logical OR left-to-right 13 ?: Ternary conditional right-to-left = Assignment right-to-left 14 += -= Addition/subtraction assignment *= /= Multiplication/division assignment %= &= Modulus/bitwise AND assignment ^= |= Bitwise exclusive/inclusive OR assignment = Bitwise shift left/right assignment 15 , Comma (separate expressions) left-to-right 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. Examples of Operators Precedence in C: Example #1 – Parenthesis Precedence: Code: //used to include basice c library files #include //main method for run the C application int main() { //declaring variables int a,b; double output; //Asking user to enter 2 numbers as input printf("Please enter any 2 numbers \n"); //store 2 numbers in 2 variables scanf("%d\n\t%d",&a,&b); //assigning resultant of operators to a variable output=(a-b)*(a+b*a)+a/b; //displaying output //first precedence given to (), followed by / and + printf("output of %d and %d is = %lf ",a, b,output); return 0; } Output: Explanation: The first compiler read the entire output statement and start calculating based on precedence. As we discussed above first precedence given to parenthesis(()). If inside parenthesis also has more than 2 parameters with different operators then inside parenthesis also followed precedence rule. (a-b)*(a+b*a)+a/b; a-b =(10-2)=8 (a+b*a) =(10+2*10)=10+20=30 (a-b)*(a+b*a)=8*30=240 a/b =10/2=5 (a-b)*(a+b*a)+a/b =240+5=245 Therefore we got output as 245. Example #2 – Precedence with Arithmetic Operators Code: //used to include basic c library files #include //main method for run the C application int main() { //declaring variables int a,b; double output; //Asking user to enter 2 numbers as input printf("Please enter any 2 numbers \n"); //store 2 numbers in 2 variables scanf("%d\n\t%d",&a,&b); //assigning resultant of operators to a variable output=a+b*b-a/b%a; //displaying output //first precedence given to *, followed by /, %, + and - printf("Output of %d and %d is =%lf ",a, b,output); return 0; } Output: Explanation: In the above example precedence order is *, /, %, + and -. a+b*b-a/b%a b*b=>5*5=25 a/b=>10/5=2 a/b/%a=>a/b is already 2 so 2%5=2 a+b*b=>10+25=35 a+b*b-a/b%a=>35-2=33 So therefore we got output as 33. Example 3: Try the following example to understand operator precedence in C − #include 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 Expression Evaluation in C While knowing about expression evaluation we must understand what is an expression in C and what is an expression means. An expression in C is defined as 2 or more operands are connected by one operator and which can also be said to a formula to perform any operation. An operand is a function reference, an array element, a variable, or any constant. An operator is symbols like “+”, “-“, “/”, “*” etc. Now expression evaluation is nothing but operator precedence and associativity Expression Evaluation in C. Expression precedence in C tells you which operator is performed first, next, and so on in an expression with more than one operator with different precedence. This plays a crucial role while we are performing day to day arithmetic operations. If we get 2 same precedences appear in an expression, then it is said to be “Associativity”. Now in this case we can calculate this statement either from Left to right or right to left because this both are having the same precedence. Expression Evaluation in C Types of Expression Evaluation in C In C there are 4 types of expressions evaluations Arithmetic expressions evaluation Relational expressions evaluation Logical expressions evaluation Conditional expressions evaluation Every expression evaluation of these 4 types takes certain types of operands and used a specific type of operators. The result of this expression evaluation operation produces a specific value. Expression Evaluation in C 1. Arithmetic expression Evaluation Addition (+), Subtraction(-), Multiplication(*), Division(/), Modulus(%), Increment(++) and Decrement(–) operators are said to “Arithmetic expressions”. These operators work in between operands. like A+B, A-B, A–, A++ etc. While we perform the operation with these operators based on specified precedence order as like below image. A+B*C/D-E%F Arithmetic Expression evaluation order: Code: //used to include basic C libraries #include //main method for run c application int main() { //declaring variables int a,b,result_art_eval; //Asking the user to enter 2 numbers printf("Enter 2 numbers for Arithmetic evaluation operation\ n"); //Storing 2 numbers in varaibles a and b scanf("%d\n%d",&a,&b); //Arithmetic evaluation operations and its result displaying result_art_eval = a+b*a/b-a%b; printf("================ARITHMETIC EXPRESSION EVALUATION==============\n"); printf("Arithmetic expression evaluation of %d and %d is = %d \n",a,b,result_art_eval); printf("=============================== ==============================="); return 0; } Expression Evaluation in C Output: Explanation: As you can see in the above example arithmetic expression values evaluated based on precedence as the first *, followed by /, %, + and -. 2. Relational expression evaluation == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), B, AB)?”A is Big”:”B is Big”. While we perform the operation with these operators based on specified precedence order as like the below image. (X+2=10)?'true':'false'; Conditional expression Evaluation order: Type Conversion Typecasting is converting one data type into another one to perform some operation. It is also called as data conversion or type conversion in C language. The conversion is done only between those datatypes wherein the conversion is possible ex – char to int and vice versa. It is one of the important concepts introduced in ‘C’ programming. ‘C’ programming provides two types of type casting operations: Implicit type casting Explicit type casting Type Conversion 1)Implicit Type Conversion: This type of conversion is usually performed by the compiler when necessary without any commands by the user. Thus it is also called "Automatic Type Conversion". The compiler usually performs this type of conversion when a particular expression contains more than one data type. In such cases either type promotion or demotion takes place to avoid loss of data. Rules: 1. char or short type operands will be converted to int during an operation and the outcome data type will also be int. 2. If an operand of type long double is present in the expression, then the corresponding operand will also be converted to long double same for the double data type. 3. If an operand of float type is present then the corresponding operand in the expression will also be converted to float type and the final result will also be float type. 4. If an operand of unsigned long int is present then the other operand will be converted to unsigned long int and the final result will also be unsigned long int. 5. If an operand of long int is present then the other operand will be converted to long int and the final result will also be long int. 6. If an operand of unsigned int is present then the other operand will be converted to unsigned int and the final result will also be unsigned int. Thus, all these above illustrations suggest that whenever the compiler deals with different data types in an expression, the operand which is present at the lower rank will be converted to the corresponding datatype of the operand with the higher rank. For ease of understanding follow the flowchart given below, in which datatypes have been arranged in a hierarchy of highest to the lowest rank. Type Conversion Example 1: int a = 20; double b = 20.5; a + b; Here, first operand is int type and other is of type double. So, as per rule 2, the variable a will be converted to double. Therefore, the final answer is double a + b = 40.500000. Type Conversion Example 2 char ch='a'; int a =13; a + c; Here, first operand is char type and other is of type int. So, as per rule 1, the char variable will be converted to int type during the operation and the final answer will be of type int. We know the ASCII value for ch is 97. Therefore, final answer is a + c = 97 + 13 = 110. Type Conversion Example 3” char ch='A'; unsigned int a =60; a * b; Here, the first operand is char type and the other is of type unsigned int. So, as per rule 6, char data type will be converted to unsigned int during the operation. Therefore, the final result will be an unsigned int variable, 65 + 60 = 125. Example of Type Implicit Conversion: // An example of implicit conversion #include int main() { int x = 10; // integer x char y = 'a'; // character c // y implicitly converted to int. //ASCII value of 'a' is 97 x = x + y; // x is implicitly converted to float float z = x + 1.0; printf("x = %d, z = %f", x, z); return 0; } Output: x = 107, z = 108.000000 Important Points about Implicit Conversions: Implicit type of type conversion is also called as standard type conversion. We do not require any keyword or special statements in implicit type casting. Converting from smaller data type into larger data type is also called as type promotion. The implicit type conversion always happens with the compatible data types. We cannot perform implicit type casting on the data types which are not compatible with each other such as: Converting float to an int will truncate the fraction part hence losing the meaning of the value. Converting double to float will round up the digits. Converting long int to int will cause dropping of excess high order bits. In all the above cases, when we convert the data types, the value will lose its meaning. Generally, the loss of meaning of the value is warned by the compiler. ‘C’ programming provides another way of typecasting which is explicit type casting. Type Conversion 2) Explicit Type Conversion user defined. Explicit type conversion rules out the use of compiler for converting one data type to another instead the user explicitly defines within the program the datatype of the operands in the expression. syntax : (type) expression Example program: double da = 4.5; double db = 4.6; double dc = 4.9; //explicitly defined by user int result = (int)da + (int)db + (int)dc; printf("result = %d", result); Output result = 12 Type Conversion Thus, in the above example we find that the output result is 12 because in the result expression the user has explicitly defined the operands (variables) as integer data type. Hence, there is no implicit conversion of data type by the compiler. Type Conversion // C program to demonstrate explicit type casting #include int main() { double x = 1.2; // Explicit conversion from double to int int sum = (int)x + 1; printf("sum = %d", sum); return 0; } Output: sum = 2 Type Conversion Keep in mind the following rules for programming practice when dealing with different data type to prevent from data loss : Integers types should be converted to float. Float types should be converted to double. Character types should be converted to integer. It is always recommended to convert the lower value to higher for avoiding data loss. INPUT OUTPUT FUNCTIONS We know that input, process, output are the three essential features of computer program. The program takes some input data, processes it and gives the output. When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement. We have two methods for providing data to the program Assigning the data to the variable in a program eg:(x = 5, a = 0 ;) Another method is to use the Input then scanf which can be used to read data from a key board. When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files. For outputting results we have used extensively the function printf which sends results out to a terminal. In ‘C’ language, two types of Input/output statements are available, and all input and output operation are carried out through function calls. Several functions are available for input/output operations in ‘C’. These functions are collectively known as the standard I/O library 1. Unformatted Input/output Statements 2. Formatted Input/output Statements. Each program that uses standard input / out put function must contain the statement. # include < stdio.h > (at the beginning ) INPUT OUTPUT FUNCTIONS Formatted Input/output Statements: Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the user. These types of I/O functions can help to display the output to the user in different formats using the format specifiers. These I/O supports all data types like int, float, char, and many more. Formatted Input/output refers to input and output, that has been arranged in a particular format Why they are called formatted I/O? These functions are called formatted I/O functions because we can use format specifiers in these functions and hence, we can format these functions according to our needs. List of some format specifiers: Description Format Specifier S NO. Type used for I/O signed 1 %d int/signed int integer value Used for I/O character 2 %c char value Used for I/O decimal 3 %f float floating-point value Used for I/O string/group of 4 %s string characters Used for I/O long 5 %ld long int signed integer value Used for I/O unsigned 6 %u unsigned int integer value used for the I/O integer 7 %i unsigned int value Used for I/O fractional 8 %lf double or floating data INPUT OUTPUT FUNCTIONS The following are the Input/output formatted I/O functions : printf() scanf() sprintf() sscanf() INPUT OUTPUT FUNCTIONS We use printf() function with %d format specifier to display the value of an integer variable. Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal variable. To generate a newline,we use “\n” in C printf() statement. INPUT OUTPUT FUNCTIONS Note: C language is case sensitive. For example, printf() and scanf() are different from Printf() and Scanf(). All characters in printf() and scanf() functions must be in lower case. INPUT OUTPUT FUNCTIONS printf(): printf() function is used in a C program to display any value like float, integer, character, string, etc on the console(output) screen. It is a pre-defined function that is already declared in the stdio.h(header file). Syntax 1: printf(“Format Specifier”, var1, var2, …., varn); Example: // C program to implement // printf() function #include int main() { // Declaring an int type variable int a; // Assigning a value in a variable a = 20; // Printing the value of a variable printf("%d", a); return 0; } Output: 20 Example2: #include int main() { char ch = 'A'; char str = "fresh2refresh.com"; float flt = 10.234; int no = 150; double dbl = 20.123456; printf("Character is %c \n", ch); printf("String is %s \n" , str); printf("Float value is %f \n", flt); printf("Integer value is %d\n" , no); printf("Double value is %lf \n", dbl); return 0; } OUTPUT: Character is A String is fresh2refresh.com Float value is 10.234000 Integer value is 150 Double value is 20.123456 %c got replaced by value of a character variable (ch), %s got replaced by value of a string variable (str), %f got replaced by value of a float variable (flt), %d got replaced by value of an integer variable (no) %lf got replaced by value of a double variable Syntax 2: (To display any string or a message) printf(“Enter the text which you want to display”); Program: / C program to implement // printf() function #include // Driver code int main() { // Displays the string written // inside the double quotes printf("This is a string"); return 0; } Output: This is a string scanf(): scanf() function is used in the C program for reading or taking any value from the keyboard by the user, these values can be of any data type like integer, float, character, string, and many more. This function is declared in stdio.h(header file), that’s why it is also a pre-defined function. In scanf() function we use &(address-of operator) which is used to store the variable value on the memory location of that variable. Syntax: scanf(“Format Specifier”, &var1, &var2, …., &varn); / C program to implement scanf() function #include int main() { int num1; // Printing a message on the output screen printf("Enter a integer number: "); // Taking an integer value from keyboard scanf("%d", &num1); // Displaying the entered value printf("You have entered %d", num1); return 0; } Output: Enter a integer number: You have entered 0 Output: Enter a integer number: 56 You have entered 56 Program to print sum of 2 numbers: Let's see a simple example of input and output in C language that prints addition of 2 numbers. #include int main(){ int x=0,y=0,result=0; printf("enter first number:"); scanf("%d",&x); printf("enter second number:"); scanf("%d",&y); result=x+y; printf("sum of 2 numbers:%d ",result); return 0; } Output: enter first number:9 enter second number:9 sum of 2 numbers:18 printf() and scanf() functions are inbuilt library functions in C programming language which are available in C library by default. These functions are declared and related macros are defined in “stdio.h” which is a header file in C language. We have to include “stdio.h” file to make use of these printf() and scanf() library functions in C language. sscanf(): sscanf stands for “string scanf”. This function is similar to scanf() function but this function reads data from the string or character array instead of the console screen and store each value into variables of matching data type by specifying the matching format specifier. Syntax: sscanf(array_name, “format specifier”, &variable_name); extract the data from the character array according to the conversion specifier and store into the respective variables. sscanf() will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab). Consider example: char *str = "Learn C Online"; If we want to extract “Learn”, “C” and “Online” in a different variable then it can be done using sscanf function. example of sscanf() function: #include int main () { char buffer="Fresh2refresh 5 "; char name ; int age; sscanf (buffer,"%s %d",name,&age); printf ("Name : %s \n Age : %d \n",name,age); return 0; } OUTPUT: Name : Fresh2refresh Age : 5 example2 of sscanf() function: In the upcoming example, we are going to use scanf function to read(linearly) the multiple values present in a char[] array and store each value in a matching variable using a matching format specifier within sscanf() function. include int main() { char ar = "User M 19 1.85"; char str; char ch; int i; float f; sscanf(ar, "%s %c %d", &str, &ch, &i, &f); printf("The value in string is : %s ", str); printf("\n"); printf("The value in char is : %c ", ch); printf("\n"); printf("The value in int is : %d ", i); printf("\n"); printf("The value in float is : %f ", f); sscanf(ar, "%s %c %d", &str, &ch, &i); return 0; } Output: The value in string is : User The value in char is : M The value in int is : 19 The value in float is : 1.850000 Explanation: – Reads the first value i.e. a string by using format specifier %s and stores it in str. – Reads the second value i.e. a char by using format specifier %c and stores it in ch. – Reads the third value i.e. a int by using format specifier %d and stores it in i. – Reads the fourth value i.e. float by using format specifier %f and stores it in f. INPUT OUTPUT FUNCTIONS sprintf(): sprintf stands for “string print”. This function is similar to printf() function but this function prints the string into a character array instead of printing it on the console screen. Syntax: sprintf(array_name, “format specifier”, variable_name); sprintf() function is exactly opposite to sscanf() function. Sprint() function writes the formatted text to a EXAMPLE PROGRAM FOR SPRINTF() FUNCTION IN C PROGRAMMING LANGUAGE: 1 #include 2 #include 3 4 int main( ) 5 { 6 int value = 50 ; 7 float flt = 7.25 ; 8 char c = 'Z' ; 9 char string = {‘\0’} ; 1 printf ( "int value = %d \n char value = %c \n " \ 0 "float value = %f", value, c, flt ) ; 1 1 2 printf(“\n Before using sprint, data in string is %s”, 1 string); 3 sprintf ( string, "%d %c %f", value, c, flt ); 1 printf(“\n After using sprint, data in string is %s”, 4 string); 1 return 0; 5 } 1 6 1 7 1 8 1 9 output #include int main() { char target; char name = "Andrea"; char gender = 'F'; int age = 25; float height = 1.70; printf("The name is : %s", name); printf("\n"); printf("The gender is : %c", gender); printf("\n"); printf("The age is : %d", age); printf("\n"); printf("The height is : %f", height); sprintf(target, "%s %c %d %f", name, gender, age, height); printf("\n"); printf("The value in the target string is : %s ", target); return 0; } Output: The name is : Andrea The gender is : F The age is : 25 The height is : 1.700000 The value in the target string is : Andrea F 25 1.700000 Explanation: sprintf() function, which linearly reads multiple values by specifying the matching format specifier with their variable names and stores each all these values in a char[] array named target. // C program to implement the sprintf() function #include int main() { char str; int a = 2, b = 8; // The string "2 and 8 are even number“ // is now stored into str sprintf(str, "%d and %d are even number", a, b); // Displays the string printf("%s", str); return 0; } Output: 2 and 8 are even number INPUT OUTPUT FUNCTIONS Unformatted Input/output Statements: These statements are used to Input/output a single/group of characters form/ to the input/output devices. Here the user cannot specify the type of data that is going to be input/output. Functions Description Reads a single character from the user getch() at the console, without echoing it. Reads a single character from the user getche() at the console, and echoing it. Reads a single character from the user at the console, and echoing it, but getchar() needs an Enter key to be pressed at the end. Reads a single string entered by the gets() user at the console. Functions Description Displays a single string's value at the puts() console. Displays a single character value at the putch() console. putchar() Displays a single character value at the console. INPUT OUTPUT FUNCTIONS getch() : It accepts only a single character from the keyboard. The character entered through getch() is not displayed on the screen (monitor). Why we use a getch() function? We use a getch() function in a C/ C++ program to hold the output screen for some time until the user passes a key from the keyboard to exit the console screen. Using getch() function, we can hide the input character provided by the users in the ATM PIN, password, etc. Syntax: int getch(void); Parameters: The getch() function does not accept any parameter from the user. Eg: 1 #include 2 int main() 3 { 4 5 printf("Hello World! "); 6 getch(); 7 return 0; 8 } OUTPUT: Hello World! Explanation: This is a simple Hello World! C program. After displaying Hello World! in output screen, this program waits for any character input from keyboard. After any single character is typed/pressed, this program returns 0. But, please note that, getch() function will just wait for any keyboard input (and press ENTER). It won’t display the given input character in output screen. getche(): getche() function is a function in C programming language which waits for any character input from keyboard and it will also echo the input character on to the output screen. EXAMPLE PROGRAM FOR GETCHE() FUNCTION IN C: 1 #include 2 int main() 3 { 4 char flag; 5 6 printf("Hello World! "); 7 printf("Do you want to continue Y or N"); 8 flag = getche(); // It waits for keyboard input. 9 if (flag == 'Y') 1 { 0 printf("You have entered Yes"); 1 } 1 else 1 {