0% found this document useful (0 votes)
1 views53 pages

Module - 2 - Notes C Programming

Uploaded by

Sagar Wankhede
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views53 pages

Module - 2 - Notes C Programming

Uploaded by

Sagar Wankhede
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module-2

Console I/O in C: Reading and Writing Characters

● In C programming, console input and output (I/O) refers to taking input from the
keyboard and displaying output on the screen.
● Character I/O means reading or writing one character at a time.

1. Character Input Functions

(a) getchar() Function

● Used to read a single character from the standard input device (keyboard).
● It does not take any arguments.
● It returns the ASCII value of the character read.

Syntax:

int ch;
ch = getchar();

Example:

#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
c = getchar(); // reads a single character
printf("You entered: ");
putchar(c); // prints that character
return 0;
}

Explanation:

● If you type A and press Enter → getchar() reads A.


● The ASCII value of A (65) is stored in c.
● putchar(c) prints A on the screen.

(b) getch() Function (non-standard, from <conio.h>)

● Reads a single character without waiting for Enter key.


● The character is not displayed on the screen.
● Commonly used in Turbo C or DOS-based compilers.

Example:

#include <stdio.h>
#include <conio.h>
int main()
{
char c;
printf("Press any key: ");
c = getch(); // reads char without echo
printf("\nYou pressed: %c", c);
return 0;
}

(c) getche() Function

● Similar to getch(), but echoes the character (displays it on the screen).

Example:

#include <stdio.h>
#include <conio.h>
int main() {
char c;
printf("Press a key: ");
c = getche(); // reads and displays char
printf("\nYou pressed: %c", c);
return 0;
}

2. Character Output Functions

(a) putchar() Function

● Used to display a single character on the screen.


● It takes a character as an argument and writes it to the console.

Syntax: putchar(character);

Example:

#include <stdio.h>
int main()
{
char ch = 'B';
putchar(ch); // displays B
return 0;
}

(b) putch() Function

● Similar to putchar(), but it does not use buffering (faster output).


● Often used in Turbo C.

Example:

#include <stdio.h>
#include <conio.h>
int main()
{
char ch = 'Z';
putch(ch); // displays Z
return 0;
}

Reading and Writing Strings


● In C programming, a string is a sequence of characters terminated by a null character ('\
0').
● For example, "Hello" is stored as: 'H' 'e' 'l' 'l' 'o' '\0'

C provides several functions for reading and writing strings through the console.

1. Reading Strings (Input Functions)


(a) Using scanf() Function
● The simplest way to read a string is by using the scanf() function with the format
specifier %s.
● scanf() reads characters until a whitespace (space, tab, or newline) is encountered.

Syntax: scanf("%s", string_variable);


Example:
#include <stdio.h>
int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!", name);
return 0;
}
Input: Enter your name: Manoj Kumar
Output: Hello, Manoj!

Explanation:
Only Manoj is read, because scanf() stops reading at the first space.
Hence, it cannot read multi-word strings.

(b) Using gets() Function


● The gets() function reads a line of text, including spaces, until the Enter key is pressed.
● It automatically adds the null character '\0' at the end.

Syntax: gets(string_variable);
Example:
#include <stdio.h>
int main() {
char sentence[50];
printf("Enter a sentence: ");
gets(sentence);
printf("You entered: %s", sentence);
return 0;
}

Input: Enter a sentence: I love programming in C


Output: You entered: I love programming in C

⚠️ Note:
gets() is unsafe because it does not check for buffer overflow.

(c) Using fgets() Function


● fgets() reads a string including spaces from a given stream (like stdin).
● It also limits the number of characters read, preventing overflow.

Syntax: fgets(string_variable, size, stdin);


Example:
#include <stdio.h>
int main()
{
char line[50];
printf("Enter a line: ");
fgets(line, sizeof(line), stdin);
printf("You entered: %s", line);
return 0;
}

Explanation:
● fgets() reads at most (size – 1) characters.
● It includes the newline character \n if the user presses Enter before reaching the limit.

2. Writing Strings (Output Functions)


(a) Using printf() Function
● The most common method to print strings.
● Uses the %s format specifier.
Syntax: printf("%s", string_variable);

Example:
#include <stdio.h>
int main() {
char name[] = "C Programming";
printf("Welcome to %s!", name);
return 0;
}
Output: Welcome to C Programming!

(b) Using puts() Function

● Writes a string to the standard output (screen).


● Automatically adds a newline (\n) at the end.

Syntax: puts(string_variable);

Example:

#include <stdio.h>
int main() {
char msg[] = "Learning C is fun!";
puts(msg);
return 0;
}

Output: Learning C is fun!

Formatted Console I/O in C


In C programming, formatted input and output allows us to read and display data in a specific
format.
This is done using the two main functions:
● printf() → For formatted output (writing data to the screen)

● scanf() → For formatted input (reading data from the keyboard)

These are standard I/O functions defined in the header file <stdio.h>.
1. Formatted Output Function — printf()
● The printf() function is used to display information on the console in a formatted way.
● It allows us to print text, numbers, characters, and strings with specific formatting.

Syntax: int printf(const char *control_string, ...);


Return Value
It returns:
● The number of characters successfully printed, or
● A negative value if an error occurs.

Example 1: printf("Sum = %d", sum);


Here:
● "Sum = %d" → is the format string.

● %d → is a format specifier (it tells printf() to print an integer value).

● sum → is the variable whose value will be printed.

Example 2 : printf("I like %c %s", 'C', "very much!");

Common Format Specifiers for printf()

Format Data Type Description / Example Output


Specifier

%d or %i int Prints a signed decimal integer. Example: printf("%d", 25); → 25

%u unsigned int Prints an unsigned decimal integer. Example: printf("%u", 25); →


25

%f float or double Prints a floating-point number with 6 digits after decimal by


default. Example: printf("%f", 3.14); → 3.140000

%0.2f float or double Prints a floating-point number rounded to 2 decimal places.


Example: printf("%.2f", 3.14159); → 3.14

%c char Prints a single character. Example: printf("%c", 'A'); → A


%s char[] (string) Prints a string of characters. Example: printf("%s", "Hello"); →
Hello

%ld long int Prints a long signed integer. Example: printf("%ld", 123456L); →
123456

%lu unsigned long int Prints an unsigned long integer. Example: printf("%lu",
123456UL); → 123456

%lld long long int Prints a long long signed integer. Example: printf("%lld",
123456789LL); → 123456789

%llu unsigned long Prints an unsigned long long integer. Example: printf("%llu",
long int 123456789ULL); → 123456789

%e or %E float or double Prints a floating-point number in exponential (scientific) form.


Example: printf("%e", 3.14); → 3.140000e+00

%g or %G float or double Prints a floating-point number in normal or exponential form,


whichever is shorter.

%x unsigned int Prints an integer in hexadecimal (lowercase). Example:


printf("%x", 255); → ff

%X unsigned int Prints an integer in hexadecimal (uppercase). Example:


printf("%X", 255); → FF

%o unsigned int Prints an integer in octal form. Example: printf("%o", 8); → 10

%p Pointer (address) Prints the memory address stored in a pointer. Example:


printf("%p", ptr); → 0x7ffdec2a

%% Literal % sign Prints a percent symbol. Example: printf("%%"); → %

Example Program 1
#include <stdio.h>
int main() {
int roll = 101;
float marks = 89.75;
char grade = 'A';
char name[] = "Manoj";

printf("Name: %s\n", name);


printf("Roll No: %d\n", roll);
printf("Marks: %.2f\n", marks);
printf("Grade: %c\n", grade);
return 0;
}

Output:

Name: Manoj
Roll No: 101
Marks: 89.75
Grade: A

Example Program 2:
#include <stdio.h>
int main(void)
{
printf("%d\n", 25); // prints integer
printf("%u\n", 40000); // prints unsigned integer
printf("%f\n", 3.142); // prints floating-point number
printf("%e\n", 12345.5); // scientific notation
printf("%x\n", 255); // hexadecimal (lowercase)
printf("%X\n", 255); // hexadecimal (uppercase)
printf("%o\n", 255); // octal

Output:
25
40000
3.142000
1.234550e+004
ff
FF
377

%n format specifier
● The %n format specifier in printf() is a special code that does not print anything.
● Instead, it stores the number of characters printed so far into an integer variable
provided through a pointer.
● %n tells printf() to count the characters it has printed up to that point and store that
number in a variable whose address is given as an argument.
Example:

#include <stdio.h>
int main(void)
{
int count=0;
printf("this%n is a test\n", &count);
printf("Value stored in count: %d\n", count);
return 0;
}
output:
this is a test
Value stored in count: 4

Explanation:

● "this" → prints 4 characters.


● %n → stores 4 into count (number of characters printed so far).

● " is a test\n" → prints rest of the text.

● Second printf → prints the value of count (which is 4).

Precision Specifier in printf()


The precision specifier in C is used with the printf() function to control:
1. Number of digits after the decimal point (for floating-point numbers)
2. Maximum number of characters to print (for strings)

The precision specifier is written as: %.nf


Where:
● n → number of digits after the decimal point (for floating-point numbers)

● For strings → maximum number of characters to print

1. Precision with Floating-Point Numbers


When printing floating-point numbers (%f, %e, %E):
● Precision controls how many digits appear after the decimal point.
● The default precision for %f is 6.

Syntax: printf("%.nf", value);

Example:
#include <stdio.h>
int main()
{
float num = 3.141592;
printf("%.2f\n", num);
printf("%.4f\n", num);
printf("%.0f\n", num);
return 0;
}

Output:
3.14
3.1416
3

Explanation:
● %.2f → prints 2 digits after decimal → 3.14

● %.4f → prints 4 digits → 3.1416

● %.0f → no decimal digits → rounded → 3

2. Precision with Strings


When printing strings (%s):
● Precision limits the number of characters printed.
● If the string length exceeds n, only the first n characters are printed.

Syntax: printf("%.ns", string);

Example:
#include <stdio.h>
int main() {
char str[] = "HelloWorld";
printf("%.5s\n", str);
printf("%.8s\n", str);
return 0;
}

Output:
Hello
HelloWor

Explanation:
● %.5s → prints first 5 characters of string → Hello

● %.8s → prints first 8 characters → HelloWor

3. Precision with %g and %G


For %g and %G format specifiers:
● Precision specifies maximum significant digits (not just digits after decimal).
● Trailing zeros are removed unless necessary.

Example:
#include <stdio.h>
int main() {
double num = 123.456789;
printf("%.4g\n", num);
printf("%.6g\n", num);
return 0;
}

Output:
123.5
123.457

4. Minimum Field Width (m) and Precision (.n) for Integers

When using %[Link] in printf():

❖ Precision .n
● For integers, .n specifies the minimum number of digits to print.
● If the integer has fewer digits, leading zeros are added
● If the integer already has equal or more digits, it prints normally.

Example: printf("%.5d", 23);


Output: 00023
(23 → 2 digits, .5 forces 5 digits → add 3 leading zeros)

❖ Minimum Field Width m


➢ m specifies the minimum width of the output field.
➢ If the printed number (after applying precision) is shorter than m, it is padded
with spaces (default) to make up the width.
➢ Padding is added before the number (right-aligned).
Example: printf("%8d", 23);
Output: 23

(2 digits → width 8 → 6 spaces added)

❖ When m and .n both appear: %[Link]


➢ First, precision .n is applied → determines the minimum digits.

➢ Then, minimum width m is applied → determines if extra spaces are needed.

Rule:
If .n produces a number wider than m, m is ignored.

Example: printf("%3.8d", 10);

● .8 → 8 digits → "00000010".

● m = 3 → less than 8 → ignored.

Output: 00000010
Another example: printf("%10.3d", 10);

● .3 → "010" (3 digits).

● m = 10 → width = 10 → 7 spaces added before "010".

Output: 010

Left and Right Justification in printf()


When printing data using printf(), justification controls where padding spaces are added
when the output is shorter than the specified minimum width.

1. Right Justification (Default)


● By default, printf() right-aligns the output.
● Padding spaces are added before the value.
● This is the standard behavior without any special flags.

Example: printf("|%8d|\n", 123);


● %8d → minimum width = 8.

● Number "123" has length = 3 → add 5 spaces before it.

Output: | 123|
(Spaces before the number)

2. Left Justification
● Left justification is done by adding a - flag before the width.
● Padding spaces are added after the value.
● This makes the value align to the left side of the field.

Example: printf("|%-8d|\n", 123);


● %-8d → left justify, minimum width = 8.

● Number "123" has length = 3 → add 5 spaces after it.

Output: |123 |
(Spaces after the number)

Handling Other Data Types

1. Handling Other Data Types in printf()


● In printf(), format modifiers tell the compiler the exact data type of the argument.
● They go between % and the format specifier.
Common Modifiers for integers and floating points:

Modifier Meaning Example

l Long integer (long int) or wide character/string %ld

h Short integer (short int) %hd

hh Signed/unsigned char (C99) %hhd

ll Long long integer (long long int) %lld

L Long double (long double) %Lf

Examples:
long int a = 100000;
printf("%ld", a); // Prints long integer

short int b = 10;


printf("%hd", b); // Prints short integer

2. The # Modifier
● The # flag changes the appearance of the output for certain format specifiers.
Format Specifier Effect

%o Adds a leading 0 (octal numbers)

%x, %X Adds 0x or 0X prefix (hexadecimal)

%f, %e, %E, %g, %G Forces decimal point even if no decimals

%a (C99) Forces decimal point

Example:
printf("%#x\n", 10); // Output: 0xa
printf("%#o\n", 10); // Output: 012
printf("%#f\n", 10); // Output: 10.000000

3. The * Modifier
● The * modifier allows dynamic control of minimum field width and precision.
● Instead of hardcoding width or precision in the format string, they are taken from
arguments.
Syntax: %*.*specifier
● First * → field width

● Second * → precision

Example:
#include <stdio.h>
int main(void) {
printf("%*.*f", 10, 4, 1234.34);
return 0;
}

Explanation:
● 10 → minimum field width

● 4 → precision (decimal places)

● 1234.34 → value to print

Output: 1234.3400
(Spaces added before number to make total width = 10, decimals rounded to 4 places.)

Another example: printf("%x %#x\n", 10, 10);

● %x → prints hex without prefix → a

● %#x → prints hex with prefix → 0xa

Output: a 0xa

2. Formatted Input Function — scanf()


● The scanf() function is used to take input from the user in a formatted way.
● It allows the program to read integers, floats, characters, and strings according to
specified format specifiers.
Syntax : scanf("format string", &variable1, &variable2, ...);

int scanf(const char *control_string, ...);


Returns:
● the number of input items successfully assigned.
● If an error occurs, returns EOF.
● control_string defines how the input should be interpreted.

Example: scanf("%d %f", &age, &height);


Here:
%d → expects an integer input.

%f → expects a floating-point input.

& (address-of operator) → tells scanf() where to store the value in memory.

Example:
#include <stdio.h>
int main()
{
int age;
float height;
char grade;
char name[20];

printf("Enter your name, age, height, and grade:\n");


scanf("%s %d %f %c", name, &age, &height, &grade);

printf("\nStudent Details:\n");
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Grade: %c\n", grade);

return 0;
}
Input:
Manoj 20 5.8 A

Output:
Student Details:
Name: Manoj
Age: 20
Height: 5.80
Grade: A

Controlling Input Format in C (scanf())


The scanf() function allows fine control over how input is read. This is useful to ensure data is
read correctly and to avoid errors. Controlling input format involves:

1. White-space handling
2. Maximum field width
3. Non-white-space characters in control string
4. Assignment suppression (*)
5. Scansets (%[...])

1. White-space Handling

● Any white-space character in the control string (space, tab, newline) tells scanf() to skip
all leading whitespace until the next non-whitespace character.
● Works for numeric and string inputs.

Example Program:

#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers:\n");
scanf("%d %d", &a, &b);
printf("First: %d, Second: %d\n", a, b);
return 0;
}
Input:
10
20

Output: First: 10, Second: 20

2. Maximum Field Width


● Limits how many characters are read into a variable.
● Prevents buffer overflow when reading strings.
● Syntax: %<width><specifier>
Example Program:
#include <stdio.h>
int main() {
char str[10];
printf("Enter a string: ");
scanf("%5s", str);
printf("You entered: %s\n", str);
return 0;
}

Input:
HelloWorld

Output:
You entered: Hello

3. Non-white-space Characters in Control String


● Characters other than % or white-space must match exactly in the input.
● If they do not match, scanf() stops reading.
Example Program:
#include <stdio.h>
int main() {
int x, y;
printf("Enter two numbers separated by a comma:\n");
scanf("%d,%d", &x, &y);
printf("x = %d, y = %d\n", x, y);
return 0;
}

Input: 10,20
Output: x = 10, y = 20
(If you enter 10 20 → scanf fails.)

4. Assignment Suppression (*)


● Use * before a format specifier to read input but not store it.
● Useful when you want to skip unwanted characters or delimiters.

Example Program:
#include <stdio.h>
int main() {
int x, y;
printf("Enter two numbers separated by a comma:\n");
scanf("%d%*c%d", &x, &y);
printf("x = %d, y = %d\n", x, y);
return 0;
}

Input: 10,20
Output: x = 10, y = 20
(The comma is read but not stored.)
What %d%*c%d means
In scanf():
● %d → read an integer

● %*c → read a character but ignore it (* means assignment suppression)

● %d → read another integer

So %d%*c%d means:
1. Read first integer → store in x

2. Read a single character → ignore it

3. Read second integer → store in y

5. Scanset (%[...])

● Reads only specific characters defined in the set.


● Stops when a character not in the set is encountered.
● Null-terminates the string.

Syntax: %[characters] or %[^characters] (inverted)

Example

#include <stdio.h>
int main() {
char str[20];
printf("Enter string with only a, b, c:\n");
scanf("%[abc]", str);
printf("Read string: %s\n", str);
return 0;
}
Input:
Enter string with only a, b, c:
abcashods
output:
Read string: abca

Inverted scanset Example:

#include <stdio.h>
int main() {
char str[20];
printf("Enter string until digit is found:\n");
scanf("%[^0-9]", str);
printf("Read string: %s\n", str);
return 0;
}

Input: hello123world

Output: Read string: hello


Selection Statements

Decision Control Statements in C


● Decision control statements are used to alter the normal flow of a program.
● Normally, C executes statements one by one.
● Using decision statements, a program can execute some part of the code only if a
condition is satisfied.
● These statements help a program decide which block of code to execute depending on a
condition.

Types of Decision Control Statements

1. if statement
2. if-else statement
3. if-else if statement
4. switch statement

1. if Statement
The if statement is the simplest decision statement. It executes a block of code only if a
condition is true.
Syntax:
if (condition)
{
// statements executed if condition is true
}

Data Flow Diagram for if condition:


Example: Check voting eligibility
#include <stdio.h>
void main()
{
int age;
printf("Enter the age: ");
scanf("%d", &age);
if(age >= 18)
{
printf("He/she is eligible to vote\n");
}
}

Explanation:
● The condition (age >= 18) is checked.
● If true → the message is printed.
● If false → nothing happens, the program moves to the next statement.

2. if-else Statement
● The if-else statement executes one of two blocks depending on whether the condition is
true or false.
● It executes the if block if the condition is true otherwise the else block is executed.

Syntax:
if (condition) {
// executed if condition is true
} else {
// executed if condition is false
}
Data Flow Diagram:

Examples:
a) Check Even or Odd Number
#include <stdio.h>
void main() {
int a;
printf("Enter a number: ");
scanf("%d", &a);
if(a % 2 == 0) {
printf("The number is even\n");
} else {
printf("The number is odd\n");
}
}
Example:

Input : 12
Output : The number is even
Input : 7
Output : The number is odd

b) Check Vowel or Consonant


#include <stdio.h>
void main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if(ch=='a'||ch=='A'||ch=='e'||ch=='E'||ch=='i'||ch=='I'||ch=='o'||ch=='O'||ch=='u'||ch=='U')
{
printf("The character %c is a vowel.\n", ch);
} else {
printf("The character %c is a consonant.\n", ch);
}
}
Example:
Input Output

A The character A is a vowel.

C The character C is a consonant.

c) Largest of Two Numbers


#include <stdio.h>
void main() {
int a = 100, b = 20;
if(a < b)
printf("b is largest\n");
else
printf("a is largest\n");
}

Output: a is largest

d) Convert Uppercase to Lowercase and Vice Versa


#include <stdio.h>
void main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if(ch >= 'A' && ch <= 'Z')
printf("Lowercase: %c\n", ch + 32);
else
printf("Uppercase: %c\n", ch - 32);
}

Example:
Input Output

A Lowercase: a

k Uppercase: K

e) Check Leap Year


#include <stdio.h>
void main() {
int year;
printf("Enter any year: ");
scanf("%d", &year);
if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
printf("Leap year\n");
else
printf("Not a leap year\n");
}

Example:

Input Output

2000 Leap year

1900 Not a leap year

2024 Leap year

2023 Not a leap year

Explanation:
● The condition is checked first.
● If true → the first block executes.

● If false → else block executes.


● After execution, the program continues to the next statement.
3. if-else if Statement
● if-else if is used when there are multiple conditions to check.
● Only the block with the first true condition is executed.
Syntax:
if (condition1)
{
// executed if condition1 is true
} else if (condition2)
{
// executed if condition2 is true
} else
{
// executed if none of the above conditions are true
}

DataFlow Diagram:

Example: Find the largest of three numbers


#include <stdio.h>
void main()
{
int a = 10, b = 20, c = 15;
if(a > b && a > c)
printf("a is largest\n");
else if(b > a && b > c)
printf("b is largest\n");
else
printf("c is largest\n");
}

Example:
Input (a,b,c) Output

10, 20, 15 b is largest

30, 20, 10 a is largest

10, 20, 25 c is largest

4. Nested if Statement
A nested if statement is an if or if-else statement inside another if or else block. It is
used when a decision depends on another decision.

Syntax

if(condition1)
{
// executed if condition1 is true
if(condition2)
{
// executed if condition2 is true
}
else
{
// executed if condition2 is false
}
} else
{
// executed if condition1 is false
}

Rules for Nested if

1. Inner if executes only if outer if is true.


2. You can nest multiple if statements, but avoid too many levels (for readability).
3. else belongs to the nearest unmatched if.
4. Braces {} are recommended to avoid confusion.

Example 1: Find Largest of Three Numbers

#include <stdio.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("a is largest\n");
else
printf("c is largest\n");
} else {
if(b > c)
printf("b is largest\n");
else
printf("c is largest\n");
}
}
Sample input/output:

Input (a,b,c) Output

10, 20, 15 b is largest

30, 20, 10 a is largest

10, 20, 25 c is largest

5. switch Statement
Switch is used to select one block from many options based on the value of a variable.

Rules for switch:

1. The variable in switch must be integer or character type.


2. Each case must have a unique constant value.
3. Use break to exit the switch, otherwise execution continues to the next case.
4. default is optional but executed if no case matches.

Syntax:

switch(variable)
{
case value1:
// statements
break;
case value2:
// statements
break;
...
default:
// statements if no case matches
}

DataFlow Diagram:

Example 1: Find the day of the week

#include <stdio.h>
void main()
{
int day;
printf("Enter a number (1-7): ");
scanf("%d", &day);
switch(day) {
case 1: printf("Sunday\n"); break;
case 2: printf("Monday\n"); break;
case 3: printf("Tuesday\n"); break;
case 4: printf("Wednesday\n"); break;
case 5: printf("Thursday\n"); break;
case 6: printf("Friday\n"); break;
case 7: printf("Saturday\n"); break;
default: printf("Invalid input\n");
}

Example

Input Output

1 Sunday

4 Wednesday

8 Invalid input

Example 2: Simple Calculator Using Switch


#include <stdio.h>
void main() {
char op;
float num1, num2, result;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &op);

printf("Enter two numbers: ");


scanf("%f %f", &num1, &num2);

switch(op) {
case '+':
result = num1 + num2;
printf("Result: %.2f\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2f\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2f\n", result);
break;
case '/':
if(num2 != 0)
printf("Result: %.2f\n", num1 / num2);
else
printf("Error: Division by zero\n");
break;
default:
printf("Invalid operator\n");
}
}
Sample input/output

Input Output

+, 10, 5 Result: 15.00

-, 12, 7 Result: 5.00

*, 4, 6 Result: 24.00

/, 20, 4 Result: 5.00


/, 10, 0 Error: Division by zero

%, 5, 2 Invalid operator

1. Valid /invalid Expressions for Switch Variable

Switch Variable Valid / Example Explanation


Invalid

Integer (int) Valid switch(a) int type works directly.

Character (char) Valid switch(ch) Characters are stored as ASCII


integers.

Short (short) Valid switch(s) Short integer works.

Long (long) Valid switch(l) Long integer works.

Enum type Valid switch(color) Enums are internally integer


constants.

Float (float) Invalid switch(f) Switch cannot evaluate float/double.

Double (double) Invalid switch(d) Not allowed.

String (char str[]) Invalid switch(str) Switch cannot handle strings.

Boolean (C99 _Bool) Valid switch(flag) Treated as integer 0 or 1.

Expression (a+b) Valid switch(a+b) Must evaluate to integer or char.

Logical expression Valid switch(a>5) Returns 0 (false) or 1 (true).


(a>5)
2. Valid / invalid Case Values

Case Value Valid / Example Explanation


Invalid

Integer literal Valid case 1: Simple constant value.

Character literal Valid case 'A': ASCII value is used internally.

Hexadecimal literal Valid case 0x1F: Constant value in hex is valid.

Octal literal Valid case 012: Octal constants are valid.

Const variable Valid const int x=5; case x: Const evaluated at compile-
time.

Enum constant Valid case RED: Enum constants are integer


values.

Expression with Valid case 2+3: Evaluated at compile-time.


constants

Variable (non-const) Invalid case a: Must be constant, cannot be


variable.

Float / double Invalid case 3.5: Not allowed.

String Invalid case "A": Switch cannot compare strings.

Iteration Statements

● Iteration statements, also called loops, allow a program to repeat a block of code
multiple times until a condition is satisfied.
● They are used when the same task needs to be performed repeatedly.
Purpose:

● To avoid writing the same code multiple times.


● To repeat tasks until a condition becomes false or true.

Types of Loops in C

1. while loop
2. do-while loop
3. for loop
4. Nested loops

1. while Loop

● The while loop executes a block of statements as long as a condition is true.


● It is called a pre-test loop because the condition is checked before entering the loop body.
● If the condition is false initially, the loop may never execute.

Syntax:
while(condition)
{
// statements
}
Flow Diagram:
Rules:

1. Condition must return true (non-zero) or false (0).


2. The loop variable must be updated inside the loop to avoid an infinite loop.
3. Can be used when the number of iterations is unknown in advance.

Example: Sum numbers from 1 to 5

#include <stdio.h>
void main()
{
int i = 1, sum = 0;
while(i <= 5)
{
sum += i;
i++;
}
printf("Sum = %d\n", sum);
}
Output:
Sum = 15

2. do-while Loop

● do-while is also called post-test loop that means the loop body executes first, then the
condition is checked.
● Guarantees at least one execution even if the condition is false.

Syntax:

do {
// statements
} while(condition);

Flow diagram:

Rules:
1. Condition works same as while.
2. Useful when input or action must happen at least once, like reading user input.
3. Semicolon after while(condition); is mandatory.

Example: Print numbers 1 to 3

#include <stdio.h>
void main()
{
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 3);
}

Output:

123

3. for Loop

● for loop is used when number of iterations is known.


● Combines initialization, condition, and increment/decrement in a single line.
● Pre-test loop: condition is checked before each iteration.

Syntax:

for(initialization; condition; increment/decrement)


{
// statements
}
➢ Initialization
○ This part is executed only once at the beginning of the loop.
○ It usually declares or sets the starting value of the loop variable.
○ Example: int i = 0; → sets i to 0 before the loop starts.
➢ Condition
○ This is checked before every iteration of the loop.
○ If the condition is true, the loop executes the statements inside.
○ If the condition is false, the loop stops.
○ Example: i < 5 → loop continues as long as i is less than 5.
➢ Increment/Decrement
○ This is executed after each iteration of the loop body.
○ It updates the loop variable so the loop moves towards ending.
○ Example: i++ → increases i by 1 after every iteration.
➢ Statements ({ ... })
○ This is the block of code that is repeated as long as the condition is true.
○ Can contain one or more statements.
○ Example: printf("%d ", i); → prints the value of i each time.

FlowDiagram:
Example: Print 1 to 5 using for

#include <stdio.h>
void main() {
int i;
for(i = 1; i <= 5; i++)
printf("%d ", i);
}

Output:

12345

Jump Statements
Jump statements transfer the control of program execution from one part to another.

Types of Jump Statements in C:

1. break
2. continue
3. goto
4. return

1. break Statement

● The break statement is used to terminate a loop or a switch statement immediately.


● When break is executed, control comes out of the loop or switch and continues with the
next statement after it.
● Mostly used in:
○ Loops (for, while, do-while) when we want to stop early.
○ switch-case to exit a case after execution.

Example with loop:

#include <stdio.h>
int main() {
for(int i=1; i<=5; i++)
{
if(i == 3)
break; // exit loop immediately
printf("%d\n", i);
}
return 0;
}
Output:

1
2

2. continue Statement
● The continue statement skips the current iteration of the loop and moves control to the
next iteration.
● Useful when we want to ignore some cases but continue looping.
Example:
#include <stdio.h>
int main() {
for(int i=1; i<=5; i++)
{
if(i == 3)
continue; // skip iteration when i=3
printf("%d\n", i);
}
return 0;
}

Output:
1
2
4
5

3. goto Statement
● The goto statement is used to jump to a labeled statement in the same function.

● Its use is discouraged in modern programming because it makes code difficult to read.
Syntax:
goto label_name;
...
label_name: statement;

Example:
#include <stdio.h>
int main() {
int i = 1;
start: // label
if(i <= 5)
{
printf("%d\n", i);
i++;
goto start; // jump back to label
}
return 0;
}

Output:
1
2
3
4
5

4. return Statement

● The return statement is used in functions to exit the function and optionally send a value
back to the caller.
Example:
#include <stdio.h>
int square(int n)
{
return n * n; // return value
}
int main()
{
int result = square(5);
printf("Square = %d", result);
return 0;
}

Output:
Square = 25

Block Statements in C
1. A block statement is a group of one or more statements enclosed within curly braces { }.
2. The compiler treats the whole block as a single statement, so it is also called a compound
statement.
3. A block can contain both declarations (like variable definitions) and executable
statements (like assignments, loops, function calls)
4. Blocks are required when C syntax allows only one statement but we need to write
multiple statements.
○ Example: after if, else, for, while, or do-while.
5. The body of every function in C is a block statement.
6. A block does not end with a semicolon. Only the statements inside it require semicolons.
7. A block introduces a new scope.
○ Variables declared inside a block exist only within that block.
○ They cannot be accessed outside the block.
8. Blocks can be nested, meaning a block can contain another block.
9. An empty block written as { } is allowed and is sometimes used as a placeholder.

General Form

{
statement1;
statement2;
...
statementN;
}

Example 1: Block in if-else

#include <stdio.h>
int main()
{
int x = 10;
if (x > 5)
{
// Block statement
printf("x is greater than 5\n");
x++;
printf("Now x = %d\n", x);
} else
{
// Another block
printf("x is 5 or less\n");
}
return 0;
}

Example 2: Block in Loops

#include <stdio.h>
int main() {
for(int i=1; i<=3; i++) {
// block
{
int square = i * i;
printf("Square of %d = %d\n", i, square);
}
}
return 0;
}

Example 3: Function Body as a Block

int add(int a, int b) {


// block
int sum = a + b;
return sum;
}

Important Notes
● A block creates a new scope.
● Variables declared inside a block are local to that block and cannot be used outside.
● Nested blocks (block inside another block) are allowed.
● A block may also be empty, like { }. This is sometimes used as a placeholder.

You might also like