C Programming Language.pdf
Document Details
Full Transcript
C & C++ Notes BY Xhk Basharat Sheikh Basharat 9682669193 1 NOTES OF C & C++ BY XHK BASHARAT...... C Programming Language What is C? C is a general-purpose, procedural, high-level programming language used in the development of computer s...
C & C++ Notes BY Xhk Basharat Sheikh Basharat 9682669193 1 NOTES OF C & C++ BY XHK BASHARAT...... C Programming Language What is C? C is a general-purpose, procedural, high-level programming language used in the development of computer software and applications, system programming, games, and more. C language was developed by Dennis M. Ritchie at the Bell Telephone Laboratories in 1972. It is a powerful and flexible language which was first developed for the programming of the UNIX operating System. C is one of the most widely used programming languages. C programming language is known for its simplicity and efficiency. It is the best choice to start with programming as it gives you a foundational understanding of programming C Language Introduction C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and Portable Low-level Memory Access Fast Speed Clean Syntax These features make the C language suitable for system programming like an operating system or compiler development. Why Should We Learn C? Many later languages have borrowed syntax/features directly or indirectly from the C language like the syntax of Java, PHP, JavaScript, and many other languages that are mainly based on the C language. C++ is nearly a superset of C language (Only a few programs may compile in C, but not in C++). So, if a person learns C programming first, it will help them to learn any modern programming language as well. Also, learning C helps to understand a lot of the underlying architecture of the operating system like pointers, working with memory locations, etc. Difference Between C and C++ C++ was created to add the OOPs concept into the C language so they both have very similar syntax with a few differences. The following are some of the main differences between C and C++ Programming languages. C++ supports OOPs paradigm while C only has the procedural concept of programming. 2 NOTES OF C & C++ BY XHK BASHARAT...... C++ has exception handling capabilities. In C, we have to resolve exceptions manually. There are no references in C. There are many more differences between C and C++ which are discussed here: Difference between C and C++ Beginning with C Programming Writing the First Program in C The following code is one of the simplest C programs that will help us understand the basic syntax structure of a C program. #include int main() { int a = 10; printf("%d", a); return 0; } Output 10 Let us analyze the structure of our program line by line. Structure of the C program After the above discussion, we can formally assess the basic structure of a C program. By structure, it is meant that any program can be written in this structure only. Writing a C program in any other structure will lead to a Compilation Error. The structure of a C program is as follows: Components of a C Program: 1. Header Files Inclusion – Line 1 [#include ] 3 NOTES OF C & C++ BY XHK BASHARAT...... The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension.h which contains C function declarations and macro definitions to be shared between several source files. All lines that start with # are processed by a preprocessor which is a program invoked by the compiler. In the above example, the preprocessor copies the preprocessed code of stdio.h to our file. The.h files are called header files in C. Some of the C Header files: stddef.h – Defines several useful types and macros. stdint.h – Defines exact width integer types. stdio.h – Defines core input and output functions stdlib.h – Defines numeric conversion functions, pseudo-random number generator, and memory allocation string.h – Defines string handling functions math.h – Defines common mathematical functions. 2. Main Method Declaration – Line 2 [int main()] The next part of a C program is to declare the main() function. It is the entry point of a C program and the execution typically begins with the first line of the main(). The empty brackets indicate that the main doesn’t take any parameter (See this for more details). The int that was written before the main indicates the return type of main(). The value returned by the main indicates the status of program termination. See this post for more details on the return type. 3. Body of Main Method – Line 3 to Line 6 [enclosed in {}] The body of a function in the C program refers to statements that are a part of that function. It can be anything like manipulations, searching, sorting, printing, etc. A pair of curly brackets define the body of a function. All functions must start and end with curly brackets. 4. Statement – Line 4 [printf(“Hello World”);] Statements are the instructions given to the compiler. In C, a statement is always terminated by a semicolon (;). In this particular case, we use printf() function to instruct the compiler to display “Hello World” text on the screen. 5. Return Statement – Line 5 [return 0;] The last part of any C function is the return statement. The return statement refers to the return values from a function. This return statement and return value depend upon the return type of the function. The return statement in our program returns the value from main(). The returned value may be used by an operating system to know the termination status of your program. The value 0 typically means successful termination. How to Execute the Above Program? In order to execute the above program, we need to first compile it using a compiler and then we can run the generated executable. There are online IDEs available for free like GeeksforGeeksIDE, that can be used to start development in C without installing a compiler. 4 NOTES OF C & C++ BY XHK BASHARAT...... 1. Windows: There are many free IDEs available for developing programs in C like Code Blocks and Dev-CPP. IDEs provide us with an environment to develop code, compile it and finally execute it. We strongly recommend Code Blocks. 2. Linux: GCC compiler comes bundled with Linux which compiles C programs and generates executables for us to run. Code Blocks can also be used with Linux. 3. macOS: macOS already has a built-in text editor where you can just simply write the code and save it with a “.c” extension. Application of C Operating systems: C is widely used for developing operating systems such as Unix, Linux, and Windows. Embedded systems: C is a popular language for developing embedded systems such as microcontrollers, microprocessors, and other electronic devices. System software: C is used for developing system software such as device drivers, compilers, and assemblers. Networking: C is widely used for developing networking applications such as web servers, network protocols, and network drivers. Database systems: C is used for developing database systems such as Oracle, MySQL, and PostgreSQL. Gaming: C is often used for developing computer games due to its ability to handle low-level hardware interactions. Artificial Intelligence: C is used for developing artificial intelligence and machine learning applications such as neural networks and deep learning algorithms. Scientific applications: C is used for developing scientific applications such as simulation software and numerical analysis tools. Financial applications: C is used for developing financial applications such as stock market analysis and trading systems. Features of C Programming Language C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programming like an operating system or compiler development. What are the Most Important Features of C Language? Here are some of the most important features of the C language: 1. Procedural Language 2. Fast and Efficient 5 NOTES OF C & C++ BY XHK BASHARAT...... 3. Modularity 4. Statically Type 5. General-Purpose Language 6. Rich set of built-in Operators 7. Libraries with Rich Functions 8. Middle-Level Language 9. Portability 10. Easy to Extend Let discuss these features one by one: 1. Procedural Language In a procedural language like C step by step, predefined instructions are carried out. C program may contain more than one function to perform a particular task. New people to programming will think that this is the only way a particular programming language works. There are other programming paradigms as well in the programming world. Most of the commonly used paradigm is an object- oriented programming language. 2. Fast and Efficient Newer languages like Java, python offer more features than c programming language but due to additional processing in these languages, their performance rate gets down effectively. C programming language as the middle-level language provides programmers access to direct manipulation with the computer hardware but higher-level languages do not allow this. That’s one of the reasons C language is considered the first choice to start learning programming languages. It’s fast because statically typed languages are faster than dynamically typed languages. 3. Modularity The concept of storing C programming language code in the form of libraries for further future uses is known as modularity. This programming language can do very little on its own most of its power is held by its libraries. C language has its own library to solve common problems. 6 NOTES OF C & C++ BY XHK BASHARAT...... 4. Statically Type C programming language is a statically typed language. Meaning the type of variable is checked at the time of compilation but not at run time. This means each time a programmer types a program they have to mention the type of variables used. 5. General-Purpose Language From system programming to photo editing software, the C programming language is used in various applications. Some of the common applications where it’s used are as follows: Operating systems: Windows, Linux, iOS, Android, OXS Databases: PostgreSQL, Oracle, MySQL, MS SQL Server, etc. 6. Rich set of built-in Operators It is a diversified language with a rich set of built-in operators which are used in writing complex or simplified C programs. 7. Libraries with Rich Functions Robust libraries and functions in C help even a beginner coder to code with ease. 8. Middle-Level Language As it is a middle-level language so it has the combined form of both capabilities of assembly language and features of the high-level language. 9. Portability C language is lavishly portable as programs that are written in C language can run and compile on any system with either no or small changes. 10. Easy to Extend Programs written in C language can be extended means when a program is already written in it then some more features and operations can be added to it. C Programming Language Standard Introduction: The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18. 1. C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the features that are still used in modern C programming, including data types, control structures, and the standard library. 2. C99 (ISO/IEC 9899:1999) introduced several new features, including variable-length arrays, flexible array members, complex numbers, inline functions, and designated initializers. This standard also includes several new library functions and updates to existing ones. 7 NOTES OF C & C++ BY XHK BASHARAT...... 3. C11 (ISO/IEC 9899:2011) introduced several new features, including _Generic, static_assert, and the atomic type qualifier. This standard also includes several updates to the library, including new functions for math, threads, and memory manipulation. 4. C18 (ISO/IEC 9899:2018) is the most recent standard and includes updates and clarifications to the language specification and the library. When writing C code, it’s important to know which standard version is being used and to write code that is compatible with that standard. Many compilers support multiple standard versions, and it’s often possible to specify which version to use with a compiler flag or directive. Here are some advantages and disadvantages of using the C programming language: Advantages: 1. Efficiency: C is a fast and efficient language that can be used to create high-performance applications. 2. Portability: C programs can be compiled and run on a wide range of platforms and operating systems. 3. Low-level access: C provides low-level access to system resources, making it ideal for systems programming and developing operating systems. 4. Large user community: C has a large and active user community, which means there are many resources and libraries available for developers. 5. Widely used: C is a widely used language, and many modern programming languages are built on top of it. Disadvantages: 1. Steep learning curve: C can be difficult to learn, especially for beginners, due to its complex syntax and low-level access to system resources. 2. Lack of memory management: C does not provide automatic memory management, which can lead to memory leaks and other memory-related bugs if not handled properly. 3. No built-in support for object-oriented programming: C does not provide built-in support for object-oriented programming, making it more difficult to write object-oriented code compared to languages like Java or Python. 4. No built-in support for concurrency: C does not provide built-in support for concurrency, making it more difficult to write multithreaded applications compared to languages like Java or Go. 5. Security vulnerabilities: C programs are prone to security vulnerabilities, such as buffer overflows, if not written carefully. Overall, C is a powerful language with many advantages, but it also requires a high degree of expertise to use effectively and has some potential drawbacks, especially for beginners or developers working on complex projects. 8 NOTES OF C & C++ BY XHK BASHARAT...... What to do when a C program produces different results in two different compilers? For example, consider the following simple C program. C void main() { } The above program fails in GCC as the return type of main is void, but it compiles in Turbo C. How do we decide whether it is a legitimate C program or not? Consider the following program as another example. It produces different results in different compilers. C // C++ Program to illustrate the difference in different // compiler execution #include int main() { int i = 1; printf("%d %d %d\n", i++, i++, i); return 0; } 2 1 3 - using g++ 4.2.1 on Linux.i686 1 2 3 - using SunStudio C++ 5.9 on Linux.i686 2 1 3 - using g++ 4.2.1 on SunOS.x86pc 1 2 3 - using SunStudio C++ 5.9 on SunOS.x86pc 1 2 3 - using g++ 4.2.1 on SunOS.sun4u 1 2 3 - using SunStudio C++ 5.9 on SunOS.sun4u Source: Stackoverflow Which compiler is right? The answer to all such questions is C standard. In all such cases, we need to see what C standard says about such programs. 9 NOTES OF C & C++ BY XHK BASHARAT...... C Hello World Program The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the “Hello World”, we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print “Hello World” The following C program displays “Hello World” in the output screen: C // Simple C program to display "Hello World" // Header file for input output functions #include // Main function: entry point for execution int main() { // writing print statement to print hello world printf("Hello World"); return 0; } Output Hello World Explanation: #include – This line includes the standard input-output library in the program. int main() – The main function where the execution of the program begins. printf(“Hello, World!\n”); – This function call prints “Hello, World!” followed by a new line. return 0; -This statement indicates that the program ended successfully. Table of Content Other Different Ways to Write a “Hello, World!” Program in C o Using puts() Function o Using write() System Call o Character-by-Character Printing Other Ways to Write a “Hello, World!” Program in C We can use many different methods apart from the printf() to print “Hello, World!” in C. Some of them are given below: 10 NOTES OF C & C++ BY XHK BASHARAT...... Using puts() Function The puts function can be used instead of printf for a simpler approach. C #include int main() { puts("Hello, World!"); return 0; } Output Hello, World! Using write() System Call Although not recommended for beginners, you can avoid including stdio.h and use system calls instead. This is more advanced and not as portable. C int main() { write(1, "Hello, World!\n", 14); return 0; } Output Hello, World! Character-by-Character Printing You can print each character of the string separately. C #include int main() { char *str = "Hello, World!\n"; while (*str) { putchar(*str++); 11 NOTES OF C & C++ BY XHK BASHARAT...... } return 0; } Output Hello, World! These are various ways to write a “Hello, World!” program in C. Each example demonstrates different aspects and functions of the language, providing multiple approaches for beginners to understand and explore. Compiling a C Program: Behind the Scenes The compilation is the process of converting the source code of the C language into machine code. As C is a mid-level language, it needs a compiler to convert it into an executable code so that the program can be run on our machine. The C program goes through the following phases during compilation: Compilation Process in C How do we compile and run a C program? We first need a compiler and a code editor to compile and run a C Program. The below example is of an Ubuntu machine with GCC compiler. Step 1: Creating a C Source File We first create a C program using an editor and save the file as filename.c $ vi filename.c We can write a simple hello world program and save it. Step 2: Compiling using GCC compiler We use the following command in the terminal for compiling our filename.c source file $ gcc filename.c –o filename We can pass many instructions to the GCC compiler to different tasks such as: 12 NOTES OF C & C++ BY XHK BASHARAT...... The option -Wall enables all compiler’s warning messages. This option is recommended to generate better code. The option -o is used to specify the output file name. If we do not use this option, then an output file with the name a.out is generated. If there are no errors in our C program, the executable file of the C program will be generated. Step 3: Executing the program After compilation executable is generated and we run the generated executable using the below command. $./filename The program will be executed and the output will be shown in the terminal. What goes inside the compilation process? A compiler converts a C program into an executable. There are four phases for a C program to become an executable: 1. Pre-processing 2. Compilation 3. Assembly 4. Linking By executing the below command, we get all intermediate files in the current directory along with the executable. $gcc -Wall -save-temps filename.c –o filename The following screenshot shows all generated intermediate files. Intermediate Files Let us one by one see what these intermediate files contain. 1. Pre-processing This is the first phase through which source code is passed. This phase includes: Removal of Comments Expansion of Macros Expansion of the included files. Conditional compilation The preprocessed output is stored in the filename.i. Let’s see what’s inside filename.i: using $vi filename.i 13 NOTES OF C & C++ BY XHK BASHARAT...... In the above output, the source file is filled with lots and lots of info, but in the end, our code is preserved. printf contains now a + b rather than add(a, b) that’s because macros have expanded. Comments are stripped off. #include is missing instead we see lots of code. So header files have been expanded and included in our source file. 2. Compiling The next step is to compile filename.i and produce an; intermediate compiled output file filename.s. This file is in assembly-level instructions. Let’s see through this file using $nano filename.s terminal command. 3. Assembling In this phase the filename.s is taken as input and turned into filename.o by the assembler. This file contains machine-level instructions. At this phase, only existing code is converted into machine language, and the function calls like printf() are not resolved. Let’s view this file using $vi filename.o 4. Linking This is the final phase in which all the linking of function calls with their definitions is done. Linker knows where all these functions are implemented. Linker does some extra work also, it adds some extra code to our program which is required when the program starts and ends. For example, there is a code that is required for setting up the environment like passing command line arguments. This task can be easily verified by using $size filename.o and $size filename. Through these commands, we know how the output file increases from an object file to an executable file. This is because of the extra code that Linker adds to our program. C Comments The comments in C are human-readable explanations or notes in the source code of a C program. A comment makes the program easier to read and understand. These are the statements that are not executed by the compiler or an interpreter. It is considered to be a good practice to document our code using comments. When and Why to use Comments in C programming? 1. A person reading a large code will be bemused if comments are not provided about details of the program. 2. C Comments are a way to make a code more readable by providing more descriptions. 3. C Comments can include a description of an algorithm to make code understandable. 4. C Comments can be used to prevent the execution of some parts of the code. Types of comments in C In C there are two types of comments in C language: 14 NOTES OF C & C++ BY XHK BASHARAT...... Single-line comment Multi-line comment Types of Comments in C 1. Single-line Comment in C A single-line comment in C starts with ( // ) double forward slash. It extends till the end of the line and we don’t need to specify its end. Syntax of Single Line C Comment // This is a single line comment Example 1: C Program to illustrate single-line comment C // C program to illustrate // use of single-line comment #include int main(void) { // This is a single-line comment printf("Welcome to GeeksforGeeks"); return 0; } Output: Welcome to GeeksforGeeks Comment at End of Code Line We can also create a comment that displays at the end of a line of code using a single-line comment. But generally, it’s better to practice putting the comment before the line of code. Example: C 15 NOTES OF C & C++ BY XHK BASHARAT...... // C program to demonstrate commenting after line of code #include int main() { // single line comment here printf("Welcome to GeeksforGeeks"); // comment here return 0; } Output Welcome to GeeksforGeeks 2. Multi-line Comment in C The Multi-line comment in C starts with a forward slash and asterisk ( ). Any text between is treated as a comment and is ignored by the compiler. It can apply comments to multiple lines in the program. Syntax of Multi-Line C Comment Example 2: C Program to illustrate the multi-line comment C #include int main(void) 16 NOTES OF C & C++ BY XHK BASHARAT...... { printf("Welcome to GeeksforGeeks"); return 0; } Output: Welcome to GeeksforGeeks Tokens in C A token in C can be defined as the smallest individual element of the C programming language that is meaningful to the compiler. It is the basic component of a C program. Types of Tokens in C The tokens of C language can be classified into six types based on the functions they are used to perform. The types of C tokens are as follows: 1. Keywords 2. Identifiers 3. Constants 17 NOTES OF C & C++ BY XHK BASHARAT...... 4. Strings 5. Special Symbols 6. Operators 1. C Token – Keywords The keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords. However, you can specify the text to be substituted for keywords before compilation by using C preprocessor directives. C language supports 32 keywords which are given below: auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while Note: The number of keywords may change depending on the version of C you are using. For example, keywords present in ANSI C are 32 while in C11, it was increased to 44. Moreover, in the latest c23, it is increased to around 54. 2. C Token – Identifiers Identifiers are used as the general terminology for the naming of variables, functions, and arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special identifier called a statement label can be used in goto statements. Rules for Naming Identifiers Certain rules should be followed while naming c identifiers which are as follows: They must begin with a letter or underscore(_). They must consist of only letters, digits, or underscore. No other special character is allowed. It should not be a keyword. It must not contain white space. It should be up to 31 characters long as only the first 31 characters are significant. Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different. For example, main: method name. 18 NOTES OF C & C++ BY XHK BASHARAT...... a: variable name. 3. C Token – Constants The constants refer to the variables with fixed values. They are like normal variables but with the difference that their values can not be modified in the program once they are defined. Constants may belong to any of the data types. Examples of Constants in C const int c_var = 20; const int* const ptr = &c_var; 4. C Token – Strings Strings are nothing but an array of characters ended with a null character (‘\0’). This null character indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a character is enclosed in single quotes in C and C++. Examples of String char string = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’}; char string = “geeksforgeeks”; char string [] = “geeksforgeeks”; 5. C Token – Special Symbols The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose. Some of these are listed below: Brackets[]: Opening and closing brackets are used as array element references. These indicate single and multidimensional subscripts. Parentheses(): These special symbols are used to indicate function calls and function parameters. Braces{}: These opening and ending curly braces mark the start and end of a block of code containing more than one executable statement. Comma (, ): It is used to separate more than one statement like for separating parameters in function calls. Colon(:): It is an operator that essentially invokes something called an initialization list. Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s why each individual statement must be ended with a semicolon. Asterisk (*): It is used to create a pointer variable and for the multiplication of variables. Assignment operator(=): It is used to assign values and for logical operation validation. Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler to transform your program before actual compilation. Period (.): Used to access members of a structure or union. Tilde(~): Bitwise One’s Complement Operator. 19 NOTES OF C & C++ BY XHK BASHARAT...... 6. C Token – Operators Operators are symbols that trigger an action when applied to C variables and other objects. The data items on which operators act are called operands. Depending on the number of operands that an operator can act upon, operators can be classified as follows: Unary Operators: Those operators that require only a single operand to act upon are known as unary operators.For Example increment and decrement operators Binary Operators: Those operators that require two operands to act upon are called binary operators. Binary operators can further are classified into: 1. Arithmetic operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Bitwise Operator Ternary Operator: The operator that requires three operands to act upon is called the ternary operator. Conditional Operator(?) is also called the ternary operator. Keywords in C In C Programming language, there are many rules so to avoid different types of errors. One of such rule is not able to declare variable names with auto, long, etc. This is all because these are keywords. Let us check all keywords in C language. What are Keywords? Keywords are predefined or reserved words that have special meanings to the compiler. These are part of the syntax and cannot be used as identifiers in the program. A list of keywords in C or reserved words in the C programming language are mentioned below: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while auto 20 NOTES OF C & C++ BY XHK BASHARAT...... auto is the default storage class variable that is declared inside a function or a block. auto variables can only be accessed within the function/block they are declared. By default, auto variables have garbage values assigned to them. Automatic variables are also called local variables as they are local to a function. auto int num; Here num is the variable of the storage class auto and its type is int. Below is the C program to demonstrate the auto keyword: C // C program to demonstrate // auto keyword #include int printvalue() { auto int a = 10; printf("%d", a); } // Driver code int main() { printvalue(); return 0; } Output 10 break and continue The break statement is used to terminate the innermost loop. It generally terminates a loop or a break statement. The continue statement skips to the next iteration of the loop. Below is the C program to demonstrate break and continue in C: C // C program to show use 21 NOTES OF C & C++ BY XHK BASHARAT...... // C program to show use // of break and continue #include // Driver code int main() { for (int i = 1; i b", a > b); return 0; } Output a is smaller 0 is the result of a>b Using bool in Loops The bool data type is also used in loops such as while loops and for loops. Conditional statements are one of the most important parts used with loops. We can’t define breakpoints of loops without using conditional statements which return boolean values, without conditional statement loop becomes infinite loop. Below is the implementation of the above approach: C // C Program to demonstrate // Using bool in loops #include #include // Main Function int main() 101 NOTES OF C & C++ BY XHK BASHARAT...... { // boolean declared bool a = true; int i = 0; // while loop while (a) { printf("i is %d\n", i); i++; // Conditional statement returning // true or false // Breaking point for loop if (i > 5) { a = false; } } return 0; } Output i is 0 i is 1 i is 2 i is 3 i is 4 i is 5 Using bool as a Function Return Type You can also use the bool data type as a function return type. Function return type adds the feature to return the result of all the operations performed inside the function. Below is the implementation of the above approach: 102 NOTES OF C & C++ BY XHK BASHARAT...... C // C Program to demonstrate using of // bool as a function return type #include #include // function returning boolean value bool is_even(int num) { if (num % 2 == 0) { return true; } else { return false; } } // Main function int main() { // Integer value declared int num = 5; // Function calling if (is_even(num)) { printf("%d is even\n", num); } else { printf("%d is odd\n", num); } 103 NOTES OF C & C++ BY XHK BASHARAT...... return 0; } Output 5 is odd Conclusion The bool data type is a fundamental data type in most programming languages that can hold one of two values: true or false. In C, you can use bool variables by including the header file “stdbool.h”, using an enumeration type, or using an int or a char with a value of either 0(false) or 1(true) according to the condition defined. bool in C – FAQs What is boolean example in C? Boolean is a data type in C that holds two values that can be either true or false. What is the C header for bool? “stdbool.h” is the C header for bool. What is the size of boolean in C? Boolean in C has the size of 1 byte as it needs only two values 0 and 1. Does C use bool or boolean? Boolean is a data type that can store values as true or false, and we use it in C as a bool. Integer Promotions in C Some data types like char , short int take less number of bytes than int, these data types are automatically promoted to int or unsigned int when an operation is performed on them. This is called integer promotion. For example no arithmetic calculation happens on smaller types like char, short and enum. They are first converted to int or unsigned int, and then arithmetic is done on them. If an int can represent all values of the original type, the value is converted to an int. Otherwise, it is converted to an unsigned int. For example see the following program. C #include int main() { char a = 30, b = 40, c = 10; 104 NOTES OF C & C++ BY XHK BASHARAT...... char d = (a * b) / c; printf ("%d ", d); return 0; } Output: 120 At first look, the expression (a*b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (in most of the C compilers), and the value of subexpression ‘(a*b)’ is 1200 which is greater than 128. But integer promotion happens here in arithmetic done on char types and we get the appropriate result without any overflow. Consider the following program as another example. C #include int main() { char a = 0xfb; unsigned char b = 0xfb; printf("a = %c", a); printf("\nb = %c", b); if (a == b) printf("\nSame"); else printf("\nNot Same"); return 0; } Output: a=? 105 NOTES OF C & C++ BY XHK BASHARAT...... b=? Not Same When we print ‘a’ and ‘b’, same character is printed, but when we compare them, we get the output as “Not Same”. ‘a’ and ‘b’ have same binary representation as char. But when comparison operation is performed on ‘a’ and ‘b’, they are first converted to int. ‘a’ is a signed char, when it is converted to int, its value becomes -5 (signed value of 0xfb). ‘b’ is unsigned char, when it is converted to int, its value becomes 251. The values -5 and 251 have different representations as int, so we get the output as “Not Same”. Character Arithmetic in C Character Arithmetic? Character arithmetic is used to implement arithmetic operations like addition, subtraction, multiplication, and division on characters in C language. In character arithmetic character converts into an integer value to perform the task. For this ASCII value is used. It is used to perform actions on the strings. To understand better let’s take an example. Example 1 C // C program to demonstrate character arithmetic. #include int main() { char ch1 = 125, ch2 = 10; ch1 = ch1 + ch2; printf("%d\n", ch1); printf("%c\n", ch1 - ch2 - 4); return 0; } Output -121 y 106 NOTES OF C & C++ BY XHK BASHARAT...... So %d specifier causes an integer value to be printed and %c specifier causes a character value to printed. But care has to taken that while using %c specifier the integer value should not exceed 127. Let’s take one more example. Example 2 C #include // driver code int main(void) { char value1 = 'a'; char value2 = 'b'; char value3 = 'z'; // perform character arithmetic char num1 = value1 + 3; char num2 = value2 - 1; char num3 = value3 + 2; // print value printf("numerical value=%d\n", num1); printf("numerical value=%d\n", num2); printf("numerical value=%d\n", num3); return 0; } Output numerical value=100 numerical value=97 numerical value=124 Example 3 C #include 107 NOTES OF C & C++ BY XHK BASHARAT...... int main() { char a = 'A'; char b = 'B'; printf("a = %c\n", a); printf("b = %c\n", b); printf("a + b = %c\n", a + b); return 0; } Output a=A b=B a+b=â Explanation In this program, two character variables a and b are declared and assigned the values ‘A’ and ‘B’, respectively. The program then adds a and b using character arithmetic, which results ‘â’. The result is then printed using the printf() function. Note that in character arithmetic, the characters are treated as integers based on their ASCII code values. For example, the ASCII code for ‘A’ is 65 and for ‘B’ is 66, so adding ‘A’ and ‘B’ results in 65 + 66 = 131, which is the ASCII code for ‘â’. Type Conversion in C Type conversion in C is the process of converting one data type to another. The type conversion is only performed to those data types where conversion is possible. Type conversion is performed by a compiler. In type conversion, the destination data type can’t be smaller than the source data type. Type conversion is done at compile time and it is also called widening conversion because the destination data type can’t be smaller than the source data type. There are two types of Conversion: 1. Implicit Type Conversion 108 NOTES OF C & C++ BY XHK BASHARAT...... Also known as ‘automatic type conversion’. A. Done by the compiler on its own, without any external trigger from the user. B. Generally takes place when in an expression more than one data type is present. In such conditions type conversion (type promotion) takes place to avoid loss of data. C. All the data types of the variables are upgraded to the data type of the variable with the largest data type. bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double D. It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long is implicitly converted to float). Occurrences of Implicit Type Conversion in C Implicit type conversion is also called automatic type conversion. Some of its few occurrences are mentioned below: Conversion Rank Conversions in Assignment Expressions Conversion in other Binary Expressions Promotion Demotion Example of Type Implicit Conversion Example no 1 C 109 NOTES OF C & C++ BY XHK BASHARAT...... // 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 2. Explicit Type Conversion This process is also called type casting and it is user-defined. Here the user can typecast the result to make it of a particular data type. The syntax in C Programming: (type) expression Type indicated the data type to which the final result is converted. 110 NOTES OF C & C++ BY XHK BASHARAT...... Example no 2 C // 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 Example no 3 C #include int main() { float a = 1.5; int b = (int)a; printf("a = %f\n", a); printf("b = %d\n", b); 111 NOTES OF C & C++ BY XHK BASHARAT...... return 0; } Output a = 1.500000 b=1 Advantages of Type Conversion Type safety: Type conversions can be used to ensure that data is being stored and processed in the correct data type, avoiding potential type mismatches and type errors. Improved code readability: By explicitly converting data between different types, you can make the intent of your code clearer and easier to understand. Improved performance: In some cases, type conversions can be used to optimize the performance of your code by converting data to a more efficient data type for processing. Improved compatibility: Type conversions can be used to convert data between different types that are not compatible, allowing you to write code that is compatible with a wider range of APIs and libraries. Improved data manipulation: Type conversions can be used to manipulate data in various ways, such as converting an integer to a string, converting a string to an integer, or converting a floating-point number to an integer. Improved data storage: Type conversions can be used to store data in a more compact form, such as converting a large integer value to a smaller integer type, or converting a large floating-point value to a smaller floating-point type. Disadvantages of type conversions in C programming: Loss of precision: Converting data from a larger data type to a smaller data type can result in loss of precision, as some of the data may be truncated. Overflow or underflow: Converting data from a smaller data type to a larger data type can result in overflow or underflow if the value being converted is too large or too small for the new data type. Unexpected behavior: Type conversions can lead to unexpected behavior, such as when converting between signed and unsigned integer types, or when converting between floating-point and integer types. Confusing syntax: Type conversions can have confusing syntax, particularly when using typecast operators or type conversion functions, making the code more difficult to read and understand. Increased complexity: Type conversions can increase the complexity of your code, making it harder to debug and maintain. 112 NOTES OF C & C++ BY XHK BASHARAT...... Slower performance: Type conversions can sometimes result in slower performance, particularly when converting data between complex data types, such as between structures and arrays. Basic Input and Output in C C language has standard libraries that allow input and output in a program. The stdio.h or standard input output library in C that has methods for input and output. scanf() The scanf() method, in C, reads the value from the console as per the type specified and store it in the given address. Syntax: scanf("%X", &variableOfXType); where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and & is the address operator in C, which tells the compiler to change the real value of variableOfXType, stored at this address in the memory. printf() The printf() method, in C, prints the value passed as the parameter to it, on the console screen. Syntax: printf("%X", variableOfXType); where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and variableOfXType is the variable to be printed. How to take input and output of basic types in C? The basic type in C includes types like int, float, char, etc. Inorder to input or output the specific type, the X in the above syntax is changed with the specific format specifier of that type. The Syntax for input and output for these are: Integer: Input: scanf("%d", &intVariable); Output: printf("%d", intVariable); Float: Input: scanf("%f", &floatVariable); Output: printf("%f", floatVariable); Character: Input: scanf("%c", &charVariable); 113 NOTES OF C & C++ BY XHK BASHARAT...... Output: printf("%c", charVariable); Please refer Format specifiers in C for more examples. C // C program to show input and output #include int main() { // Declare the variables int num; char ch; float f; // --- Integer --- // Input the integer printf("Enter the integer: "); scanf("%d", &num); // Output the integer printf("\nEntered integer is: %d", num); // --- Float --- //For input Clearing buffer while((getchar()) != '\n'); // Input the float printf("\n\nEnter the float: "); 114 NOTES OF C & C++ BY XHK BASHARAT...... scanf("%f", &f); // Output the float printf("\nEntered float is: %f", f); // --- Character --- // Input the Character printf("\n\nEnter the Character: "); scanf("%c", &ch); // Output the Character printf("\nEntered character is: %c", ch); return 0; } Output Enter the integer: 10 Entered integer is: 10 Enter the float: 2.5 Entered float is: 2.500000 Enter the Character: A Entered Character is: A How to take input and output of advanced type in C? The advanced type in C includes type like String. In order to input or output the string type, the X in the above syntax is changed with the %s format specifier. The Syntax for input and output for String is: Input: scanf("%s", stringVariable); Output: printf("%s", stringVariable); 115 NOTES OF C & C++ BY XHK BASHARAT...... Example: C // C program to show input and output #include int main() { // Declare string variable // as character array char str; // --- String --- // To read a word // Input the Word printf("Enter the Word: "); scanf("%s\n", str); // Output the Word printf("\nEntered Word is: %s", str); // --- String --- // To read a Sentence // Input the Sentence printf("\n\nEnter the Sentence: "); scanf("%[^\n]s", str); // Output the String 116 NOTES OF C & C++ BY XHK BASHARAT...... printf("\nEntered Sentence is: %s", str); return 0; } Output Enter the Word: GeeksForGeeks Entered Word is: GeeksForGeeks Enter the Sentence: Geeks For Geeks Entered Sentence is: Geeks For Geeks Format Specifiers in C The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different data types such as %d for int, %c for char, etc. In this article, we will discuss some commonly used format specifiers and how to use them. List of Format Specifiers in C The below table contains the most commonly used format specifiers in C Format Specifier Description %c For character type. %d For signed integer type. %e or %E For scientific notation of floats. %f For float type. 117 NOTES OF C & C++ BY XHK BASHARAT...... Format Specifier Description %g or %G For float type with the current precision. %i signed integer %ld or %li Long %lf Double %Lf Long double %lu Unsigned int or unsigned long %lli or %lld Long long %llu Unsigned long long %o Octal representation %p Pointer %s String %u Unsigned int %x or %X Hexadecimal representation %n Prints nothing %% Prints % character 118 NOTES OF C & C++ BY XHK BASHARAT...... Examples of Format Specifiers in C 1. Character Format Specifier – %c in C The %c is the format specifier for the char data type in C language. It can be used for both formatted input and formatted output in C language. Syntax: scanf("%d...",...); printf("%d...",...); Example: C // C Program to illustrate the %c format specifier. #include int main() { char c; // using %c for character input scanf("Enter some character: %c", &c); // using %c for character output printf("The entered character: %c", &c); return 0; } Input: Enter some character: A Output: The entered character: A 2. Integer Format Specifier (signed) – %d in C We can use the signed integer format specifier %d in the scanf() and print() functions or other functions that use formatted string for input and output of int data type. Syntax: 119 NOTES OF C & C++ BY XHK BASHARAT...... scanf("%d...",...); printf("%i...",...); Example: C // C Program to demonstrate the use of %d and %i #include // Driver code int main() { int x; // taking integer input scanf("Enter the two integers: %d", &x); // printing integer output printf("Printed using %%d: %d\n", x); printf("Printed using %%i: %3i\n", x); return 0; } Input: Enter the integer: 45 Output: Printed using %d: 45 Printed using %i: 45 3. Unsigned Integer Format Specifier – %u in C The %u is the format specifier for the unsigned integer data type. If we specify a negative integer value to the %u, it converts the integer to its first complement. Syntax: printf("%u...",...); scanf("%u...",...); Example: The following C Program demonstrates how to use %u in C. C 120 NOTES OF C & C++ BY XHK BASHARAT...... // C Program to illustrate the how to use %u #include // driver code int main() { unsigned int var; scanf("Enter an integer: %u", &var); printf("Entered Unsigned Integer: %u", var); // trying to print negative value using %u printf("Printing -10 using %%u: %u\n", -10); return 0; } Input: Enter an integer: 25 Output: Entered unsigned integer: 25 Printing -10 using %u: 4294967286 4. Floating-point format specifier – %f in C The %f is the floating point format specifier in C language that can be used inside the formatted string for input and output of float data type. Apart from %f, we can use %e or %E format specifiers to print the floating point value in the exponential form. Syntax: printf("%f...",...); scanf("%e...",...); printf("%E...",...); Example: C // C program to demonstrate the use of %f, %e and %E 121 NOTES OF C & C++ BY XHK BASHARAT...... #include // driver code int main() { float a = 12.67; printf("Using %%f: %f\n", a); printf("Using %%e: %e\n", a); printf("Using %%E, %E", a); return 0; } Output Using %f: 12.670000 Using %e: 1.267000e+01 Using %E, 1.267000E+01 5. Unsigned Octal number for integer – %o in C We can use the %o format specifier in the C program to print or take input for the unsigned octal integer number. Syntax: printf("%o...",...); scanf("%o...",...); Example: C #include int main() { int a = 67; printf("%o\n", a); return 0; } 122 NOTES OF C & C++ BY XHK BASHARAT...... Output 103 6. Unsigned Hexadecimal for integer – %x in C The %x format specifier is used in the formatted string for hexadecimal integers. In this case, the alphabets in the hexadecimal numbers will be in lowercase. For uppercase alphabet digits, we use %X instead. Syntax: printf("%x...",...); scanf("%X...",...); Example: C // C Program to demonstrate the use of %x and %X #include int main() { int a = 15454; printf("%x\n", a); printf("%X", a); return 0; } Output 3c5e 3C5E 7. String Format Specifier – %s in C The %s in C is used to print strings or take strings as input. Syntax: printf("%s...",...); scanf("%s...",...); Example: C // C program to illustrate the use of %s in C 123 NOTES OF C & C++ BY XHK BASHARAT...... #include int main() { char a[] = "Hi Geeks"; printf("%s\n", a); return 0; } Output Hi Geeks Example: The working of %s with scanf() is a little bit different from its working with printf(). Let’s understand this with the help of the following C program. C // C Program to illustrate the working of %s with scanf() #include int main() { char str; // taking string as input scanf("Enter the String: %s", str); printf("Entered String: %s", str); return 0; } Input Enter the string: Hi Geeks Output 124 NOTES OF C & C++ BY XHK BASHARAT...... Hi As we can see, the string is only scanned till a whitespace is encountered. We can avoid that by using scansets in C. 8. Address Format Specifier – %p in C The C language also provides the format specifier to print the address/pointers. We can use %p to print addresses and pointers in C Syntax printf("%p...",...); Example: C #include int main() { int a = 10; printf("The Memory Address of a: %p\n",(void*)&a); return 0; } Output The Memory Address of a: 0x7ffe9645b3fc Input and Output Formatting C language provides some tools using which we can format the input and output. They are generally inserted between the % sign and the format specifier symbol Some of them are as follows: 1. A minus(-) sign tells left alignment. 2. A number after % specifies the minimum field width to be printed if the characters are less than the size of the width the remaining space is filled with space and if it is greater then it is printed as it is without truncation. 3. A period(. ) symbol separates field width with precision. Precision tells the minimum number of digits in an integer, the maximum number of characters in a string, and the number of digits after the decimal part in a floating value. Example of I/O Formatting C // C Program to demonstrate the formatting methods. 125 NOTES OF C & C++ BY XHK BASHARAT...... #include int main() { char str[] = "geeksforgeeks"; printf("%20s\n", str); printf("%-20s\n", str); printf("%20.5s\n", str); printf("%-20.5s\n", str); return 0; } Output geeksforgeeks geeksforgeeks geeks geeks Format Specifiers in C – FAQs Does C have a format specifier for binary numbers? No, the C language does not provide a format specifier for binary numbers. What is the formatted string? The input and output functions in C take a string as an argument that decides how the data is displayed on the screen or the data is retrieved to the memory. This string is called the formatted string. printf in C In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library and it can allow formatting the output in numerous ways. Syntax of printf printf ( "formatted_string", arguments_list); Parameters formatted_string: It is a string that specifies the data to be printed. It may also contain a format specifier to print the value of any variable such as a character and an integer. arguments_list: These are the variable names corresponding to the format specifier. 126 NOTES OF C & C++ BY XHK BASHARAT...... Return Value printf() returns the number of characters printed after successful execution. If an error occurs, a negative value is returned. Example of printf In this example, we are printing the string “Hello Geek!” in the output using printf() function. In printf() function what we will write inside the double quotes (” “) is printed in the output. C // C program to illustrate the use of printf function #include int main() { // using printf to print "Hello Geek!" printf("Hello Geek!"); return 0; } Output Hello Geek! Formatting in C printf In C, a value can be a character type, integer type, float type, and so on. To display and format these values using printf, we have format specifiers that are used in the formatted string. These format specifiers start with the percentage symbol ‘%’. Syntax of Format Specifier %[flags][width][.precision][length]specifier 1. Specifier It is the character that denotes the type of data. Some commonly used specifiers are: %d: for printing integers %f: for printing floating-point numbers %c: for printing characters %s: for printing strings 127 NOTES OF C & C++ BY XHK BASHARAT...... %p: for printing memory addresses %x: for printing hexadecimal values Example printf("%c", char_variable); 2. Width It is the sub-specifier that denotes the minimum number of characters that will be printed. If the number of characters is less than the specified width, the white space will be used to fill the remaining characters’ places. But if the number of characters is greater than the specified width, all the characters will be still printed without cutting off any. Example printf("%25s", some_string); or printf("%*s", 25, some_string); 3. Precision Precision subspecifier meaning differs for different format specifiers it is being used with. For Integral data(d, i, u, o, x, X): Specifies the minimum number of digits to be printed. But unlike the width sub-specifier, instead of white spaces, this sub-specifier adds leading zeroes to the number. If the number has more digits than the precision, the number is printed as it is. For Float or Double Data(f, e, a, A): Specifies the number of digits to be printed after the decimal point. For String (s): Specifies the length of the string to be printed. Example printf("%.10d", some_integer); printf("%.3f", some_float); printf("%.25s", some_string); or printf("%.*d", 10, some_integer); printf("%.*f", 3, some_float); printf("%.*s", 25, some_string); 4. Length Specifies the length of the data type in the memory. It is used in correspondence with data type modifiers. 128 NOTES OF C & C++ BY XHK BASHARAT...... There are 3 length sub-specifiers: h: With short int and unsigned short int l: With long int and unsigned long int. L: With long double Example printf("%lf", double_variable); Examples of printf() in C Example 1: Print a Variable using Specifier in printf() In this example, we are printing an integer using a format specifier “%d” which is used for an integer. In the printf() function we are printing integers along with string using %d and in the arguments, we have passed variable names in a sequence corresponding to their format specifiers. C // C program to print a variable #include int main() { int num1 = 99; int num2 = 1; printf("The sum of %d and %d is %d\n", num1, num2, num1 + num2); return 0; } Output The sum of 99 and 1 is 100 Example 2: printf with Specified Width In this example, we will specify the width of the output which will be printed by the printf() function. C // C program to illustrate the use of printf with width // specifier 129 NOTES OF C & C++ BY XHK BASHARAT...... #include int main() { // number to be printed int num = 123456; // printing the num with 10 width and getting the // printed characters in char_printed printf("Printing num with width 10: "); int chars_printed = printf("%10d", num); printf("\nNumber of characters printed: %d", chars_printed); // specifying with using other method printf("\nPrinting num with width 3: "); chars_printed = printf("%*d", 3, num); printf("\nNumber of characters printed: %d", chars_printed); return 0; } Output Printing num with width 10: 123456 Number of characters printed: 10 Printing num with width 3: 123456 Number of characters printed: 6 As we can see, even if we define the width that is less than the present characters, all the characters are still printed. Also, we have seen the two ways in which we can define the width. Example 3: printf with Precision Sub-Specifier In this example, we will demonstrate the precision sub-specifier in the printf() function C 130 NOTES OF C & C++ BY XHK BASHARAT...... // C program to illustrate the use of precision // sub-specifier #include int main() { int num = 2451; float dec = 12.45126; char* str = "GeeksforGeeks"; // precision for integral data printf("For integers: %.10d\n", num); // precision for numbers with decimal points printf("For floats: %.2f\n", dec); // for strings printf("For strings: %.5s", str); return 0; } Output For integers: 0000002451 For floats: 12.45 For strings: Geeks Example 4: printf with Length Sub-Specifier C 131 NOTES OF C & C++ BY XHK BASHARAT...... // C program to illustrate the length modifier #include int main() { long var = 3000000000; // printing var using %d printf("Using %%d: %d", var); // printing var using %ld printf("\nUsing %%ld: %ld", var); return 0; } Output Using %d: -1294967296 Using %ld: 3000000000 scanf in C In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input. scanf also uses format specifiers like printf. scanf Syntax The syntax of scanf() in C is similar to the syntax of printf(). int scanf( const char *format,... ); Here, int is the return type. format is a string that contains the format specifiers(s). “…” indicates that the function accepts a variable number of arguments. Example format specifiers recognized by scanf: 132 NOTES OF C & C++ BY XHK BASHARAT...... %d to accept input of integers. %ld to accept input of long integers %lld to accept input of long long integers %f to accept input of real number. %c to accept input of character types. %s to accept input of a string. To know more about format specifiers, refer to this article – Format Specifiers in C Example: int var; scanf(“%d”, &var); The scanf will write the value input by the user into the integer variable var. Return Value of scanf The scanf in C returns three types of values: >0: The number of values converted and assigned successfully. 0: No value was assigned. b the right operand. Else 2 false Returns true if the left operand Less than or is less than or = b equal to equal to right operand. Else 4 false 155 NOTES OF C & C++ BY XHK BASHARAT...... S. No. Symbol Operator Description Syntax Returns true if both the == Equal to a == b operands are 5 equal. Returns true if both the != Not equal to a != b operands are 6 NOT equal. Example of C Relational Operators C // C program to illustrate the relational operators #include int main() { int a = 25, b = 5; // using operators and printing results printf("a < b : %d\n", a < b); printf("a > b : %d\n", a > b); printf("a = b: %d\n", a >= b); printf("a == b: %d\n", a == b); printf("a != b : %d\n", a != b); return 0; } Output 156 NOTES OF C & C++ BY XHK BASHARAT...... ab :1 a = b: 1 a == b: 0 a != b : 1 Here, 0 means false and 1 means true. 3. Logical Operator in C Logical Operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a Boolean value either true or false. S. No. Symbol Operator Description Syntax Returns true if both the && Logical AND a && b operands are 1 true. Returns true if both or any of || Logical OR a || b the operand is 2 true. Returns true if ! Logical NOT the operand is !a 3 false. Example of Logical Operators in C C // C program to illustrate the logical operators #include int main() 157 NOTES OF C & C++ BY XHK BASHARAT...... { int a = 25, b = 5; // using operators and printing results printf("a && b : %d\n", a && b); printf("a || b : %d\n", a || b); printf("!a: %d\n", !a); return 0; } Output a && b : 1 a || b : 1 !a: 0 4. Bitwise Operators in C The Bitwise operators are used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for faster processing. There are 6 bitwise operators in C: S. No. Symbol Operator Description Syntax Performs bit-by- bit AND & Bitwise AND operation and a&b returns the 1 result. | Bitwise OR Performs bit-by- a|b 2 bit OR operation 158 NOTES OF C & C++ BY XHK BASHARAT...... S. No. Symbol Operator Description Syntax and returns the result. Performs bit-by- bit XOR operation ^ Bitwise XOR a^b and returns the 3 result. Flips all the set Bitwise First ~ and unset bits on ~a Complement 4 the number. Shifts the number in binary form by one place in the a >> b Rightshilft operation and returns the 6 result. Example of Bitwise Operators C // C program to illustrate the bitwise operators #include int main() { 159 NOTES OF C & C++ BY XHK BASHARAT...... int a = 25, b = 5; // using operators and printing results printf("a & b: %d\n", a & b); printf("a | b: %d\n", a | b); printf("a ^ b: %d\n", a ^ b); printf("~a: %d\n", ~a); printf("a >> b: %d\n", a >> b); printf("a >= b: %d\n", a >>= b); printf("a 1 = %d\n", x >> 1); return 0; } Output x > 1 = 9 Time Complexity: O(1) Auxiliary Space: O(1) 6. The & operator can be used to quickly check if a number is odd or even. 193 NOTES OF C & C++ BY XHK BASHARAT...... The value of the expression (x & 1) would be non-zero only if x is odd, otherwise, the value would be zero. Example The below example demonstrates the use bitwise & operator to find if the given number is even or odd. C #include int main() { int x = 19; (x & 1) ? printf("Odd") : printf("Even"); return 0; } Output Odd Time Complexity: O(1) Auxiliary Space: O(1) 7. The ~ operator should be used carefully. The result of the ~ operator on a small number can be a big number if the result is stored in an unsigned variable. The result may be a negative number if the result is stored in a signed variable (assuming that the negative numbers are stored in 2’s complement form where the leftmost bit is the sign bit). Example The below example demonstrates the use of bitwise NOT operator. C // C program to demonstrate the use of bitwise NOT operator. #include int main() { 194 NOTES OF C & C++ BY XHK BASHARAT...... unsigned int x = 1; printf("Signed Result %d \n", ~x); printf("Unsigned Result %u \n", ~x); return 0; } Output Signed Result -2 Unsigned Result 4294967294 Time Complexity: O(1) Auxiliary Space: O(1) Note The output of the above program is compiler dependent C Logical Operators Logical operators in C are used to combine multiple conditions/constraints. Logical Operators returns either 0 or 1, it depends on whether the expression result is true or false. In C programming for decision-making, we use logical operators. We have 3 logical operators in the C language: Logical AND ( && ) Logical OR ( || ) Logical NOT ( ! ) Types of Logical Operators 1. Logical AND Operator ( && ) The logical AND operator (&&) returns true only if both operands are non-zero. Otherwise, it returns false (0). The return type of the result is int. Below is the truth table for the logical AND operator. X Y X && Y 1 1 1 1 0 0 0 1 0 195 NOTES OF C & C++ BY XHK BASHARAT...... X Y X && Y 0 0 0 Syntax (operand_1 && operand_2) Example C // C program for Logical // AND Operator #include // Driver code int main() { int a = 10, b = 20; if (a > 0 && b > 0) { printf("Both values are greater than 0\n"); } else { printf("Both values are less than 0\n"); } return 0; } Output Both values are greater than 0 2. Logical OR Operator ( || ) The logical OR operator returns true if any one of the operands is non-zero. Otherwise, it returns false i.e., 0 as the value. Below is the truth table for the logical OR operator. 196 NOTES OF C & C++ BY XHK BASHARAT...... X Y X || Y 1 1 1 1 0 1 0 1 1 0 0 0 Syntax (operand_1 || operand_2) Example C // C program for Logical // OR Operator #include // Driver code int main() { int a = -1, b = 20; if (a > 0 || b > 0) { printf("Any one of the given value is " "greater than 0\n"); } else { printf("Both values are less than 0\n"); } return 0; 197 NOTES OF C & C++ BY XHK BASHARAT...... } Output Any one of the given value is greater than 0 3. Logical NOT Operator ( ! ) If the given operand is true then the logical NOT operator will make it false and vice-versa. Below is the truth table for the logical NOT operator. X !X 0 1 1 0 Syntax !(operand_1 && operand_2) Example C // C program for Logical // NOT Operator #include // Driver code int main() { int a = 10, b = 20; if (!(a > 0 && b > 0)) { // condition returned true but // logical NOT operator changed // it to false printf("Both values are greater than 0\n"); } 198 NOTES OF C & C++ BY XHK BASHARAT...... else { printf("Both values are less than 0\n"); } return 0; } Short Circuit Logical Operators When the result can be determined by evaluating the preceding Logical expression without evaluating the further operands, it is known as short-circuiting. Short-circuiting can be seen in the equation having more than one Logical operator. They can either AND, OR, or both. 1. Short Circuiting in Logical AND Operator The logical AND operator returns true if and only if all operands evaluate to true. If the first operand is false, then the further operands will not be evaluated. This is because even if the further operands evaluate to true, the entire condition will still return false. Example C++ // C++ Program to illustrate short circuiting in Logical AND #include using namespace std; // utility function to check positive bool is_positive(int number) { if (number > 0) return true; else return false; } // utility function to check if the number is even bool is_even(int number) { if (number % 2 == 0) 199 NOTES OF C & C++ BY XHK BASHARAT...... return true; else return false; } // driver code int main() { int x = 10; // Both conditions are evaluated if (is_positive(x) && is_even(x)) { cout ' // is left to right. Therefore the value becomes ((30 > 20) > 10) // which becomes (1 > 10) if (c > b > a) printf("TRUE"); else printf("FALSE"); return 0; } Output FALSE Decision Making in C (if , if..else, Nested if, if-else-if ) The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision- making statements in programming languages decide the direction of the flow of program execution. Need of Conditional Statements There come situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code. For example, in C if x occurs then execute y else execute z. There can also be multiple conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r. This condition of C else-if is one of the many ways of importing multiple conditions. Types of Conditional Statements in C Following are the decision-making statements available in C: 1. if Statement 2. if-else Statement 3. Nested if Statement 4. if-else-if Ladder 5. switch Statement 228 NOTES OF C & C++ BY XHK BASHARAT...... 6. Conditional Operator 7. Jump Statements: break continue goto return Let’s discuss each of them one by one. 1. if in C The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statements is executed otherwise not. Syntax of if Statement if(condition) { // Statements to execute if // condition is true } Here, the condition after evaluation will be either true or false. C if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement will consider the first immediately below statement to be inside its block. Flowchart of if Statement Flow Diagram of if Statement Example of if in C C // C program to illustrate If statement #include 229 NOTES OF C & C++ BY XHK BASHARAT...... int main() { int i = 10; if (i > 15) { printf("10 is greater than 15"); } printf("I am Not in if"); } Output I am Not in if As the condition present in the if statement is false. So, the block below the if statement is not executed. 2. if-else in C The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else when the condition is false? Here comes the C else statement. We can use the else statement with the if statement to execute a block of code when the condition is false. The if-else statement consists of two blocks, one for false expression and one for true expression. Syntax of if else in C if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false } 230 NOTES OF C & C++ BY XHK BASHARAT...... Flowchart of if-else Statement Flow Diagram of if else Example of if-else C // C program to illustrate If statement #include int main() { int i = 20; if (i < 15) { printf("i is smaller than 15"); } else { printf("i is greater than 15"); } return 0; } Output i is greater than 15 The block of code following the else statement is executed as the condition present in the if statement is false. 231 NOTES OF C & C++ BY XHK BASHARAT...... 3. Nested if-else in C A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Yes, C allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement. Syntax of Nested if-else if (condition1) { // Executes when condition1 is true if (condition_2) { // statement 1 } else { // Statement 2 } } else { if (condition_3) { // statement 3 } else { // Statement 4 } } The below flowchart helps in visualize the above syntax. Flowchart of Nested if-else Example of Nested if-else C // C program to illustrate nested-if statement #include 232 NOTES OF C & C++ BY XHK BASHARAT...... int main() { int i = 10; if (i == 10) { // First if statement if (i < 15) printf("i is smaller than 15\n"); // Nested - if statement // Will only be executed if statement above // is true if (i < 12) printf("i is smaller than 12 too\n"); else printf("i is greater than 15"); } else { if (i == 20) { // Nested - if statement // Will only be executed if statement above // is true if (i < 22) printf("i is smaller than 22 too\n"); else printf("i is greater than 25"); } } 233 NOTES OF C & C++ BY XHK BASHARAT...... return 0; } Output i is smaller than 15 i is smaller than 12 too 4. if-else-if Ladder in C The if else if statements are used when the user has to decide among multiple options. The C if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. if-else-if ladder is similar to the switch statement. Syntax of if-else-if Ladder if (condition) statement; else if (condition) statement;.. else statement; Flowchart of if-else-if Ladder Flow Diagram of if-else-if Example of if-else-if Ladder C // C program to illustrate nested-if statement #include 234 NOTES OF C & C++ BY XHK BASHARAT...... int main() { int i = 20; if (i == 10) printf("i is 10"); else if (i == 15) printf("i is 15"); else if (i == 20) printf("i is 20"); else printf("i is not present"); } Output i is 20 5. switch Statement in C The switch case statement is an alternative to the if else if ladder that can be used to execute the conditional code based on the value of the variable specified in the switch statement. The switch block consists of cases to be executed based on the value of the switch variable. Syntax of switch switch (expression) { case value1: statements; case value2: statements;............ default: statements; 235 NOTES OF C & C++ BY XHK BASHARAT...... } Note: The switch expression should evaluate to either integer or character. It cannot evaluate any other data type. Flowchart of switch Flowchart of switch in C Example of switch Statement C // C Program to illustrate the use of switch statement #include int main() { // variable to be u