C Programming: Decision Making, Loops, Arrays, and Structures Study Notes on Arrays, Strings, and Data Structures
Decision Making and Branching in C
- The C language possesses decision-making capabilities through the following statements: 1. if statement 2. Switch statement 3. Conditional operator statement 4. goto statement
- These statements are popularly known as decision-making statements.
- Because these statements control the flow of execution of a program, they are also referred to as control statements.
Decision Making with the if Statement
- The if statement is described as a powerful decision-making statement used to control the flow of execution of statements.
- Syntax:
if (test expression) - The if statement is implemented in different forms based on the complexity of the conditions being tested: 1. Simple if statement 2. if…else statement 3. Nested if…else statement 4. Else-if ladder
Simple if Statement
- The general form of a simple if statement is:
if (test expression)
{
statement-block;
}
statement-x;
```
- The 'statement-block' can be a single statement or a group of statements.
- If the test expression is true, the statement block is executed.
- If the test expression is false, the statement block is skipped, and execution jumps directly to statement-x.
- If the condition is true, both the statement-block and statement-x are executed in sequence.
- Example Program:
c
#include
- Output: - a is less than 20 - value of a is :
If-Else Statement
- The if-else statement is an extension of the simple if statement.
- Syntax:
if (test expression)
{
true-block statements;
}
else
{
false-block statements;
}
statement-x;
```
- If the test expression is true, the true-block statements are executed; otherwise, the false-block statements are executed.
- In both cases, either the true-block or the false-block will be executed, but never both.
- Example Program:
c
#include
- Output: y is greater than x
Nested If-Else Statement
- This form is used when a series of decisions are involved, necessitating more than one if-else statement in nested form.
- Execution Logic: - If condition is false, it skips to statement . - If condition is true, it tests condition . - If condition is true, it executes statement . - If condition is false, it executes statement . - Control is затем transferred to statement-x.
- Example Program (Finding the greatest of three numbers):
#include <stdio.h>
void main() {
int a, b, c;
printf("Enter 3 numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
if (a > c) {
printf("\n A is greater");
} else {
printf("\n C is greater");
}
} else {
if (b > c) {
printf("\n B is greater");
} else {
printf("\n C is greater");
}
}
getch();
}
```
- Output Example: Enter 3 numbers : -> B is greater
# Else-If Ladder
- This construct is used when multipath decisions are involved.
- A multipath decision is a chain of ifs where the statement associated with each "else" is another "if".
- Evaluation Logic:
- Conditions are evaluated from the top of the ladder downward.
- As soon as a true condition is found, its associated statement is executed, and control is transferred to statement-x (skipping the rest of the ladder).
- If all conditions are false, the final "else" containing the default-statement is executed.
- Example Program (Grade Assignment):
c
#include
Switch Statement
- The switch statement is a multiway branch statement.
- It provides an easy way to dispatch execution to different parts of the code based on the value of an expression.
- It allows a value to change the control of execution.
- Syntax:
switch (expression) {
case value1 : block1; break;
case value2 : block2; break;
default : default block; break;
}
statement-x;
```
- Role of break: Break statements are used to exit the switch block. If omitted, all consecutive blocks of code will be executed after the matching block.
- Rules for Using Switch:
1. The expression must yield an integer value (integer, variable, or expression evaluating to an integer).
2. Case label values must be unique.
3. Case labels must end with a colon (:).
4. The line after a case statement can be any valid C statement.
- Example Program for Days of the Week:
c switch (number) { case 1 : printf("Monday"); break; case 2 : printf("Tuesday"); break; case 3 : printf("Wednesday"); break; case 4 : printf("Thursday"); break; case 5 : printf("Friday"); break; default : printf("Saturday"); break; } ```
Conditional Operator (Ternary Operator)
- The operator pair "?" and ":" is known as the conditional operator.
- These are ternary operators.
- Syntax:
expression1 ? expression2 : expression3 ; - Operation Logic:
1. The
conditionalExpression(expression1) is evaluated first. 2. It evaluates to if true and if false. 3. If expression1 is true, expression2 is evaluated. 4. If expression1 is false, expression3 is evaluated. - Comparison with if-else:
-
if (a > b) x = a; else x = b;can be rewritten asx = (a > b) ? a : b ;. - Example Program:
#include <stdio.h>
#include <conio.h>
void main() {
int a = 10, b = 20, c;
c = (a > b) ? a : b;
printf("%d", c);
getch();
}
```
- Output:
# Goto Statement
- Used to transfer program control from one point to another.
- It is referred to as unconditional branching.
- Syntax: `goto label;` ... `label: statement;`
- Rules for labels:
- A label is any valid variable name followed by a colon.
- A label can precede any statement: `Label: statement;`.
- This statement breaks the normal sequential execution.
- Jump Types:
- Forward Jump: The label is placed after the `goto` statement, skipping some code.
- Backward Jump: The label is placed before the `goto` statement, forming a loop where statements repeat.
- Example Program:
c
#include
Decision Making and Looping
- Definition: Execution of a statement or set of statements repeatedly is called looping.
- Loops execute a specified number of times depending on a test condition.
- Loop Components: 1. Body of the loop. 2. Control condition.
- Classifications by Control Statement Position: 1. Entry Controlled Loop: Control statement is before the body. If the initial test fails, the body never executes. 2. Exit Controlled Loop: Control statement is after the body. The body is executed first, then the condition is checked. The body executes at least once even if the condition is false initially.
- General Steps of a Looping Process: 1. Setting and initialization of a condition variable. 2. Execution of statements within the loop. 3. Test for a specified value of the condition variable. 4. Increasing or updating the condition variable.
- Types of Loops in C: 1. while loop 2. do while loop 3. for loop
While Statement (Entry Controlled)
- The test condition is placed before the body.
- Syntax:
while (test condition) {
body of the loop;
}
```
- Operation: If the expression is true (non-zero), the body executes. It evaluates the expression again and continues until it becomes false ().
- Example (Printing first 10 natural numbers):
c
#include
- Output:
Do-While Statement (Exit Controlled)
- Similar to the while loop but the body executes once before checking the expression.
- The conditional expression appears at the end.
- Syntax:
do {
body of the loop;
} while (test condition);
```
- Example Program:
c
#include
- Output:
For Statement
- An entry-controlled loop providing a concise control structure.
- Syntax:
for(initialization; test-condition; increment or decrement) { body; } - Four Operation Steps: 1. Initialization: Happens once at the beginning. 2. Test Expression Evaluation: If false (), loop terminates. If true (non-zero), body executes. 3. Update: The expression is incremented or decremented. 4. Repeat: Process repeats from the test until the expression is false.
- Commonly used when the number of iterations is known in advance.
- Example Program:
for (i = 1; i <= 5; i++) {
printf("%d \t", i);
}
```
- Nested For Loops: Placing one for statement inside another. Syntax:
c for(initialization; test; update) { for(initialization; test; update) { statement(s); } statement(s); } ```
Break and Continue Statements
- Break Statement:
- Used inside a loop or switch.
- When encountered, the loop is immediately exited, and the program resumes at the statement following the loop.
- Syntax:
break; - Continue Statement:
- Used inside loops to skip the remainder of the current iteration.
- When encountered, the compiler skips the following statements in the loop and resumes the next iteration of the loop.
- Syntax:
continue;
Arrays in C
- Definition: A C Array is a collection of variables belonging to the same data type.
- Features: - Can store groups of data (numbers, characters, employee names, student marks). - Best practice: Initialize to or null during declaration. - Size must be a constant value. - Elements are stored in contiguous (adjacent) memory locations.
- Advantages: A single array variable can store more than one value at a time.
- Examples:
int a[10];(integer array) andchar b[10];(string). - Types of Arrays: 1. One dimensional array. 2. Two dimensional array. 3. Multi-dimensional array (3D, 4D, etc.).
One-Dimensional Arrays
- A single variable name using only one subscript (single-subscripted variable).
- Example: Representing marks (, , , , ) as
int mark[5];. - Storage locations:mark[0]tomark[4]. - Declaration Syntax:
type variable-name[size];- Type: int, float, char. - Size: Maximum number of elements. - Example Strings:
char name[15];for "WELL DONE". Stored as:'W','E','L','L',' ','D','O','N','E','\0'.
Initializing One-Dimensional Arrays
- Compile-Time Initialization:
- Syntax:
type array-name[size] = {list of values};- Initializing all locations:int a[5] = {10, 15, 1, 3, 20};. - Error:int a[3] = {9, 2, 4, 5, 6};(Too many initial values). - Partial initialization:int a[5] = {10, 15};(remaining elements are automatically set to ). - Without size:char b[] = {'C', 'O', 'M', 'P', 'U', 'T', 'E', 'R'};(Size set to automatically). - String initialization:char b[] = "COMPUTER";. - Run-Time Initialization:
- Using functions like
scanfor loops to initialize large arrays. - Example:int x[3]; scanf("%d%d%d", &x[0], &x[1], &x[2]);.
Two-Dimensional Arrays
- Consists of two subscripts; often called an "array of the array".
- Divided into rows and columns, suited for handling tables of data.
- Declaration:
DataType Arrayname[rowsize][columnsize];. - Example:int a[3][3];where the first index is row count and the second is column count. - Initialization:
- Row by row:
int table[2][3] = {0,0,0, 1,1,1};. - Using braces:int table[2][3] = { {0,0,0}, {1,1,1} };. - Omission of size: If completely initialized, the first dimension isn't required:int table[][3] = { {0,0,0}, {1,1,1} };. - Missing values are automatically set to .
Character Arrays and Strings
- C String: A group or array of characters terminated by the delimiter
'\0'(null). - Common Operations: 1. Reading and writing strings. 2. Combining strings together. 3. Copying strings. 4. Comparing strings for equality. 5. Extracting portions of a string.
- Declaration:
char string_name[size];. - Initialization methods:
-
char c[] = "abcd";-char c[50] = "abcd";-char c[] = {'a', 'b', 'c', 'd', '\0'};
String Handling Functions
- Defined in the header file
<string.h>. strcat(string1, string2): Concatenates (appends) string2 to the end of string1. If string1 is "VERY" and string2 is "GOOD", string1 becomes "VERYGOOD".strcmp(string1, string2): Character-by-character ASCII comparison. Returns: -0if strings are equal. - Negative value if string1 is alphabetically above string2. - Positive value if string2 is alphabetically above string1.strcpy(string1, string2): Copies content of string2 into string1. If string1 is "master" and string2 is "madam", string1 becomes "madam".strlen(string): Counts the number of characters in a string, excluding the NULL character.
Input and Output Functions for Strings
- Reading Strings:
- Formatted:
scanf("%s", name);(Does not use '&'). - Unformatted:getchar()(reads single character) andgets(line)(reads string including spaces). - Writing Strings:
- Formatted:
printf("%s", name);. - Unformatted:putchar(ch)(prints character) andputs(line)(prints string with spaces).
Structures
- Definition: A collection of one or more variables of different data types grouped under a single name.
- Tagged Structure: The definition associated with the structure name. It does not allocate memory on its own.
- Syntax:
c struct tag_name { data_type member1; data_type member2; }; - Declaring Variables:
- Together with definition:
} stu1, stu2, stu3;. - Separately:struct student stu1, stu2, stu3;. - Accessing Members: Use the dot [ . ] operator (member access operator).
- Example:
stu1.age = 20;orstrcpy(stu1.name, "Varsha");. - Read via keyboard:scanf("%s", stu1.name);.
Unions
- Definition: A derived data type that is a collection of variables referred to under a single name.
- Difference from Structures: While syntax and declaration are similar, the functionality differs.
- Memory Organization: A union creates a storage location shared by all its members. Only one member can be used at a time. The size of the union is the size of its largest member.
- Example: In a union
uwithchar c,int i, andfloat f, the size is bytes (the size of the float). Assigning a new value to one member supersedes the previous member's value.