PSC Notes PDF

Summary

These notes cover fundamental concepts in algorithm and data structures. They define algorithms, variables, constants, and discuss different types of operators in C programming. Flowcharts and examples are included to illustrate the topics.

Full Transcript

# Algorithm and Data Structures ## What is an algorithm? What are the characteristics of an algorithm? An algorithm is a set of instructions used to solve a specific problem or perform a particular task. It is a systematic approach to problem solving that outlines a sequence of operations, actions...

# Algorithm and Data Structures ## What is an algorithm? What are the characteristics of an algorithm? An algorithm is a set of instructions used to solve a specific problem or perform a particular task. It is a systematic approach to problem solving that outlines a sequence of operations, actions, or decisions that need to be executed in a specific order to achieve a desired result. **Remarks:** * It is simply a logic to be implemented to solve the problem. * It can be described as a pseudo-code. * It can be represented as a flowchart. **Characteristics of Algorithm** 1. **Input:** It takes input data on which the algorithm operates to produce the desired output. An algorithm may or may not require input. 2. **Output:** Every algorithm produces a result or output based on the input and the series of operations it performs. Each algorithm is expected to produce at least one result. 3. **Definiteness:** Algorithms have clear, unambiguous, and precisely defined steps. Each step must be understandable and executable. 4. **Finiteness:** An algorithm must terminate after a finite number of steps. It cannot go on indefinitely. 5. **Independent:** An algorithm should have step-by-step directions which should be independent of any programming. ## Define a variable. How you declare a variable and assign values to a variable. **Variable:** It is the name for a memory location on that may be used to store a data value. * A variable may take different values at different times during execution. * A variable name may be chosen by the programmer in a meaningful way, so as to reflect its function (or) nature in the program. * For example: sum, avg, total, etc. **Variable declaration:** The syntax and example with regards to variable declaration are explained below: ``` datatype <variable name> ; ``` **Assigning values to variable (Initialization):** After declaring variables, you can assign a value to a variable later on using a statement like this: ``` variable name= value; ``` **Example:** ``` int a; a=10; ``` ## Define a keyword. Give 100 examples. Keywords are words that have special meaning to the C compiler and their meanings cannot be changed during execution of a program. Keywords are reserved words of the language. They have specific meaning in the language and cannot be used by the programmers as variable or constant names. C has 32 keywords, all keywords are written in lowercase, for example, int, if, for, float, while, etc. **Examples:** | Keyword | Keyword | Keyword | Keyword | |---|---|---|---| | 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 | ## Define a constant. Which are the two ways for which you can declare a constant. A physical quantity which does not change its value during the execution of a program is known as a constant. **Two types:** 1. **Numeric constants:** Constants with only numbers are known as numeric constants. 2. **Character constants:** Constants which is made up of only characters or letters. ## What is symbolic constant. How you create symbolic constants in C. A symbolic constant: How you create a symbolic numeric Constant in our program **Ex:** In the above example numeric constant will be 3.14. This can be replaced by symbolic constant "PI". Then so we are using one pre-processor directive that is `# define`. `#define PI 3.142` ## Define Identifier with an example. Mention the rules of identifiers Identifiers refer to the name given to programming concepts like variables, functions, arrays, structures, unions. These are user defined names consisting of a sequence of letters and digits. Both uppercase and lowercase letters are permitted. A "C program" consist of two type of elements: user defined and system defined. **Rules of Identifiers** 1. The first character of an identifier should be either an alphabet or an underscore. 2. A valid identifier can have only alphabets (both uppercase and lowercase), digits and underscore. 3. It cannot use keywords like `int, if, while ... etc` as identifiers. 4. An identifier must not contain any space, for example: ``` int price; int to price ; ``` Here, `price` & `to_price` are identifiers which denotes a variable of `int` type. ## Define a flow chart. Explain different components in a flow chart. (Draw one sample) A flowchart is a graphical representation of an algorithm, using specific symbols and annotations. It provides a visual representation of the sequence of actions and decision points in the program's execution. Flowcharts help programmers design, understand, and communicate the logic of their programs effectively. **Flowchart Symbols:** | Name | Symbol | Description | |---|---|---| | Oval | <img src="https://i.imgur.com/28J3a0o.png" alt="Oval"> | Denotes the beginning or end of a program | | Flow Line | <img src="https://i.imgur.com/7eCYY2d.png" alt="Flow Line"> | Denotes the direction of logic flow in a program | | Parallelogram | <img src="https://i.imgur.com/Y8k4P0m.png" alt="Parallelogram"> | Denotes either an input operation (e.g., INPUT) or an output operation (e.g., PRINT). | | Rectangle | <img src="https://i.imgur.com/HwrE3jH.png" alt="Rectangle"> | Denotes a process to be carried out (e.g., addition). | | Diamond | <img src="https://i.imgur.com/xS9F9Xz.png" alt="Diamond"> | Denotes a decision (or branch) to be made. The program should continue along one of two routes (e.g., IF/THEN/ELSE). | | Circle | <img src="https://i.imgur.com/f8K72O3.png" alt="Circle"> | Connector: Connects segments of a flow chart when segments are on different pages. | **Sample Flowchart:** <img src="https://i.imgur.com/9A9q4m5.png" alt="Flowchart"> ## Define a variable. Explain different scope of variable in C. It is the name for a memory location that may be used to store a data value. * A variable may take different values at different times during execution. * A variable name may be chosen by the programmer in a meaningful way, so as to reflect its function (or) nature in the program. * For example: sum, avg, total, etc. **Scope of variables** 1. **Local variables:** A variable inside the main block and its value is available within that block. 2. **Global variables:** A variable outside the main block and its value is available throughout the program. ## Define Datatype. Explain the built-in datatypes available in C Datatypes are used to inform the type and value that can be stored in a variable. In C, datatypes are classified into two types: 1. **Primary Datatype:** Built-in datatypes. 2. **Secondary Datatype:** User-defined datatypes. **Built-in Datatypes:** Built-in datatypes are also known as built-in data types, on the basic or primary datatypes. C has 4 basic datatypes. They are: * **Integer:** Stores whole numbers. * **Floating point:** Stores decimal numbers. * **Double:** Stores double precision decimal numbers. * **Char:** Stores single characters. **C Data Type Hierarchy** <img src="https://i.imgur.com/7g0J71k.png" alt="C Data Type Hierarchy"> ## Define a constant. Explain types of constants available in C. A physical quantity which does not change its value during the execution of a program is known as a constant. C language supports several types of constants: * **Numeric constants:** Constants with only numbers are known as numeric constants. * **Character constants:** Constants which is made up of only characters or letters. **Numeric constants:** are divided into two types: * **Integer constants:** Stores whole numbers. * **Real constants:** Stores decimal numbers. ## Explain the basic structure of a C program. A C program is divided into 6 parts. They are: * **Documentation Section:** Provides information about the program, author, date created, and purpose. * **Preprocessor Section:** Includes header files and defines macros. * **Definition Section:** Defines symbolic constants. * **Global Declaration Section:** Declares global variables and functions. * **Main() function Section:** Contains the `main()` function, which is the entry point of the program. * **Subprogram Section:** Contains user-defined functions. ## Documentation Section The documentation section consists of comments in lines which include the name of the program, the author and other details like time and date of writing the program. * The documentation section helps anyone to get an overview of the program and its functionalities. * Compilers ignore comments and do not print them on the screen. `/* File Name: Hello.c Author Name: Jectu Saher, founder of is Tutorialpoint Date: 05/05/2021 Description: A program to find add of even number. */` ## Multi-line Comment Multi-line comment starts with an asterisk slash (`/`) and with an asterisk slash (`*/`). You can use multi-line comments anywhere in your code. A multi-line comment can be one or more than one line in a program. The syntax of the multi-line comment is: ``` /* Line 1 Line 2 .... Comment ends */ ``` **Ex:** ``` /* Author: XYZ Description: A program to find odd or even number. */ ``` ## Single line Comment Single-line comment is used in single line only. Single-line comment is represented as double forward slash (`//`). The syntax of single-line comment is: ``` // Single line comment // description: // Date: ``` **Ex:** ``` // description: A program to find odd or even number. // Date: 07/08/21 ``` ## Definition Section All the symbolic constants are written in definition section. Macros are known as symbolic constants. ``` # define PI 3.14 ``` ## Global Declaration Section Within the Global declaration section we can use declare such variables which we can use anywhere in our program, and that variable is called Global variables. ``` int area; int add(int x); // global function int n; // global variable ``` ## Preprocessor Section/Include Section The link section consists of the header files of the functions that are used in the program. It provides instructions to the compiler to link functions from the system library. ``` #include <stdio.h> #include <conio.h> #include <string.h> #include <math.h> ``` ## Subprogram Section The subprogram section contains all the user-defined functions that are used to perform a specific task. These user-defined functions are called in the main function. ``` int add(int a, int b) { return a+b; } ``` ## Write an algorithm and draw a flowchart to: 1. **Find the average of three numbers.** 2. **Find the largest of three numbers.** 3. **Find the sum of n natural numbers.** ### Algorithm 1: Finding the average of three numbers **Step 1:** Start **Step 2:** PRINT Enter three numbers. **Step 3:** Read num1, num2, and num3. **Step 4:** Sum = num1 + num2 + num3 **Step 5:** Print average = Sum / 3 **Step 6:** End **Flowchart 1:** <img src="https://i.imgur.com/A46f53V.png" alt="Flowchart 1"> ### Algorithm 2: Finding the largest of three numbers **Step 1:** Start **Step 2:** PRINT Enter three numbers. **Step 3:** Read num1, num2, and num3. **Step 4:** If num1 > num2 and num1 > num3 THEN PRINT num1 is largest ELSE PRINT num3 is largest **Step 5:** End. **Flowchart 2:** <img src="https://i.imgur.com/33M3mKh.png" alt="Flowchart 2"> ### Algorithm 3: Finding the sum of n natural numbers **Step 1:** Start **Step 2:** Read n **Step 3:** Sum = 0 **Step 4:** Repeat steps 5-6. **Step 5:** Sum = Sum + i **Step 6:** i = i + 1 **Step 7:** Print Sum. **Step 8:** End **Flowchart 3:** <img align="center" width="400" src="https://i.imgur.com/vL8l1t5.png" alt="Flowchart 3"> ## What are Unary operators and explain with an example Unary operators are operators that act upon a single operand to produce a new value. **Example:** ``` int a = -10; int b = +a; b = -1; ``` ## Define binary operators with an example. Binary operators are operators that act upon two operands to produce a new value. **Example:** ``` 10 + 12 ``` Here, `+` is a binary operator. Other examples of binary operators include: * Subtraction (`-`) * Multiplication (`*`) * Division (`/`) ## Define ternary operator with an example A ternary operator is a conditional operator in programming that evaluates an expression based on a condition. **Example:** ``` N = (10 > 2) ? greatest += 10; greatest; ``` If `(10 > 2)` is true, then `greatest += 10` will be executed, otherwise `greatest` will be returned. **Output:** `N = 10` ## Define auto increment operator with an example Increment is used to increase the value of the variable by 1. **Example:** ``` a++ means a = a+1 ``` ## Define auto decrement operator with an example Decrement is used to decrease the value of the variable by 1. **Example:** ``` a-- means a = a-1 ``` ## Difference between pre-increment and post increment operators ### Pre-increment: The operator precedes the operand. The quantity on which an operation is to be done. **Example:** ``` int a = 2; int b = ++a; ``` Here, `++a` is a pre-increment operator. The value of a is incremented before it is assigned to b. Therefore, the value of b will be 3. **Output:** `b = 3` ### Post-increment: The operator follows the operand. **Example:** ``` int a = 1; int b = a++; int c = a; ``` Here, `a++` is a post-increment operator. The value of a is assigned to b before it is incremented. The value of c will be 2. **Output:** `c = 2` ## Difference between pre-decrement and post decrement ### Pre-decrement The operator precedes the operand. **Example:** ``` int a =1; int b = --a; ``` Here, `--a` is a pre-decrement operator. The value of a is decremented before it is assigned to b.. Therefore, the value of b will be 0. **Output:** `b = 0` ### Post-decrement The operator follows the operand. **Example:** ``` int a =1; int b = a--; int c = a; ``` Here, `a--` is a post-decrement operator. The value of a is assigned to b before it is decremented. The value of c will be 0. **Output:** `c = 0` ## What is the difference between `=` and `==` operators? * `=` is an assignment operator which is used to assign value to variables. * `==` is a relational operator which is used for checking equality. **Example:** ``` Sum = 10 // will assign the value 10 to the variable sum 6 == 6 // will return true ``` ## What is the difference between `&` and `&& ` operators? ### Bitwise operator (`&`) AND ( `&` ) represents multiplication at the bit level (bitwise AND operation). It's often used for manipulating data, such as setting specific bits, masking, and testing flag values. ### Logical AND (`&&`) Logical AND ( `&&` ) operator combines two conditions. It returns `true` only if both conditions are `true`. Otherwise, it returns `false`. ## Define escape sequence with an example An escape sequence is a series of characters used in programming to represent special characters that cannot be directly typed on a keyboard. These characters are otherwise reserved for specific functions. The sequence typically begins with a backslash (`\`). **Example:** The escape sequence `\n` represents a newline character, which moves the cursor to the next line. ``` printf("Hello, world!\nWelcome"); ``` **Output:** ``` Hello, world! Welcome ``` ## What are the formatted input/output functions? Standard input and output functions are used to handle data reading and writing to the primary input and output functions from the standard library: * **`printf()`:** Writes formatted output to the console or a file. * **`scanf()`:** Reads formatted input from the console or a file. ## What are standard input and output functions? Standard input and output functions are used to handle data reading and writing to the primary input and output functions form the standard library: * **`printf()`:** Writes formatted output to the console or a file. * **`scanf()`:** Reads formatted input from the console or a file. **Other standard input/output functions:** * **`fprintf()`:** Writes formatted output to a specific file stream. * **`fscanf()`:** Reads formatted input from a specific file stream. * **`getch()`:** Returns a single character directly without displaying it. * **`getche()`** Reads a single character directly from the keyboard and displays it. * **`gets()`:** Reads an entire line of input from the console until a newline character is encountered. * **`puts()`:**Writes a string to the console, followed by a newline (`\n`) character. ## What is the difference between `gets()` and `scanf()`? ### `gets()` * **Unformatted input:** Reads an entire line of input from the console until a newline character is encountered. * **String input:** Reads a string (sequence of characters) at a time. **Syntax:** ``` gets(string); ``` **Example:** ``` gets(name); ``` ### `scanf()` * **Formatted input:** Reads formatted input from the console based on the format specifiers provided. * **Various data types:** Can read input for various data types, such as integers, floats, strings, and characters. **Syntax:** ``` scanf("formatted string", &var1, &var2, ...); ``` **Example:** ``` scanf("%d", &age); ``` ## What is the difference between `getch()` and `getche()`? ### `getch()` * **Non-displayed character:** Reads a single character directly from the keyboard without displaying it. * **Quick input**: Useful for creating menu-driven programs where you don't want to see characters echoed to the screen. ### `getche()` * **Displayed character:** Reads a single character from the keyboard and displays it. * **Immediate feedback:** Useful for programs where you want to provide immediate feedback to the user. ## What is the syntax of `printf()` and `scanf()` functions? ### `printf()` **Syntax:** ``` printf("formatted string", var1, var2, ...); ``` **Example:** ``` printf("The sum is %d", sum); printf("Welcome to C programming"); ``` ### `scanf()` **Syntax:** ``` scanf("formatted string", &var1, &var2, ...); ``` **Example:** ``` scanf("%d", &num); ``` ### **Explanation of `scanf()` / `printf()` Syntax** 1. **`formatted string`**: This is a string that specifies the format of the input or output. It contains format specifiers and optional text. 2. **Format specifiers**: These are special characters that tell `scanf()` and `printf()` how to interpret the data. 3. **Variables**: These are variables that `scanf()` will read data into, and `printf()` will print data from. ## What is type conversion in C? Explain different types of type conversion with suitable examples. Type conversion is a method to convert a value of one data type to another data type. The types of conversions are classified into 2 types: 1. **Implicit Type Conversion:** Also known as **automatic type conversion**. Happens automatically when a mixed arithmetic expression contains operands of different data types. **Example:** ``` int i = 5; float f; f = i; ``` In this example, `i` (integer) is converted to `f` (float) because the compiler automatically promotes the smaller data type (int) to the larger data type (float). 2. **Explicit Type Conversions:** Also known as **type casting**. This method is used to explicitly convert the value of one data type to another data type, even when the compiler does not automatically convert it. This conversion is done using the **type casting** operator. **Syntax:** ``` (type)expression ``` **Example:** ``` float a = 5.25; int b = (int)a; ``` In this example, the `(int)` is a type casting operator, which explicitly converts the `float` value `a` to an `int` value and assigns it to the variable `b`. ## Explain different types of Arithmetic operators? Arithmetic operators are used to perform arithmetic or mathematical operations on operands . Types of arithmetic operators: * **Addition (`+`):** Adds one operand to the other operand. * **Subtraction (`-`):** Subtracts the second operand from the first operand. * **Multiplication (`*`):** Multiplies one operand by the other operand. * **Division (`/`):** Divides the first operand by the second operand. * **Modulo (`%`):** Divides the first integer operand by the second and returns the remainder. ## Explain different types of logical operators? Logical operators are used to combine or modify Boolean expressions. Three types of Logical operators: * **Logical AND (`&&`):** Performs logical AND operation between two Boolean expressions. It returns true only if both conditions are true. **Example:** ``` A && B ``` * **Logical OR (`||`):** Performs logical OR operation between two Boolean expressions. It returns true if at least one condition is true. **Example:** ``` A || B ``` * **Logical NOT (`!`):** Negates the Boolean expression. It returns true if the condition is false. **Example:** ``` !A ``` ## Explain different types of conditional operators? Conditional operators are also known as ternary operators. These operators are used for conditional decision-making. It depends upon the output of the expression. It is represented by two symbols: `?` and `:`. **Syntax:** ``` Variable = Expression1 ? Expression2 : Expression3 ``` * **Expression1** is evaluated first. * **Expression2** is evaluated if **Expression1** is true, and the result is assigned to the variable. * **Expression3** is evaluated if **Expression1** is false, and the result is assigned to the variable. * Either **Expression2** or **Expression3** will be evaluated, but never both. **Example:** ``` #include <stdio.h> void main() { int a, b, x; printf("Enter the values of a and b: "); scanf("%d %d", &a, &b); x = (a > b) ? a : b; printf("Biggest value is: %d", x); } ``` ## Explain different Bitwise operators? Bitwise operators are used for manipulating data at the bit level. This is also called bit-level programming. ### Types of Bitwise Operators * **Bitwise AND (`&`):** Performs a bitwise AND operation on two integer operands. If both corresponding bits are 1, then the result is 1; otherwise, the result is 0. **Truth Table:** | X | Y | X & Y | |---|---|---| | 0 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | * **Bitwise OR (`|`):** Performs a bitwise OR operation on two integer operands. If at least one corresponding bit is 1, then the result is 1; otherwise, the result is 0. **Truth Table:** | X | Y | X | Y | |---|---|---| | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 | * **Bitwise NOT (`~`):** Performs a bitwise complement operation on a single integer operand. It flips the bits of the operand (0 to 1, 1 to 0). **Example:** ``` ~0101 ``` **Result:** `1010` * **Bitwise Left Shift (`<<`):** Shifts the bits of an operand to the left. Each shift to the left multiplies the value by 2. **Syntax:** ``` variable << number of bits ``` **Example:** ``` Suppose a = 0000 1010 then a<<3 then the result is 01010000 ``` * **Bitwise Right Shift (`>>`):** Shifts the bits of an operand to the right. Each shift right divides the value by 2. **Syntax:** ``` variable >> number of bits ``` **Example:** ``` Suppose a = 01101010 then a>>3 then the result is 00001101 ``` ## Explain decision making using the `if` statement with suitable examples. In C programming, decision making is crucial for controlling the flow of execution based on a condition. The `if` statement is a primary control structure that allows for this functionality: * **Simple `if` statement:** The `if` statement checks whether a given condition is `true`. If the condition is `true`, then it executes the statements within the block of code. If the condition is `false`, it skips the block of code and continues execution after the `if` block. <img src="https://i.imgur.com/Y2E2g3y.png" alt="If block"> **Example:** ``` #include <stdio.h> #include <conio.h> void main() { int a, b; printf("Enter two numbers: "); scanf("%d %d", &a, &b); if (a > b) { printf("The larger number is %d\n",a); } getch(); } ``` * **`if-else` statement:** The `if-else` statement provides an alternative path of execution in case the condition in the `if` statement is `false`. If the condition is `true`, then the `if` block is executed. Otherwise, the `else` block is executed. <img src="https://i.imgur.com/7P74sJ9.png" alt="If-else block"> **Example:** ``` #include <stdio.h> #include <conio.h> void main() { int a, b; printf("Enter two numbers: "); scanf("%d %d", &a, &b); if (a > b) { printf("The larger number is %d\n",a); } else { printf("The larger number is %d\n",b); } getch(); } ``` * **`if-else if ladder` statement:** The `if-else if ladder` allows for multiple conditional checks. It evaluates each condition in sequence. If a condition is `true`, the corresponding block of code associated with that condition is executed and the ladder is exited. If the condition is `false`, the next `else if` condition is checked. If none of the conditions in the `else if` ladder are true, the `else ` block (if provided) is executed. <img src="https://i.imgur.com/fYfX43s.png" alt="If-else if ladder block"> **Example:** ``` #include <stdio.h> #include <conio.h> void main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num > 0) { printf("The number is positive\n"); } else if (num < 0) { printf("The number is negative\n"); } else { printf("The number is zero\n"); } getch(); } ``` * **Nested `if` statement:** A nested `if` statement is an `if` statement within another `if` statement. This creates a hierarchical decision-making structure where conditions are evaluated step by step. <img src="https://i.imgur.com/Q4gM46i.png" alt="Nested If Block"> **Example:** ``` #include <stdio.h> #include <conio.h> void main() { int a, b, c; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); if (a > b) { if (a > c) { printf("Largest number is %d\n", a); } else { printf("Largest number is %d\n", c); } } else { if (b > c) { printf("Largest number is %d\n", b); } else { printf("Largest number is %d\n", c); } } getch(); } ``` ## Explain decision making using the `switch` statement with suitable examples. The `switch` statement provides a multi-way branching mechanism. It is an extension of the `if-else if ladder` statement . Here are some key points about the `switch` statement: * **Multiple conditions:** It allows evaluation of multiple conditions based on the value of an expression. * **Case labels:** The `switch` statement uses `case` labels to test against possible values of the expression. Each `case` label represents a specific value or range of values. * **`break` statement:** The `break` statement is used to exit the current `switch` block. If a `break` statement is not used, the program will continue executing the next `case` label, which is not always the desired behavior. * **`default` label:** The `default` label is optional and provides a fallback option if none of the `case` labels match the value of the expression. **Syntax:** ``` switch (expression) { case label1: statement1; break; case label2: statement2; break; .... case labelN: statementN; break; default: default statement; break; } ``` **Important rules for `switch` statement:** * **Duplicate case values:** Duplicate case values are not allowed. Each case label must have a unique value. * **Data type:** The data type of the variable in the `switch` statement and the `case` labels must be the same. * **`break` statement:** It is essential to include a `break` statement at the end of each `case` block to prevent "fall-through" behavior, where code continues to execute in the next case block. * **The `default` block:** The `default` case block is usually placed at the end of the `switch` block, and it is executed when none of the `case` labels match the expression. **Example:** ``` #include <stdio.h> #include <conio.h> void main() { int day; printf("Enter a day number (1-7): "); scanf("%d", &day); switch (day) { case 1: printf("It's Sunday\n"); break; case 2: printf("It's Monday\n"); break; case 3: printf("It's Tuesday\n"); break; case 4: printf("It's Wednesday\n"); break; case 5: printf("It's Thursday\n"); break; case 6: printf("It's Friday\n"); break; case 7: printf("It's Saturday\n"); break; default: printf("Invalid day input.\n"); } getch(); } ``` ## Write the syntax of "for loop" detailing its components and write a suitable example. ### Introduction to `for` loops `for` loops are a powerful looping construct in C programming. They allow you to repeat a block of code a specific number of times, making them ideal for tasks involving iteration. ### Understanding the syntax The `for` loop in C has a specific syntax that controls the looping process: ```c for (expression1; expression2; expression3) { [statement(s)]; } ``` The `for` loop is composed of three main parts: **1. Initialization (expression1):** * This section is executed only once at the beginning of the `for` loop. * It typically initializes a counter variable or sets up variables needed for the loop. This expression is a statement that runs only once at first. **2. Condition (expression2):** * This section is evaluated before each iteration. * It determines whether the loop should continue or terminate. * This condition is checked before each iteration. If it is *true*, the body of the loop will be executed. If it is *false*, the loop will terminate. **3. Update (expression3):** * This section is executed after each iteration. * It typically updates the counter variable or modifies other variables used within the loop. * This statement executes immediately after the body of the loop for each iteration. ### Illustrative example Let's create a simple `for` loop to print numbers from 1 to 5: ```c #include <stdio.h> void main() { int i; for (i = 1; i <= 5; i++) { printf("%d ", i); } } ``` **Explanation of the example:** 1. **Initialization:** `i = 1;` * The counter variable `i` is

Use Quizgecko on...
Browser
Browser