0% found this document useful (0 votes)
8 views14 pages

C 2nd Module Notes

The document provides an overview of input and output operations in C programming, detailing console and file I/O functions, including character and string I/O functions. It explains various types of statements such as selection, iteration, and jump statements, along with their syntax and examples. Additionally, it covers the concept of true and false in C, as well as the structure of expression and block statements.

Uploaded by

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

C 2nd Module Notes

The document provides an overview of input and output operations in C programming, detailing console and file I/O functions, including character and string I/O functions. It explains various types of statements such as selection, iteration, and jump statements, along with their syntax and examples. Additionally, it covers the concept of true and false in C, as well as the structure of expression and block statements.

Uploaded by

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

Introduction

 C language does not have built-in commands for input and output.
 All I/O operations are done using library functions present in the header file
<stdio.h> (Standard Input/Output header).
 These functions allow the program to take input from the keyboard, display
output on the screen, or read/write data from files.

Types of I/O in C
There are two main types of I/O:

1. Console I/O
 Input is taken from the keyboard.
 Output is displayed on the screen.
Example: scanf(), printf(), getchar(), putchar(), gets(), puts().

2. File I/O
 Input and output operations are done with files stored on disk.
Example: fopen(), fprintf(), fscanf(), fclose().

Character I/O Functions


1. getchar()
 Reads a single character from the keyboard.
 Returns EOF (-1) if an error occurs or end of file is reached.
Example:
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c", ch);
Advantages:
 Simple and easy to use.
 Reads one character at a time, useful in loops.
 Works for both text and special characters.
Disadvantages:
 Can only read one character at a time.
 Needs Enter key press after each input.
 Not suitable for large inputs.
2. putchar()
 Writes a single character to the screen.
Example:
putchar('A'); // Output: A

Example Program using getchar() and putchar()


#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
printf("Enter text (type . to stop): ");
do {
ch = getchar();
if (islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while (ch != '.');
return 0;
}
Explanation:
Reads characters one by one.
Converts lowercase to uppercase and vice versa.
Stops when . is entered.
Advantages:
 Simple function for displaying one character.
 Useful in loops to display many characters one by one.
 Fast and efficient for single-character output.
Disadvantages:
 Can print only one character at a time.
 Not suitable for printing strings or formatted data.
String I/O Functions
1. gets()
 Reads a line of text from the keyboard.
 Stores it in a character array.
 Does not check array limits (may cause buffer overflow).
Example:
char name[20];
gets(name);
Advantages:
 Easy way to input complete strings (including spaces).
 No need to specify format specifiers.
Disadvantages:
 Unsafe function – it doesn’t check array boundaries.
 Can cause buffer overflow, so not recommended.
 Removed from the C11 standard.

2. puts()
 Displays a string on the screen followed by a newline.
Example: puts(name);
Advantages:
 Simple and fast way to print strings.
 Automatically adds a newline character at the end.
 Safer than printf() for strings.
Disadvantages:
 Cannot print formatted data (e.g., numbers with strings).
 Always prints a newline at the end (no control over it).

Formatted I/O Functions


1. printf()
 Used to display formatted output on screen.
 Supports format specifiers like %d, %f, %c, %s.

Syntax: printf(format_ specifiers, variable, variable,…….);


Example:
int age = 20;
printf("My age is %d", age);
Advantages:
 Powerful for formatted output (text + numbers).
 Can display multiple values easily.
 Widely supported and flexible.
Disadvantages:
 Slightly slower for large outputs.
 Formatting errors can lead to wrong display.
 Cannot take user input (output only).

2. scanf()
 Used to take formatted input from user.
 Uses address operator (&) to store data in variables.
Syntax: scanf(“%d %c”, &info_a, &info_b);
Example:
int age;
scanf("%d", &age);
Advantages:
 Can read multiple values at once.
 Supports various data types (int, float, char, string).
 Widely used for all kinds of user inputs.
Disadvantages:
 Requires & (address) operator for variables.
 Stops reading strings at space (can’t take full sentence).
 Input errors may cause unexpected results.

Common Format Specifiers


Specifier Meaning
%d Integer
%f Floating number
%c Character
%s String
%lf Double
%x Hexadecimal integer
Statements
In the most general sense, a statement is a part of your program that can be
executed. That is, a statement specifies an action. C categorizes statements into
these groups:

• Selection
• Iteration
• Jump
• Label
• Expression
• Block
Included in the selection statements are if and switch. (The term conditional
statement is often used in place of selection statement.)

The iteration statements are while, for, and do-while. These are also commonly
called loop statements.

The jump statements are break, continue, goto, and return.

The label statements include the case and default statements (discussed along
with the switch statement) and the label statement itself (discussed with goto).

Expression statements are statements composed of a valid expression.

Block statements are simply blocks of code. (A block begins with a{ and ends
with a }.)
Block statements are also referred to as compound statements.

True and False in C


A conditional expression evaluates to either a true or false value.
 In C, true is any nonzero value, including negative numbers.
 A false value is 0.
 This approach to true and false allows a wide range of routines to be
coded extremely efficiently.
Selection Statements in C
� Definition:
Selection statements are used to make decisions in a C program.
They allow the program to choose different paths of execution depending on
the result of a condition (true or false).

C provides two main selection statements:


1. if statement
2. switch statement

� 1. if Statement
The if statement is used to test a condition.
If the condition is true, a block of code runs; otherwise, it is skipped.

Syntax:
if (condition)
{
// statements
}

Example:
int a = 10;
if (a > 5)
{
printf("a is greater than 5");
}
Output:
a is greater than 5

� 2. if-else Statement
The if-else statement runs one block of code when the condition is true, and
another when it is false.
Syntax:
if (condition)
statement1;
else
statement2;
Example:
int num = 7;
if (num % 2 == 0)
printf("Even");
else
printf("Odd");
Output:
Odd

� 3. Nested if Statement
An if statement inside another if statement is called a nested if.
It is used when one condition depends on another.

Example:
int a = 10, b = 20;
if (a < b)
{
if (b == 20)
printf("Both conditions are true");
}
Output:
Both conditions are true

� 4. if-else-if Ladder
Used to test multiple conditions one after another.
As soon as one condition is true, the related statement is executed, and others
are skipped.
Syntax:
if (condition1)
statement1;
else if (condition2)
statement2;
else
statement3;
Example:
int marks = 85;
if (marks >= 90)
printf("Grade A");
else if (marks >= 75)
printf("Grade B");
else
printf("Grade C");
Output:
Grade B

5. switch Statement
The switch statement is used when you need to choose from many options.
It compares a variable with different case values and executes the matching
case.
Syntax:
switch (expression)
{
case 1: statement1; break;
case 2: statement2; break;
default: statement3;
}

Example:
int choice = 2;
switch (choice)
{
case 1: printf("Start"); break;
case 2: printf("Stop"); break;
default: printf("Invalid");
}
Output:
Stop
Summary Table
Type Description Example
if Executes code if condition true if(a>b)
if-else Executes one of two blocks if-else
nested if if inside another if if(a){if(b){...}}
if-else-if Tests multiple conditions Grading system
switch Selects one case from many Menu program
ternary Short form of if-else (a>b)?a:b

Iteration Statements
Iteration means repeating a set of instructions until a condition becomes false.
There are three types of loops in C:for loop, while loop, and do-while loop.
(a) for Loop
Definition:
Used when the number of repetitions is known in advance.
Syntax:
for(initialization; condition; increment)
{
// statements
}
Example:
for(int i=1; i<=5; i++)
{
printf("%d ", i);
}
Output: 1 2 3 4 5
Explanation:
The loop starts with i=1 and runs until i<=5. After each execution, i increases by
1.
Advantages:
 Easy to use when loop count is known.
 Compact form (initialization, condition, increment in one line).
 Improves readability.
Disadvantages:
 Not suitable when loop count is unknown.
 Complex expressions in for loop can reduce clarity
(b) while Loop
Definition:
Used when condition is checked before executing the loop.
Syntax:
while(condition)
{
// statements
}
Example:
int i=1;
while(i<=5)
{
printf("%d ", i);
i++;
}
Output: 1 2 3 4 5
Explanation:
The loop executes only if the condition is true at the beginning.
Advantages:
 Useful when the number of iterations is not known.
 Condition is tested before loop execution.
Disadvantages:
 If condition is false initially, loop may not execute even once.
 Risk of infinite loop if condition never becomes false.

(c) do-while Loop


Definition:
Used when the loop must execute at least once, even if the condition is false.
Syntax:
do
{
// statements
} while(condition);
Example:
int i=1;
do
{
printf("%d ", i);
i++;
} while(i<=5);
Output: 1 2 3 4 5
Advantages:
 Executes at least once.
 Good for menu-driven programs.
Disadvantages:
 May run unnecessarily once even if condition is false.
 Harder to predict number of executions.

Jump Statements
Jump statements change the normal flow of program execution.
C provides break, continue, goto, and return.
(a) break Statement
Definition:
Used to exit from a loop or switch immediately.
Example:
for(int i=1; i<=10; i++)
{
if(i==5)
break;
printf("%d ", i);
}
Output: 1 2 3 4
Advantages:
 Helps to stop loop instantly when a condition is met.
 Improves program efficiency.
Disadvantages:
 Can make program flow harder to follow if overused.
 Reduces readability.
(b) continue Statement
Definition:
Used to skip the current iteration and go to the next loop cycle.
Example:
for(int i=1; i<=5; i++)
{
if(i==3)
continue;
printf("%d ", i);
}
Output: 1 2 4 5
Advantages:
 Useful when some conditions should be skipped.
 Simplifies handling of special cases in loops.
Disadvantages:
 May make program logic confusing.
 Harder to debug if used many times.

(c) goto Statement


Definition:
Used to jump directly to another part of the program using labels.
Example:
int i=1;
start:
printf("%d ", i);
i++;
if(i<=5)
goto start;
Output: 1 2 3 4 5
Advantages:
 Can simplify complex nested loops.
 Useful for breaking from multiple loops at once.
Disadvantages:
 Makes code unstructured and difficult to read.
 Not recommended in modern programming.
(d) return Statement
Definition:
Used to exit from a function and optionally send a value back.
A function declared as void cannot contain a return statement that specifies a
value. Since a void function has no return value, it makes sense that no return
statement within a void function can return a value.

Example:
int add()
{
return 10 + 20;}
Advantages:
 Helps in modular programming.
 Returns values from functions easily.
Disadvantages:
 Can cause unexpected exits if used incorrectly.
 Only one value can be returned directly.

Expression Statements
However, a few special points are mentioned here.
Remember, an expression statement is simply a valid expression followed by a
semicolon, as in

func(); /* a function call */


a = b+c; /* an assignment statement */
b+f(); /* a valid, but strange statement */
; /* an empty statement */

The first expression statement executes a function call. The second is an


assignment. The third expression, though strange, is still evaluated by the
compiler because the function f( ) may perform some necessary task. The final
example shows that a statement can be empty (sometimes called a null
statement).
Block Statements
Block statements are simply groups of related statements that are treated as a
unit. The statements that make up a block are logically bound together. Block
statements are also called compound statements. A block is begun with a { and
terminated by its matching }.

#include <stdio.h>
int main(void)
{
int i;
{ /* a free-standing block statement */
i = 120;
printf(''%d", i);
}
return 0;
}

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

You might also like