Unit 2 - Notes
CSE109
Unit 2: Control structures and Input/output functions
1. Conditional Control Statements
Control structures determine the flow of execution in a program. Conditional statements allow the program to execute specific blocks of code based on whether a condition is true or false.
A. The if Statement
The simplest form of decision control. It executes a block of code only if the specified condition evaluates to true (non-zero).
Syntax:
if (condition) {
// Code to execute if condition is true
}
B. The if...else Statement
This extends the if statement by providing an alternative block of code to execute if the condition is false.
Syntax:
if (condition) {
// Code if true
} else {
// Code if false
}
Example:
int num = 10;
if (num % 2 == 0) {
printf("Even Number");
} else {
printf("Odd Number");
}
C. The else if Ladder
Used when checking multiple conditions sequentially. As soon as one condition is met, its block executes, and the rest of the ladder is skipped.
Syntax:
if (condition1) {
// Block 1
} else if (condition2) {
// Block 2
} else {
// Default block if no conditions are met
}
D. The switch Case Statement
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of an expression. It is often a cleaner alternative to long else if ladders when comparing a variable against constant values.
Key Characteristics:
- The expression must result in an integer or character.
caselabels must be unique constants.- The
breakstatement is crucial; without it, execution "falls through" to the next case. - The
defaultcase executes if no case matches.
Syntax:
switch (expression) {
case constant1:
// code to be executed
break;
case constant2:
// code to be executed
break;
default:
// code to be executed if all cases fail
}
2. Looping (Iteration) Statements
Loops are used to execute a block of code repeatedly until a specified condition becomes false.
A. The while Loop (Entry-Controlled)
The condition is evaluated before the body of the loop is executed. If the condition is false initially, the loop body never runs.
Syntax:
while (condition) {
// Code to be executed
// Increment/Decrement
}
B. The for Loop (Entry-Controlled)
The most concise loop structure, ideal when the number of iterations is known in advance. It groups initialization, condition checking, and increment/decrement in one line.
Syntax:
for (initialization; condition; update) {
// Code to be executed
}
Example:
// Print numbers 0 to 4
for (int i = 0; i < 5; i++) {
printf("%d ", i);
}
C. The do-while Loop (Exit-Controlled)
The condition is evaluated after the body of the loop. This guarantees that the loop body executes at least once, regardless of the condition.
Syntax:
do {
// Code to be executed
} while (condition);
Comparison of Loops
| Feature | while |
for |
do-while |
|---|---|---|---|
| Control | Entry-controlled | Entry-controlled | Exit-controlled |
| Use Case | When iterations are unknown | When iterations are known | When code must run at least once |
| Syntax | Condition at top | Init, Cond, Update at top | Condition at bottom |
3. Jump Statements
Jump statements unconditionally transfer control to another part of the program.
A. break
- Usage: Used inside loops (
for,while,do-while) andswitchstatements. - Action: Terminates the loop or switch immediately. Control resumes at the next statement following the loop/switch.
B. continue
- Usage: Used inside loops.
- Action: Skips the current iteration of the loop. Control jumps to the update statement (in
forloops) or condition check (inwhileloops), effectively starting the next iteration.
C. goto
- Usage: Transfers control to a labeled statement within the same function.
- Note: Generally discouraged ("spaghetti code") as it reduces readability and makes debugging difficult.
- Syntax:
Cgoto label_name; ... label_name: statement;
D. return
- Usage: Used to exit a function.
- Action: Terminates the execution of the current function and returns control (and optionally a value) to the calling function.
4. Type Conversion and Type Modifiers
A. Type Conversion
The process of converting one data type to another.
1. Implicit Conversion (Type Promotion)
- Performed automatically by the compiler.
- Occurs when variables of different types are mixed in an expression.
- Rule: Smaller types are converted to larger types to prevent data loss (e.g.,
inttofloat). - Hierarchy:
bool->char->short int->int->unsigned int->long->float->double.
2. Explicit Conversion (Type Casting)
- Forced by the programmer using the cast operator.
- Useful when you need a specific type result (e.g., floating-point division of two integers).
- Syntax:
(type_name) expression - Example:
Cint a = 5, b = 2; float result = (float)a / b; // Result is 2.5
B. Type Modifiers
Keywords that alter the meaning of basic data types to fit specific situations.
signed: The variable can hold positive and negative values. (Default forintandchar).unsigned: The variable holds only zero and positive values. This doubles the positive range capacity.short: Reduces the storage size (usually 2 bytes forint).long: Increases the storage size (usually 4 or 8 bytes forint, extends precision fordouble).
5. Designing Structured Programs
Structured programming is a paradigm aimed at improving the clarity, quality, and development time of a computer program.
Key Concepts
- Top-Down Design: Breaking a complex problem into smaller, manageable sub-problems (modules/functions). The main module drives the flow, calling sub-modules.
- Modularity: Writing code in distinct functions where each function performs a specific task. This promotes reusability.
- Control Flow structures: Strictly using the three logic structures:
- Sequence: Executing statements one after another.
- Selection: Using conditional statements (
if,switch). - Iteration: Using loops (
for,while).
- Avoidance of Global State: Minimizing the use of global variables to prevent side effects.
- Avoidance of GOTO: Relying on standard control structures rather than unstructured jumps.
6. Input/Output Functions
In C, Input/Output operations are performed using standard library functions found in <stdio.h>.
A. Formatted I/O Functions
These functions allow data to be formatted (type, width, precision) during input or output.
1. printf() (Output)
- Used to print output to the standard output device (console).
- Format Specifiers:
%d(int),%f(float),%c(char),%s(string),%lf(double). - Escape Sequences:
\n(newline),\t(tab). - Example:
Cint age = 20; printf("Age is: %d\n", age);
2. scanf() (Input)
- Used to read formatted input from the standard input (keyboard).
- Requires the address of the variable (
&) for basic data types. - Example:
Cint x; scanf("%d", &x); // Reads an integer into x
B. Unformatted I/O Functions
These functions work specifically with characters or strings and do not require format specifiers. They are generally faster but less flexible.
1. Character I/O
getchar(): Reads a single character from the keyboard. Returns the character as an integer.putchar(ch): Writes a single characterchto the screen.getch()/getche()(Non-standard, often inconio.h):getchreads a character without echoing it to the screen;getchereads and echoes it.
2. String I/O
gets(): Reads a string from stdin until a newline is found.- Warning:
gets()is unsafe and removed from modern C standards (C11) because it does not check buffer length, leading to buffer overflows. Usefgets()instead.
- Warning:
puts(): Writes a string to stdout and automatically appends a newline character.
Example of String I/O:
char name[50];
puts("Enter your name:");
// gets(name); // Unsafe
fgets(name, 50, stdin); // Safe alternative
puts("Hello, ");
puts(name);