C Programming PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides an introduction to the C programming language, covering fundamental concepts such as variables, data types, operators, and control structures. It includes examples to illustrate the use of these concepts. The document also discusses the structure of a C program, variables, predefined functions, and how to execute a C program.
Full Transcript
# C Programming ## 1. What is a computer? - A computer is an electronic device that can accept and store information, process it, and give the desirable result on output. - It can also help us solve various problems. ## 2. What is Programming? - Programming is a process for writing code to const...
# C Programming ## 1. What is a computer? - A computer is an electronic device that can accept and store information, process it, and give the desirable result on output. - It can also help us solve various problems. ## 2. What is Programming? - Programming is a process for writing code to construct an application and designing and building an executable computer program. ## 3. What is C? - C is a general-purpose, high-level programming language that is the mother of all languages. - C is called a procedure-oriented programming language (POP). ## 4. What is a Compiler? - A compiler is a computer program that translates computer code written in one programming language to another programming language. - It converts `.i` to `.obj` files. ## 5. Why are Header Files Used? - Used to define all the functions, variables contained in any function library. - A file where some predefined functions work. ## 6. Why is `#` used in header files? - The hash symbol helps the compiler load the header files that are needed for compilation of the whole program. - It is a preprocessor. ## 7. Who Developed C Language? - Dennis Ritchie at Bell Labs (USA), in 1972. ## 8. What is an Operating System? - System software that performs process management, file management, memory management. - Acts as a manager of the computer system. - Examples: Windows 7, Windows 8, Linux, Mac-OS ## 9. Why is Semicolon `(;)` used? - To terminate the statement. ## 10. Why are `{}` used? - To make a complete block. ## 11. Why is the `main()` Function Used in C Programs? - It is the core of every program. - It contains instructions that tell the computer to carry out whatever task the program is designed to do. ## 12. What is an Algorithm? - A way to write mathematical and logical problems step-by-step. - Helps the computer analyze. - Algorithms are universal. - Example: Algorithm of Series. | Step | Operation | |:---:|:---| | 1 | `x = 1` | | 2 | `Print(x)` | | 3 | `x = x + 1` | | 4 | `if(x < 11) goto Step 2;` | | 5 | `Stop;` | ## 13. What is a Flowchart? - A graphical view of an algorithm. - Called a flowchart. - Helps reduce program-making time. - Reduces errors in time. ### Flowchart Symbols | Symbol | Description | |:---|:---| | 🗲 | Starting/Ending Box | | 🗭 | Input/Output Box | | 🗬 | Processing Box | | 🗮 | Decision Box | | 🗶 | Flow Line | ## 14. What is an Operand? - Data or a variable on which the operation is performed. - Called an operand. ## 15. What is a Data Type? - A type of data used in the program. - Defines the amount of storage area allocated to variables. - Examples: | Data Type | Size (bytes) | |:---|:---| | `int` | 2 | | `char` | 1 | | `float` | 4 | | `double` | 8 | ## 16. What are the Types of Operators? - Arithmetic operators (+, -, *, /, %) - Relational operators (==, !=, <, >, <=, >=) - Logical operators (&&, ||, !) - Bitwise operators (&, |, ^, ~, >>, <<) - Conditional operators (?) - Increment/Decrement operators (++ and --) ## 17. What is a Local Variable? - A variable defined inside a block. - Called a local variable. ## 18. What is a Global Variable? - Declared outside any function and can be used in any function in the program. ## 19. What is an Operator? - Allows performing different kinds of operations on operands. - Special symbols that perform operations on one or more operands. ## 20. What is a Keyword? - Word that is predefined in the library. - A *keyword* is predefined. - Cannot be used as a variable. ## 21. What is a Variable? - Name of a storage area used to store data or information. ## 22. What is a Predefined Function? - A function predefined in the library. - Also called a *library function*. - Examples: `Printf()`, `Scanf()`, `getch()`, `clrscr()`, etc. ## 23. What is `Printf()`? - Predefined function used to *print* data or information, outputting results on to the output screen. - Defined inside *stdio.h* header file. ## 24. What is `Scanf()`? - Predefined function used to assign values. - Defined inside *stdio.h* header file. ## 25. What is `clcrscr()`? - Predefined function that clears the previous output screen. - Defined inside *conio.h* header file. ## 26. What is `getch()`? - Predefined function that holds the output screen. - Defined inside *conio.h* header file. ## 27. What is `void`? - A keyword. - Meaning: empty. ## 28. What are the Full Names of *conio* and *stdio*? - **stdio**: Standard input output. - **conio**: Console input output. ## 29. Execution of a Program - A simplified diagram: **Processor** - Set of registers & instruction register. - Memory unit. - Control Unit - ALU (Arithmetic Logic Unit) - Hard Disk - Program is saved in the hard disk and double-clicked to load it into the RAM. - Instruction is passed to the memory unit in the form of a register. - Control unit decodes the instruction and sends it to the ALU. - ALU performs the arithmetic and logical calculations, and the instruction is executed. ## 30. How to Make a Software? - Simplified diagram, steps: - Source file has the `.c` extension. - Preprocessor loads the header files and makes a `.obj` file. - Compiler converts the `.obj` file to an object file. - Linker connects the object files and library files, and creates a `.exe` file. ## 31. What are Tokens? - Basic building blocks in the C language. - Constructed together to write a C program. - Smallest individual units in a C program. ## 32. Structure of C 1. **Header File** 2. **Main Function** 3. **Open Curly Braces (`{`)** 4. **Logical Variable Declaration** 5. **Input the Program** 6. **Process (Arithmetic & Logical unit)** 7. **Output of the Program** 8. **End** 9. **Close Curly Braces (`}`)** ## 33. Data Types - **Primary data types**: `char`, `int`, `float`, `double`. - **Derived data types**: `arrays`, `structures`, `unions`, `pointers`, `enums`. - **User-defined data types**: `structures`, `unions`, `enums`. ### Primary Data Types | Data Type | Size (bytes) | Example | |:---|:---|:---| | `char` | 1 | `a`, `b`, `c` | | `int` | 2 | `1`, `2`, `3` | | `float` | 4 | `1.5`, `7.8`, `12.04671` | | `double` | 8 | `1.5`, `7.8`, `12.04671` | - **String**: a group of `char` - **`clrscr()`**: to clear screen - **`getch()`**: to hold screen - **`stdio.h`**: standard input/output functions (`Printf()`, `Scanf()`, etc.) - **`conio.h`**: console input/output functions (`clrscr()`, `getch()`, etc.) ## 34. Sum of Two Numbers ```c #include <stdio.h> #include <conio.h> void main() { int a, b, c; clrscr(); printf("Enter two numbers: "); scanf("%d%d", &a, &b); c = a + b; printf("Sum = %d", c); getch(); } ``` ## 35. Group of Characters ```c #include <stdio.h> #include <conio.h> void main() { char a[20]; clrscr(); printf("Enter name: "); scanf("%s", a); printf("Name: %s", a); getch(); } ``` ## 36. Swap Two Numbers Without Third Variable ```c #include <stdio.h> #include <conio.h> void main() { int a, b; clrscr(); printf("Enter two numbers: "); scanf("%d%d", &a, &b); // Single line swap a = a + b; b = a - b; a = a - b; printf("%d %d", a, b); getch(); } ``` ## 37. Operators - Operators allow performing different types of operations on operands. - Types of operators: - Increment/Decrement - Arithmetic - Relational - Logical - Bitwise - Conditional ### Increment/Decrement Operators - **Unary plus (`+`)**: Increases the value by 1. - **Unary minus (`-`)**: Decreases the value by 1. - **Increment (`++`)**: Increases the value by 1. - **Pre-increment**: Increases the value before assigning it. - **Post-increment**: Increases the value after assigning it. - **Decrement (`--`)**: Decreases the value by 1. - **Pre-decrement**: Decreases the value before assigning it. - **Post-decrement**: Decreases the value after assigning it. ### How to Solve Expressions with Increment/Decrement Operators 1. Count the number of pre-increment and pre-decrement operators in the expression. 2. Perform each increment/decrement operation for the appropriate number of times on the right-hand side of the expression. 3. Update the values on all operands based on the results of the increment/decrement operations. 4. Count the number of post-increment and post-decrement operators in the expression. 5. Perform any remaining increment/decrement operations. ## 38. Arithmetic Operators - **Addition (`+`)**: Adds two operands. - **Subtraction (`-`)**: Subtracts the second operand from the first operand. - **Multiplication (`*`)**: Multiplies two operands. - **Division (`/`)**: Divides the first operand by the second operand. - **Modulo (`%`)**: Returns the remainder of the division operation. ## 39. Finding the Modulo Value ```c #include <stdio.h> #include <conio.h> void main() { int a, b, c; clrscr(); a = 10; b = 5; c = a%b; printf("The modulo is %d", c); getch(); } ``` ## 40. Relational Operators - **Equals to (`==`)**: Checks if two operands are equal. - **Not equals to (`!=`)**: Checks if two operands are not equal. - **Less than (`<`)**: Checks if the first operand is less than the second operand. - **Greater than (`>`)**: Checks if the first operand is greater than the second operand. - **Less than or equals to (`<=`)**: Checks if the first operand is less than or equal to the second operand. - **Greater than or equal to (`>=`)**: Checks if the first operand is greater than or equal to the second operand. - Relational operators compare two variables. - Return a boolean value (true or false) after comparison. ## 41. Bitwise Operators - Perform operations on individual bits of integers. - Operators: - `&`: Bitwise AND. Returns 1 if both bits are 1, otherwise 0. - `|`: Bitwise OR. Returns 1 if at least one of the bits is 1, otherwise 0. - `^`: Bitwise XOR. Returns 1 if the bits are different, otherwise 0. - `~`: Bitwise NOT. Inverts the bits of an operand. - `>>`: Bitwise Right Shift. Shifts bits to the right. - `<<`: Bitwise Left Shift. Shifts bits to the left. ## 42. Logical Operators - Used to combine multiple conditions. - Operators: - **AND (`&&`)**: Returns true only if both the operands are true. - **OR (`||`)**: Returns true if at least one of the operands is true. - **NOT (`!`)**: Inverts the logical state of an operand. ## 43. Conditional Operators - **Ternary Operator (`? :`)**: A shorthand for an `if-else` statement. ### Syntax ```c (condition) ? (expression1) : (expression2) ``` - If the *condition* is true, *expression1* is executed. - Otherwise, *expression2* is executed. ## 44. Decision Control Statements - Allow altering the flow of execution based on conditions. - Types: - **Simple if** - **if-else** - **if-else ladder** - **nested if** - **switch-case** ### Simple if Statement ```c if (condition) { // Code to execute if condition is true } ``` ### if-else Statement ```c if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false } ``` ### if-else Ladder ```c if (condition1) { // Code to execute if condition1 is true } else if (condition2) { // Code to execute if condition2 is true } else if (condition3) { // Code to execute if condition3 is true } else { // Code to execute if all conditions are false } ``` ### Nested if Statement ```c if (condition1) { if (condition2) { // Code to execute if both conditions are true } } ``` ### Switch-Case Statement ```c switch (expression) { case value1: // Code to execute if expression equals value1 break; case value2: // Code to execute if expression equals value2 break; // ... more cases default: // Code to execute if no match is found } ``` - `break`: Exits the `switch` block. - `default`: Optional. Executed when no other case matches. ## 45. Looping Statements - Used for repetitive execution of code. - Types: - **while** - **do-while** - **for** ### while Loop ```c while (condition) { // Code to execute as long as condition is true } ``` ### do-while Loop ```c do { // Code to execute } while (condition); ``` - The code in the `do` block is executed at least once, even if the *condition* is false. ### for Loop ```c for (initialization; condition; update) { // Code to execute } ``` - *Initialization* happens once before the loop starts. - The *condition* is checked before each iteration. - The *update* is executed after each iteration. ## 46. Nested for Loop - A `for` loop within another `for` loop. - Useful for iterating through multi-dimensional data structures. ## 47. Breaking from a Loop - **`break` statement**: Exits the current loop. - Useful for exiting the loop prematurely based on a specific condition. ## 48. Continuing a Loop - **`continue` statement**: Skips the rest of the current iteration and starts the next loop iteration. ## 49. Returning Values from a Function - **`return` keyword**: Used to return a value from a function. - Essential for functions with a *return type* other than `void`. ## 50. Functions - A block of code that performs a specific task. - Allows code reusability and modularity. ### Types of Functions - **Predefined functions**: Built-in functions provided by the C library. - Examples: `printf()`, `scanf()`, `strlen()`, `strcpy()`, etc. - **User-defined functions**: Functions created by the programmer. ### Function Declaration - Specifies the function's return type, name, and parameters. - Needed before the function is used in the code. - Example: ```c int add(int x, int y); // Declaration ``` ### Function Definition - Contains the actual code of the function. - Example: ```c int add(int x, int y) { int sum; sum = x + y; return sum; } ``` ### Function Call - Executes the code within a function. - Example: ```c int result = add(5, 10); // Function call ``` ### Function Definition with Return Type - Function definition includes a `return` statement to return a value. - Types: - **No return type**: `void`. - **With return type**: Specifies the type of data the function returns. ### Function Definition with Arguments - Function definition can accept arguments. - Arguments are passed to the function when it is called. - The function's arguments are known as *formal parameters* - The arguments passed inside the function call are called *actual parameters*. ### Function Definition with Return Type and Arguments - Provides a way to receive input and provide a specific output. ## 51. Arrays - Collection of elements of the same data type. - Allows storing multiple values under the same name. - Stored contiguously in memory. ### Array Properties - **Base address**: The memory address of the first element. - **Array index**: Starts from 0. - **Last index**: `(total size - 1)`. ### One-Dimensional Arrays - Stores data in a single row. ### Multi-Dimensional Arrays - Stores data in multiple rows and columns. ## 52. Structure - Allows storing data of different data types under a single name. - Similar to a class in object-oriented programming. ### Structure Definition ```c struct struct_name { data_type variable_1; data_type variable_2; // ... more variables }; ``` ### Accessing Structure Members - Use the dot (`.`) operator. ### Structure Initialization - Can be done during declaration or later. ## 53. Union - A user-defined data type that allows storing different data types in a single shared memory location. - Only one member of a union can be active at any given time. ### Union Definition ```c union union_name { data_type member_1 ; data_type member_2; // ... more members }; ``` ### Union Properties - Size of the union is the size of the largest member. - Can only hold the value of the last member assigned to it. ## 54. Pointers - Variables that store memory addresses of other variables. - Provide a way to access and manipulate data directly in memory. ### Pointer Declaration - Use the `*` symbol. ### Assigning a Pointer - Use the `&` operator to get the address of a variable. ### Dereferencing a Pointer - Use the `*` operator to access the value stored at the address the pointer points to. ## 55. Pointer to Pointer - A pointer that holds the address of another pointer. - Useful for managing data structures like linked lists and trees. ## 56. Parameter Passing Methods - How arguments are passed from the calling function to the called function. - Two main methods: - **Call by Value**: Copies the values of the actual parameters to the formal parameters. Changes made inside the function do not affect the original values. - **Call by Reference (Address)**: Passes the memory addresses of the actual parameters to the formal parameters. Changes made inside the function affect the original values. ## 57. Recursion - A programming technique that allows a function to call itself within its own definition. - Useful for solving problems that can be broken down into similar subproblems. ## 58. Jumping Statements - Statements that alter the normal sequential flow of execution. - These statement "jump" to a different part of the code. - Types - **`goto`**: Unconditionally jumps to a specific label in the code. - **`break`**: Exits the current loop or `switch` statement. - **`continue`**: Skips the rest of the current loop iteration and begins the next iteration. - **`return`**: Returns a value from a function.