C Programming: Console I/O Basics
C Programming: Console I/O Basics
PROGRAMMING IN C
PREPARED BY,
PROF. SUSHMA V
ASSISTANT
PROFESSOR
DEPT. OF CSE,
SIT, MYSURU
Department of Computer Science and Engineering (CSE)
Syllabus : Module 2
Department of Computer Science and Engineering (CSE)
Introduction
putchar( )
Writes a single character to the screen.
The putchar( ) function writes a character to the screen at the
current cursor position.
This function returns the character written on the stdout as an
unsigned char. It also returns EOF when some error occurs(-
1).
Syntax: int putchar(int c);
Department of Computer Science and Engineering (CSE)
Example
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character: ");
ch = getchar(); // Read a character from the keyboard
printf("You entered: ");
putchar(ch); // Display the character on the screen
putchar('\n'); // Display a newline character
return 0;
}
Example
Department of Computer Science and Engineering (CSE)
It inputs characters from the keyboard and displays them in reverse case. That is, it prints
uppercase as lowercase and lowercase as uppercase. To stop the program, enter a period.
#include<stdio.h>
#include<ctype.h>
int main( )
{
char ch;
printf("Enter some text (type a period to quit).\n");
do
{
ch = getchar();
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while (ch != '.');
return 0;
}
Department of Computer Science and Engineering (CSE)
1. Input Buffering
It reads from a buffered input stream.
This means characters entered by the user are typically stored in a buffer until a newline
character(\n) is entered (by pressing the Enter key), or the buffer becomes full. This can lead to
unexpected behaviour if you expect character-by-character processing without requiring a
newline.
Handling Remaining Characters in the Buffer:
If a user enters more characters than your program immediately processes with getchar() the
remaining characters stay in the input buffer. Subsequent calls to getchar() or scanf() will read
these leftover characters instead of waiting for new user input, potentially leading to unintended
program flow.
Department of Computer Science and Engineering (CSE)
Alternatives to getchar( )
Alternatives to getchar( )
2. getche( )
Example:
function reads a single character from the keyboard #include <conio.h>
and displays immediately on the output screen without #include <stdio.h>
waiting for enter key.
Like getch(), it is also a non-standard function present int main()
in <conio.h> header file. {
Syntax: int getche(void); printf("%c",
getche());
return 0;
}
Department of Computer Science and Engineering (CSE)
Summary
Function Operation
getchar( ) Reads a character from the keyboard; usually waits for carriage
return.
getche( ) Reads a character with echo; does not wait for carriage return; not
defined by Standard C, but a common extension.
getch( ) Reads a character without echo; does not wait for
The printf( ) function returns the number of characters successfully printed or a negative value if an error
occurs.
const char * format: This is the "format string," a string literal enclosed in double quotes. It can contain:
Plain text: Any characters that are not part of a format specifier or escape sequence will be printed as is.
Escape sequences: Special character combinations starting with a backslash (`\`) that represent non-
printable characters or special actions.(\n for a newline, \t for a tab)
Format specifiers: Special characters starting with a percent sign (%) that act as placeholders for the
values of subsequent arguments.
Example: printf("I like %c %s", 'C', "very much!");
displays
I like C very much!
Department of Computer Science and Engineering (CSE)
Department of Computer Science and Engineering (CSE)
Format Modifiers
Many format specifiers can take modifiers that alter their meaning slightly. For example, you can
specify a minimum field width, the number of decimal places, and left justification. The format
modifier goes between the percent sign and the format code.
When you apply the precision specifier to floating-point data using the %f, %e, or %E
specifiers, it determines the number of decimal places displayed. For example, %10.4f
displays a number at least 10 characters wide with four decimal places.
Department of Computer Science and Engineering (CSE)
scanf( )
scanf( ) is the general -purpose console input routine. It can read all the built-in data types and
automatically convert numbers into the proper internal format.
Format Specifiers
The input format specifiers are preceded by a % sign and tell scanf( ) what type of data is to be read next.
Inputting Numbers
To read an integer, use either the %d or %i specifier. To read a floating-point number represented
in either standard or scientific notation, use %e, %f, or %g.
Department of Computer Science and Engineering (CSE)
Department of Computer Science and Engineering (CSE)
Reading Strings
The scanf( ) function can be used to read a string from the input stream using the %s format
specifier. Using %s causes scanf( ) to read characters until it encounters a white-space character.
As it applies to scanf( ), a white-space character is either a space, a newline, a tab, a vertical tab, or a
formfeed.
Unlike gets( ) , which reads a string until ENTER is pressed, scanf( ) reads a string until the first white
space is entered. #include <stdio.h>
int main()
{
char str[80];
printf("Enter a string: ");
scanf(''%s", str);
printf("Here's your string: %s", str);
return 0;
Department of Computer Science and Engineering (CSE)
Inputting an Address
To input a memory address, use the %p format specifier. This specifier causes
scanf( ) to read an address in the format defined by the architecture of the CPU.
The %n Specifier
The %n specifier instructs scanf( ) to store the number of characters read from
the input stream (up to the point at which the %n was encountered) in the integer
variable pointed to by the corresponding argument.
Department of Computer Science and Engineering (CSE)
Chapter2:
Statements in C
Department of Computer Science and Engineering (CSE)
Introduction
1. if
The if statement is the simplest decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statements is executed otherwise not.
A condition is any expression that evaluates to either a true or false.
#include <stdio.h>
int main() Syntax :
{
if (condition)
{
int i = 10; // if body
if (i >18) // Statements to execute if condition
is true
{
}
printf("Eligible for vote");
}
}
Department of Computer Science and Engineering (CSE)
2. if-else
The if-else statement consists of two blocks, one for false expression and
one for true expression. Syntax:
#include <stdio.h> if (condition)
int main() {
{ // Code to execute if the condition
is true
int i = 10;
}
if (i > 18) else
{ {
printf("Eligible for vote"); // Code to execute if the
} condition is false
else }
{
printf("Not Eligible for
vote");
}
return 0;
Department of Computer Science and Engineering (CSE)
Example of if else
/* Magic number program */
#include<stdio.h>
#include<stdlib.h> • It prints the message ** Right ** when the player
int main (void) guesses the magic number.
{ • It generates the magic number using the standard
int magic; /* magic number */ random number generator rand( ), which returns an
int guess; /* user's guess */ arbitrary number between 0 and RAND_MAX (which
magic = rand(); /* generate the magic number */ defines an integer value that is 32,767 or larger).
printf("Guess the magic number: "); • Progrma illustrates the use of the else statement to
scanf("%d", &guess); print a message in response to the wrong number.
if(guess == magic)
printf("** Right **");
else
printf("Wrong");
return 0;
}
Department of Computer Science and Engineering (CSE)
Exercise :
4. if else if ladder
5. Switch
Syntax :
Exercise :
Iteration Statements
1. for loop
2. while loop
3. do while loop
Unlike for and while loops, which test the loop condition at the top of the loop,
the do-while loop checks its condition at the bottom of the loop.
Syntax :
do
{
//statements
} while( condition);
Department of Computer Science and Engineering (CSE)
#include <stdio.h>
do
{
printf( "%d ", i);
i++;
return 0;
}
Department of Computer Science and Engineering (CSE)
Jump Statements
goto,
break, and
continue.
Department of Computer Science and Engineering (CSE)
The return statement is used to return from a function. It is categorized as a jump statement because it
causes execution to return (jump back) to the point at which the call to the function was made.
A return may or may not have a value associated with it.
A return with a value can be used only in a function with a non-void return type. In this case, the value
associated with return becomes the return value of the function.
A return without a value is used to return from a void function.
The general form of the return statement is :
return expression;
Eg : return 0;
Department of Computer Science and Engineering (CSE)
int main()
{
int num = 5;
printf("Starting the program...\n");
if (num > 0)
{
goto positive_label;
}
printf("This line will not be printed if num is positive.\n");
positive_label:
printf("The number is positive: %d\n", num);
printf("Exiting the program.\n");
return 0;
}
Department of Computer Science and Engineering (CSE)
You can break out of a program by using the standard library function exit( ).
This function causes immediate termination of the entire program, forcing a return to
the operating system. In effect, the exit( ) function acts as if it were breaking out of the
entire program.
The exit( ) function requires the header <stdlib.h>
The general form of the exit( ) function is
void exit(int return_code);
Eg : exit(0);
Department of Computer Science and Engineering (CSE)
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("This program will now terminate.\n");
exit(0); // Terminates the program with a success status
printf("This line will not be executed.\n");
return 0;
}
Department of Computer Science and Engineering (CSE)
continue forces the next iteration of the loop to take place skipping
any code in between.
Syntax :
continue;
Department of Computer Science and Engineering (CSE)
int main()
{
// Loop from 1 to 5
for (int i = 1; i <= 5; i++)
{
// If i is 3, skip the rest of the current iteration
if (i == 3)
{
continue;
}
// This line will not execute when i is 3
printf("%d ", i);
}
printf("\n"); // Print a newline for better output formatting
return 0;
}
Department of Computer Science and Engineering (CSE)
Expression Statements
Eg :
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( )
{
int a, b, sum;
{
a=10;
b=5;
sum=a+b;
}
return 0;
}