Lecture Notes 1 - Introduction and Importance of C PDF

Document Details

FancyDialogue

Uploaded by FancyDialogue

Rayat Bahra University

Tags

C programming computer science programming languages computer programming

Summary

These lecture notes provide an introduction to the C programming language, covering its fundamental concepts, history and characteristics. "Computer Programming in C" by Sunstone provides a detailed explanation of why C is a popular choice for system development.

Full Transcript

Computer Programming in C LECTURE 1 NOTES Introduction and Importance of C Overview of the Language's Fundamentals ▪ C is a general−purpose, high−level language that was originally developed by American computer scientist Dennis M. Ritchie to develop the UNIX operating...

Computer Programming in C LECTURE 1 NOTES Introduction and Importance of C Overview of the Language's Fundamentals ▪ C is a general−purpose, high−level language that was originally developed by American computer scientist Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. It was originally first implemented on the DEC PDP-11 computer in 1972. ▪ In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. ▪ The UNIX operating system, the C compiler, and essentially all UNIX application programs have been written in C. It has now become a widely used professional language for various reasons: ○ It is easy to learn ○ It is a structured language ○ It produces efficient programs ○ It can handle low−level activities ○ It can be compiled on a variety of computer platforms ▪ Facts about C ○ C was invented to write an operating system called UNIX. ○ C is a successor of B language which was introduced around the early 1970s. ○ The language was formalized in 1988 by the American National Standard Institute (ANSI). ○ The UNIX OS was totally written in C. ○ Today C is the most widely used and popular System Programming Language. ○ Most of the state-of-the-art software have been implemented using C. ○ Today's most popular Linux OS and RDBMS MySQL have been written in C. ▪ Why Use C Language? ○ C was initially used for system development work, particularly the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as the code written in assembly language. ○ Some examples of the use of C are: Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Databases Language Interpreters Utilities C's Role in Programming History ▪ C (pronounced /ˈsiː/ – like the letter c) is a general-purpose programming language. By design, C's features cleanly reflect the capabilities of the targeted CPUs. It has found lasting use in operating systems, device drivers, and protocol stacks, but its use in application software has been decreasing. C is commonly used on computer architectures that range from the largest supercomputers to the smallest microcontrollers and embedded systems. ▪ A successor to the programming language B, C was originally developed at Bell Labs by Dennis M. Ritchie between 1972 and 1973 to construct utilities running on Unix. It was applied to re-implementing the kernel of the Unix operating system. During the 1980s, C gradually gained popularity. It has become one of the most widely used programming languages, with C compilers available for practically all modern computer architectures and operating systems. The book The C Programming Language, co-authored by the original language designer, served for many years as the de facto standard for the language. C has been standardized since 1989 by the American National Standards Institute (ANSI) and, subsequently, jointly by the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC). ▪ C is an imperative procedural language, supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support. Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant C program written with portability in mind can be compiled for a wide variety of computer platforms and operating systems with few changes to its source code. ▪ Since 2000, C has consistently ranked among the top two languages in the TIOBE index, a measure of the popularity of programming languages. Features and Characteristics ▪ The core features of a programming language describe its ability and uniqueness and how beneficial it can be in developing a website or software. Listed below are some of the significant features of C language: ⮚ Simple and Efficient ○ The basic syntax style of implementing C language is very simple and easy to learn. This makes the language easily comprehensible and enables a programmer to redesign or create a new application. C is usually used as an introductory language to introduce programming to school students because of this feature. ⮚ Fast ○ It is a well-known fact that statically typed programming languages are faster than dynamic ones. C is a statically typed programming language, which gives it an edge over other dynamic languages. Also, unlike Java and Python, which are interpreter-based, C is a compiler-based program. This makes the compilation and execution of codes faster. ○ Another factor that makes C fast is the availability of only the essential and required features. Newer programming languages come with numerous features, which increase functionality but reduce efficiency and speed. Since C offers limited but essential features, the headache of processing these features reduces, resulting in increased speed. ⮚ Portability ○ Another feature of the C language is portability. To put it simply, C programs are machine-independent which means that you can run the fraction of a code created in C on various machines with none or some machine-specific changes. Hence, it provides the functionality of using a single code on multiple systems depending on the requirement. ⮚ Extensibility ○ You can easily (and quickly) extend a C program. This means that if a code is already written, you can add new features to it with a few alterations. Basically, it allows adding new features, functionalities, and operations to an existing C program. ⮚ Function-Rich Libraries ○ C comes with an extensive set of libraries with several built-in functions that make the life of a programmer easy. Even a beginner can easily code using these built-in functions. You can also create your user-defined functions and add them to C libraries. The availability of such a vast scope of functions and operations allows a programmer to build a vast array of programs and applications. ⮚ Dynamic Memory Management ○ One of the most significant features of C language is its support for dynamic memory management (DMA). It means that you can utilize and manage the size of the data structure in C during runtime. C also provides several predefined functions to work with memory allocation. For instance, you can use the free() function to free up the allocated memory at any time. Similarly, there are other functions such as malloc(), calloc(), and realloc() to perform operations on data structure and memory allocations. ⮚ Modularity With Structured Language ○ C is a general-purpose structured language. This feature of C language allows you to break a code into different parts using functions which can be stored in the form of libraries for future use and reusability. Structuring the code using functions increases the visual appeal and makes the program more organized and less prone to errors. ⮚ Mid-Level Programming Language ○ Although C was initially developed to do only low-level programming, it now also supports the features and functionalities of high-level programming, making it a mid-level language. And as a mid-level programming language, it provides the best of both worlds. For instance, C allows direct manipulation of hardware, which high-level programming languages do not offer. Difference between Procedural Programming and Object-oriented Languages ⮚ Procedural Programming ○ Procedural Programming can be defined as a programming model which is derived from structured programming, based upon the concept of calling procedure. Procedures, also known as routines, subroutines or functions, simply consist of a series of computational steps to be carried out. During a program’s execution, any given procedure might be called at any point, including by other procedures or itself. ○ Languages used in Procedural Programming: FORTRAN, ALGOL, COBOL, BASIC, Pascal and C. ⮚ Object-Oriented Programming ○ Object-oriented programming can be defined as a programming model which is based upon the concept of objects. Objects contain data in the form of attributes and code in the form of methods. In object-oriented programming, computer programs are designed using the concept of objects that interact with the real world. Object-oriented programming languages are various but the most popular ones are class-based, meaning that objects are instances of classes, which also determine their types. ○ Languages used in Object-Oriented Programming: Java, C++, C#, Python, PHP, JavaScript, Ruby, Perl, Objective-C, Dart, Swift, Scala. Procedural Oriented Programming Object-Oriented Programming In procedural programming, the program is In object-oriented programming, the program is divided into small parts called functions. divided into small parts called objects. Procedural programming follows a top-down Object-oriented programming follows a approach. bottom-up approach. There is no access specifier in procedural Object-oriented programming has access programming. specifiers like private, public, protected, etc. Adding new data and functions is not easy. Adding new data and functions is easy. Procedural programming does not have any Object-oriented programming provides data proper way of hiding data so it is less secure. hiding so it is more secure. In procedural programming, overloading is not Overloading is possible in object-oriented possible. programming. In procedural programming, there is no concept In object-oriented programming, the concept of of data hiding and inheritance. data hiding and inheritance is used. In procedural programming, the function is more In object-oriented programming, data is more important than the data. important than function. Procedural programming is based on the unreal Object-oriented programming is based on the world. real world. Procedural programming is used for designing Object-oriented programming is used for medium-sized programs. designing large and complex programs. Procedural programming uses the concept of Object-oriented programming uses the concept procedure abstraction. of data abstraction. Code reusability absent in procedural Code reusability present in object-oriented programming, programming. Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc. Significance of C in Contemporary Programming ▪ C programming language, despite its age, continues to hold significant importance in contemporary programming for several reasons: ⮚ System-Level Programming ○ C is widely used for system-level programming, such as developing operating systems, embedded systems, and real-time systems. Its ability to directly manipulate hardware and memory provides the necessary control for such low-level tasks. Notable examples include the Unix and Linux operating systems, which are primarily written in C. ⮚ Performance and Efficiency ○ C offers high performance and efficient use of resources. Programs written in C typically run faster and use less memory than those written in higher-level languages. This efficiency makes C an ideal choice for performance-critical applications, such as game development, high-frequency trading systems, and scientific computing. ⮚ Portability and Cross-Platform Development ○ C code is highly portable and can be compiled and run on virtually any machine with a C compiler. This makes it a preferred language for developing cross-platform software. The language's standard library provides a common interface for different hardware and operating systems. ⮚ Foundation for Other Languages ○ Many modern programming languages, such as C++, Java, and Python, have their roots in C or borrow heavily from its syntax and concepts. Learning C provides a strong foundation for understanding these and other languages, as well as key programming concepts like pointers, memory management, and data structures. ⮚ Embedded Systems ○ C remains the dominant language for programming embedded systems, which are specialized computing systems that perform dedicated functions within larger systems. These are found in a wide range of devices, from household appliances to industrial machines and medical equipment. ⮚ Legacy Code and Maintenance ○ A vast amount of legacy code is written in C, especially in critical infrastructure and systems. Maintaining and updating this code requires a good understanding of C. Many industries, including finance, telecommunications, and defense, continue to rely on C for maintaining their existing software. Computer Programming in C LECTURE 2 NOTES Basic Structure of C Program and Tokens Components including Main Function, Headers, and Comments ▪ A function in C is a block of organized reusable code that performs a single related action. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. ▪ When the algorithm of a certain problem involves long and complex logic, it is broken into smaller, independent and reusable blocks. These small blocks of code are known by different names in different programming languages such as a module, a subroutine, a function or a method. ▪ A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. ▪ The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. ⮚ Library Functions in C ○ C offers a number of library functions included in different header files. For example, the stdio.h header file includes printf() and scanf() functions. Similarly, the math.h header file includes a number of functions such as sin(), pow(), sqrt() and more. ○ These functions perform a predefined task and can be called upon in any program as per requirement. However, if you don't find a suitable library function to serve your purpose, you can define one. ⮚ Defining a Function in C ○ In C, it is necessary to provide the forward declaration of the prototype of any function. The prototype of a library function is present in the corresponding header file. ○ For a user-defined function, its prototype is present in the current program. The definition of a function and its prototype declaration should match. ○ After all the statements in a function are executed, the flow of the program returns to the calling environment. The function may return some data along with the flow control. ⮚ Function Declarations in C ○ A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. ○ A function declaration has the following parts − return_type function_name(parameter list); ○ For the above defined function max(), the function declaration is as follows − int max(int num1, int num2); ○ Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration − int max(int, int); ○ A function declaration is required when you define a function in one source file and you call that function in another file. In such cases, you should declare the function at the top of the file calling the function. ⮚ Parts of a Function in C ○ The general form of a function definition in C programming language is as follows − return_type function_name(parameter list){ body of the function } ○ A function definition in C programming consists of a function header and a function body. Here are all the parts of a function − Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Argument List − An argument (also called parameter) is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body − The function body contains a collection of statements that defines what the function does. ⮚ Comments ○ Any programming language, including C, is less verbose as compared to any human language like English. It has far less number of keywords, C being one of the smallest languages with only 32 keywords. Hence, the instructions in a C program can be difficult to understand, especially for someone with a non-programming background. ○ The C language syntax also varies and is also complicated. Usually, the programmer tries to add complexity to optimize the code. However, it makes the code hard to understand. Comments provide a useful explanation and convey the intention behind the use of a particular approach. ○ Types of Comments in C Single-line comments Multi-line comments Single-line Comment in C The C++-style single-line comments were incorporated in C compilers with C99 standards. If any text begins with the // symbol, the rest of the line is treated as a comment. The text followed by a double oblique or forward slash [//] in a code is treated as a single-line comment. All that text after // is ignored by the C compiler during compilation. Unlike the multi-line or block comment, it need not be closed. Syntax of Single-line C Comment ○ //comment text The // symbol can appear anywhere. It indicates that all the text following it till the end of the line is a comment. The subsequent line in the editor is again a place to write a valid C statement. Multi-line Comment in C In early versions of C (ANSI C), any length of text put in between the symbols is treated as a comment. The text may be spread across multiple lines in the code file. You may call it a multi-line comment. A block of consecutive lines is treated as a comment. Syntax of Multi-line C Comment ○ The general structure of a multi-line comment is as follows − Identifiers, keywords, constants, strings, and symbols ▪ Tokens in C: A token is the smallest element of the program that is meaningful to the compiler. ▪ Tokens in C can be classified as follows: ○ Keywords ○ Identifiers ○ Constants ○ Strings ○ Special symbols ○ Operators ⮚ Keywords ○ Keywords are pre-defined (or) reserved words in a programming language. Each keyword is meant to perform specific functions in a program. And we cannot redefine the keywords. C language supports 32 keywords. They are as follows: 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 ○ While in C++ there are 31 additional keywords other than C. Example #include main() { float a, b; printf("Showing how keywords are used."); return 0; } ⮚ Identifiers ○ Identifiers are nothing but used for naming variables, functions, and arrays. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers, they are reserved for special use. A special kind of identifier, called statement label, can be used in goto statements. ○ Rules for naming Identifiers They must begin with a letter or underscore _ They should consist of only letters, digits, or underscore. No other special characters are allowed. They must not contain white space. They should be up to 31 characters long. ○ Example int amount; double totalbalance; ⮚ Constants ○ Constants are similar to normal variables. The only difference between them is their values cannot be modified by the program once they are defined. And constants are referred to as fixed values. They are also called literals. ○ Constants are of a different type. They are as follows: Integer Constant: Ex: 0, 1, 2586, 201987 Real (or) Floating point constants: Ex: 0.0, 153.56, 24896.32415 Octal & Hexadecimal Constants: Ex: octal:(013)8 = (11)10, Hexadecimal:(013)16= (19)10 Character constants: ‘a’, ‘A’, ‘d’ String constants: Ex: “Freshersnow” ○ There are two ways to define constants in C programming. const keyword #define preprocessor ○ C const Keyword ○ The const keyword is used to define constant in programming. Example #include int main(){ const float PI=3.14; printf("The value of PI is: %f",PI); return 0; } ○ C #define preprocessor ○ The #define preprocessor is also used to define constant. ⮚ Strings ○ Strings are nothing but known as a sequence of characters, enclosed in double quotes, and includes letters, digits, special characters, and blank spaces. In strings, there is a difference between ” ” and ‘ ‘. Example "F" -----> represents a string. 'F' —---> represents a single character ⮚ Special Symbols ○ C language has some special symbols which can be used for different purposes like [] () {},;: * … = # Braces { } The opening and ending curly braces denote the start and end of a block of code containing more than one executable statement. Parentheses ( ) It is used to indicate function calls and function parameters. Brackets [ ] The opening and closing brackets are used as array element references. This indicates single and multi-dimensional subscripts. Preprocessor Directives: Purpose and Usage in C Programs ⮚ Definition ○ Preprocessor directives are commands that are processed by the preprocessor before the actual compilation of the code begins. They are used to make the code more flexible, readable, and maintainable by allowing conditional compilation, macro substitution, file inclusion, and other functionalities. ⮚ Purpose of Preprocessor Directives ○ Code Inclusion: They allow the inclusion of other files, usually header files, into the current file. This promotes modularity and reuse of code. ○ Macro Definitions: They enable the definition of macros, which are constants or functions that can be reused throughout the code. ○ Conditional Compilation: They allow sections of code to be compiled or ignored based on certain conditions, making it easier to write platform-specific or configuration-specific code. ○ Error and Warning Management: They can generate compile-time errors or warnings, helping developers catch potential issues early. ○ Line Control: They provide control over the line numbers and file names reported by the compiler, which is useful for debugging and error reporting. ⮚ Common Preprocessor Directives 1. #include Purpose: Includes the contents of a file into the current file. Usage: #include // Includes standard I/O library #include "myheader.h" // Includes a user-defined header file 2. #define Purpose: Defines a macro, which can be a constant or a function-like macro. Usage: #define PI 3.14159 // Constant macro #define SQUARE(x) ((x) * (x)) // Function-like macro 3. #undef Purpose: Undefines a previously defined macro. Usage: #undef PI 4. #if, #elif, #else, #endif Purpose: Conditionally compiles code based on certain conditions. Usage: #define DEBUG 1 #if DEBUG printf("Debug mode\n"); #elif RELEASE printf("Release mode\n"); #else printf("Unknown mode\n"); #endif 5. #ifdef, #ifndef Purpose: Compiles code if a macro is defined or not defined. Usage: #define FEATURE_ENABLED #ifdef FEATURE_ENABLED printf("Feature is enabled\n"); #endif #ifndef FEATURE_DISABLED printf("Feature is not disabled\n"); #endif 6. #error Purpose: Generates a compile-time error message. Usage: #ifdef WRONG_CONDITION #error "This condition is not allowed" #endif ⮚ Example Usage in a C Program ○ Example that demonstrates several preprocessor directives: #include // Standard library inclusion #define PI 3.14159 // Constant macro #define SQUARE(x) ((x) * (x)) // Function-like macro #define DEBUG_MODE // Conditional compilation void printArea(float radius) { float area = PI * SQUARE(radius); printf("Area: %.2f\n", area); } int main() { float radius = 5.0; #ifdef DEBUG_MODE printf("Debug Mode Enabled\n"); #endif printArea(radius); #undef PI // Undefine the macro // The following line would cause a compile error if uncommented, as PI is undefined // printf("Value of PI: %f\n", PI); return 0; } ⮚ Explanation ○ #include : Includes the standard I/O library. ○ #define PI 3.14159: Defines a macro for the value of π. ○ #define SQUARE(x) ((x) * (x)): Defines a macro for squaring a number. ○ #define DEBUG_MODE: Defines a macro to enable debug mode. ○ #ifdef DEBUG_MODE... #endif: Conditionally compiles the debug message if DEBUG_MODE is defined. ○ #undef PI: Undefines the PI macro, demonstrating the #undef directive. Computer Programming in C LECTURE 3 NOTES Variables and Data Types Significance and Usage of Programming Concepts in C ▪ Programming in C involves understanding various fundamental concepts such as declaring variables, data types, and storage classes. These concepts are essential for writing efficient and readable C programs. Here’s a detailed look into each of these topics. ▪ Rules and Syntax for Declaring Variables ○ Variables are used to store data that can be manipulated by the program. Declaring variables correctly is crucial for the proper functioning of the program. ○ Rules for Declaring Variables Variable Name: Must start with a letter (uppercase or lowercase) or an underscore (_), followed by letters, digits, or underscores. No Reserved Keywords: Cannot use C reserved keywords as variable names (e.g., int, return, float). Case Sensitivity: Variable names are case-sensitive (variable, Variable, and VARIABLE are different). Declare Before Use: Variables must be declared before they are used in the code. ▪ Syntax for Declaring Variables ○ The general syntax for declaring a variable is: data_type variable_name; ○ You can also initialize the variable at the time of declaration: data_type variable_name = value; ○ Examples int age; // Declaration of an integer variable float height = 1.75; // Declaration and initialization of a float variable char initial = 'A'; // Declaration and initialization of a char variable ○ Multiple Declarations You can declare multiple variables of the same type in a single statement: int a, b, c; float x = 0.0, y = 1.5; Data Types ▪ Data types in C define the type of data a variable can hold. They help the compiler understand how much memory to allocate and how to interpret the bit patterns stored in that memory. ▪ Basic Data Types ▪ Integer Types: ○ int: Standard integer. ○ short: Short integer. ○ long: Long integer. ○ long long: Longer integer. ○ unsigned: Unsigned integer (positive values only). ▪ Floating-point Types: ○ float: Single-precision floating-point. ○ double: Double-precision floating-point. ○ long double: Extended precision floating-point. ▪ Character Types: ○ char: Single character, typically 1 byte. ○ unsigned char: Unsigned character. ○ signed char: Signed character. ⮚ Derived Data Types 1. Arrays: Collection of elements of the same type. int numbers; float matrix; 2. Pointers: Variables that store the memory address of another variable. int *ptr; float *fptr; 3. Structures: User-defined data types that group different types of variables. struct Person { char name; int age; float height; }; 4. Unions: Similar to structures, but all members share the same memory location. union Data { int i; float f; char str; }; 5. Enumerations: User-defined data type consisting of a set of named integer constants. enum Color { RED, GREEN, BLUE }; #include int main() { enum Color favoriteColor = BLUE; if (favoriteColor == BLUE) { printf("Your favorite color is Blue!\n"); } return 0; } Storage Classes ▪ Storage classes in C define the scope, visibility, and lifetime of variables and functions. There are four types of storage classes: ⮚ Automatic (auto): ○ Default storage class for local variables. ○ Scope: Local to the block in which it is defined. ○ Lifetime: Till the block in which it is defined ends. void func() { auto int x = 10; // Explicitly declared auto int y = 20; // Implicitly auto } ⮚ External (extern): ○ Used to declare a global variable or function that is defined in another file. ○ Scope: Global. ○ Lifetime: Throughout the program execution. extern int globalVar; ⮚ Static (static): ○ For local variables: Preserves the value of a variable between function calls. ○ For global variables and functions: Restricts visibility to the file in which it is declared. void func() { static int count = 0; // Static local variable count++; printf("Count: %d\n", count);} static int globalStaticVar = 10; // File scope static variable ⮚ Register (register): ○ Suggests that the variable be stored in a register instead of RAM for faster access. ○ Scope: Local to the block in which it is defined. ○ Lifetime: Till the block in which it is defined ends. ○ Note: The compiler may ignore this request. void func() { register int i; for (i = 0; i < 10; i++) { printf("%d ", i); } } Example Program Using Storage Classes #include int globalVar = 100; // Global variable void function1() { static int staticVar = 0; // Static local variable staticVar++; printf("Static Variable in function1: %d\n", staticVar); } void function2() { extern int globalVar; // External variable globalVar++; printf("Global Variable in function2: %d\n", globalVar); } int main() { auto int localVar = 10; // Automatic variable register int regVar = 5; // Register variable printf("Local Variable: %d\n", localVar); printf("Register Variable: %d\n", regVar); function1(); function1(); function2(); return 0; } Computer Programming in C LECTURE 4 NOTES Operator and expression I Operators An operator is a symbol that tells the computer to perform certain manipulations. An expression is a sequence of operands and operators that reduces to a single value. C operators can be classified into a number of categories. ○ Arithmetic operators ○ Relational operators ○ Logical operators ○ Bitwise operators ○ Assignment operators ○ Increment and Decrement operators ○ Conditional operators Arithmetic Operators ○ Arithmetic operators in C are used to perform basic arithmetic calculations on numeric operands Types of Arithmetic Operators: ○ The C Arithmetic Operators are of two types based on the number of operands they work. These are as follows: a. Binary Arithmetic Operators: Binary arithmetic operators work with two operands. Example-Addition (+): Adds together two values. b. Unary Arithmetic Operators: Unary arithmetic operators work with a single operand. Example-Increment (++): Adds 1 to the operand. Operator Name Description Example Adds together two + Addition x+y values Subtracts one value - Subtraction x-y from another * Multiplication Multiplies two values x*y Divides one value by / Division x/y another Returns the division % Modulus x%y remainder ○ Note: ‘/’ is integer division which only gives the integer part as result after division. ‘%’ is modulo division which gives the remainder of the integer division as a result. ○ Example 1: Arithmetic Operators: // Working of arithmetic operators #include int main() { int a = 9,b = 4, c; c = a+b; printf("a+b = %d \n",c); c = a-b; printf("a-b = %d \n",c); c = a*b; printf("a*b = %d \n",c) c = a/b; printf("a/b = %d \n",c); c = a%b; printf("Remainder when a divided by b = %d \n",c); return 0; } ○ Output a+b = 13 a-b = 5 a*b = 36 a/b = 2 Remainder when a divided by b=1 ○ The operators +, - and * computes addition, subtraction, and multiplication respectively as you might have expected. ○ In normal calculation, 9/4 = 2.25. However, the output is 2 in the program. ○ It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25. ○ The modulo operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1. The % operator can only be used with integers. ○ Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming // Either one of the operands is a floating-point number a/b = 2.5 a/d = 2.5 c/b = 2.5 // Both operands are integers c/d = 2 Relational Operators ○ Relational operators are used when we have to make comparisons. This operator returns true or false based on the relationship between two operands. C programming offers six relational operators. Operator Name Example == Equal to x == y != Not equal x != y > Greater than x>y < Less than x= Greater than or equal to x >= y b); printf("%d > %d is %d \n", a, c, a > c); printf("%d < %d is %d \n", a, b, a < b); printf("%d < %d is %d \n", a, c, a < c); printf("%d != %d is %d \n", a, b, a != b); printf("%d != %d is %d \n", a, c, a != c); printf("%d >= %d is %d \n", a, b, a >= b); printf("%d >= %d is %d \n", a, c, a >= c); printf("%d

Use Quizgecko on...
Browser
Browser