VU-BCA-SEM-1 Unit 2 InputOutput Statements and Operators
VU-BCA-SEM-1 Unit 2 InputOutput Statements and Operators
www.RNWMULTIMEDIA.com Page | 1
Unit - 2 | Input/Output Statements and Operators
www.RNWMULTIMEDIA.com Page | 2
2.1 Input/Output statements
Header Files in C
In C language, header files contain a set of predefined standard library functions. The .h is the
extension of the header files in C and we request to use a header file in our program by
including it with the C preprocessing directive “#include”.
C Header files offer the features like library functions, data types, macros, etc by importing
them into the program with the help of a preprocessor directive “#include”.
The “#include” preprocessor directs the compiler that the header file needs to be
processed before compilation and includes all the necessary data types and function
definitions.
www.RNWMULTIMEDIA.com Page | 3
// Program to use of header files standard input and output stdio.h header file
#include <stdio.h>
int main()
{
printf("\n Printf() is the function in stdio.h header file");
return 0;
}
Preprocessors are programs that process the source code before compilation.
Several steps are involved between writing a program and executing a program in C.
Pre-processor Directives in C
Pre-processor is placed in the source program before the main line, it begins with the
symbol "#" in column one and does not require a semicolon at the end.
www.RNWMULTIMEDIA.com Page | 4
The pre-processor directives are divided into three categories –
Example of Macro
// C Program to illustrate the macro
#include <stdio.h>
#define LIMIT 5 // macro definition
int main()
{
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
www.RNWMULTIMEDIA.com Page | 5
Use of #inlcude and #define
#include is a way of including a standard or user-defined file in the program and is
mostly written at the beginning of any C program. The #include preprocessor directive is read
by the preprocessor and instructs it to insert the contents of a user-defined or system header
file in our C program. These files are mainly imported from outside header files.
The process of importing such files that might be system-defined or user-defined is known
as File Inclusion. This preprocessor directive tells the compiler to include a file in the source
code program.
1. Pre-Existing Header Files: The pre-existing header files come bundled with the compiler
and reside in the standard system file directory. This file contains C standard library function
declarations and macro definitions to be shared between several source files. Functions like the
printf(), scanf(), cout, cin, and various other input-output or other standard functions are
contained within different Pre-Existing header files.
2. User-Defined Header Files: These files resemble the header files, except for the fact that
they are written and defined by the user itself. This saves the user from writing a particular
function multiple times.
Syntax of #include in C
1. including using <>
It is mainly used to access pre-existing system header files located in the standard system
directories.
#include <header_file>
While importing a file using angular brackets(<>), the preprocessor uses a predetermined
directory path to access the file.
2. including using ” “
This type is mainly used to access any header files of the user’s program or user-defined
files.
#include "user-defined_file"
www.RNWMULTIMEDIA.com Page | 6
When using the double quotes(” “), the preprocessor accesses the current directory in which
the source “header_file” is located or the standard system directories.
Examples of #include in C
Example 2
In the below example, the #include <math.h> directive allows us to use athematical
functions like sqrt for calculating the square root.
www.RNWMULTIMEDIA.com Page | 7
Example 3
The below code shows the creation and import of a user-defined file.
scanf()
The scanf() method, in C, reads the value from the console as per the type
specified and store it in the given address.
Syntax:
scanf("%X", &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value
of variableOfXType, stored at this address in the memory.
Syntax
Example
getchar()
The difference between getc() and getchar() is getc() can read from any input stream, but
getchar() reads a single input character from standard input. So getchar() is equivalent to
getc(stdin).
Syntax
int getchar(void);
Example
#include <stdio.h>
int main()
{
printf("%c", getchar());
return 0;
}
www.RNWMULTIMEDIA.com Page | 9
getch()
Like the above functions, getch() also reads a single character from the keyboard. But it does
not use any buffer, so the entered character does not display on the screen and is immediately
returned without waiting for the enter key.
getch() is a nonstandard function and is present in <conio.h> header file which is mostly used
by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it
defined by POSIX.
Syntax
int getch();
Example
www.RNWMULTIMEDIA.com Page | 10
gets()
he C library gets() function is used to read a line from the standard input stream
(stdin) and store it into the string pointed to by str. It continues reading characters
from the input stream until a newline character is encountered or the end-of-file is
reached. The newline character is then replaced by a null terminator, and the
resulting string is stored in str.
Syntax
This example reads a string from the standard input using gets() and then prints the
entered string.
www.RNWMULTIMEDIA.com Page | 11
Example 2: Handling Buffer Overflow
This example shows what happens when the input string exceeds the size of the
buffer, causing a buffer overflow. Only the first few characters that fit into the buffer
are stored, leading to unexpected behavior.
printf()
In C, the printf() function is used to display (or print) values on the console
screen. It takes one or more parameters, known as format specifiers, and prints them
according to the format specified in the function’s argument.
For example:
www.RNWMULTIMEDIA.com Page | 12
In this example, %d is a format specifier that indicates the integer value num should be
inserted into the string at that position. When you run this program, it will display
“The value of num is: 42” on the console screen.
printf() is a versatile and powerful function used for formatted output in C, allowing
you to control how data is displayed and formatted.
In C, the basic data types like int, float, and char each has specific format specifiers
that should be used with functions like scanf() and printf() for input and output.
int num;
scanf("%d", &num);
To print a floating-point number using printf(), you would use %f:
float price = 19.99;
printf("The price is: %f\n", price);
These format specifiers ensure that the data is interpreted and displayed correctly, and
they are an essential part of input and output operations in C.
Integer
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
Float
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);
Character
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);
www.RNWMULTIMEDIA.com Page | 13
// C program to show input and output
#include <stdio.h>
int main()
{
return 0;
}
www.RNWMULTIMEDIA.com Page | 14
www.RNWMULTIMEDIA.com Page | 15
putc()
In C, the putc() function is used to write a character passed as an argument to a given
stream. It is a standard library function defined in the <stdio.h> header file. The function first
converts the character to unsigned char, then writes it to the given stream at the position
indicated by the file pointer, and finally increments the file pointer by one.
Syntax of putc()
int putc(int ch, FILE *stream);
Parameters
Return Value
Example 1:
www.RNWMULTIMEDIA.com Page | 16
www.RNWMULTIMEDIA.com Page | 17
puts()
In C programming language, puts() is a function defined in header <stdio.h> that prints
strings character by character until the NULL character is encountered. The puts() function
prints the newline character at the end of the output string.
Syntax
int puts(char* str);
Parameters
str: string to be printed.
Return Value
The return value of the puts function depends on the success/failure of its execution.
On success, the puts() function returns a non-negative value.
Otherwise, an End-Of-File (EOF) error is returned.
Example
www.RNWMULTIMEDIA.com Page | 18
putchar()
The putchar(int ch) method in C is used to write a character, of unsigned char type, to
stdout. This character is passed as the parameter to this method.
Syntax:
int putchar(int ch)
Return Value: This function returns the character written on the stdout as an unsigned char. It
also returns EOF when some error occurs.
The below examples illustrate the use of putchar() method:
Example 1:
www.RNWMULTIMEDIA.com Page | 19
Example 2:
www.RNWMULTIMEDIA.com Page | 20
2.3 Type specifiers (formatting strings) : %d, %ld, %f, %c, %s, %lf
The format specifier in C is used to tell the compiler about the type of data to be printed or
scanned in input and output operations. They always start with a % symbol and are used in the
formatted string in functions like printf(), scanf, sprintf(), etc.
The C language provides a number of format specifiers that are associated with the different
data types such as %d for int, %c for char, etc.
www.RNWMULTIMEDIA.com Page | 21
Examples of Format Specifiers in C
scanf("%d...", ...);
printf("%d...", ...);
Example:
// C Program to illustrate the %c format specifier.
#include <stdio.h>
int main()
{
char c;
// using %c for character input
scanf("Enter some character: %c", &c);
printf("%i...", ...);
Example:
// C Program to demonstrate the use of %d and %i
#include <stdio.h>
int main()
{
int x;
// taking integer input
scanf("Enter the two integers: %d", &x);
www.RNWMULTIMEDIA.com Page | 23
Syntax:
printf("%u...", ...);
scanf("%u...", ...);
scanf("%e...", ...);
printf("%E...", ...);
Example:
scanf("%s...", ...);
Example:
www.RNWMULTIMEDIA.com Page | 25
Example: The working of %s with scanf() is a little bit different from its working with
printf(). Let’s understand this with the help of the following C program.
www.RNWMULTIMEDIA.com Page | 26
Example of I/O Formatting
2.4 Operators
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and variables.
The values and variables used with operators are called operands. So we can say that the
operators are the symbols that perform operations on operands.
Types of Operators in C
C language provides a wide range of operators that can be classified into 6 types based on their
functionality:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
www.RNWMULTIMEDIA.com Page | 27
Operators are the symbols which are used to perform some operations.
www.RNWMULTIMEDIA.com Page | 28
www.RNWMULTIMEDIA.com Page | 29
www.RNWMULTIMEDIA.com Page | 30
2.5 Important Built-in functions
String Functions
We can use C's string handling library functions to handle strings. The string.h library is used
to perform string operations. It provides several functions for manipulating strings.
1. strlen():
2. strcmp():
The strcmp() function is used to compare two strings to find out whether they are the same
or different. It takes two strings as two of its parameter. It will compare two strings,
character by character until there is a mismatch or the iterator reaches the end of one of the
strings.
If both of the strings are identical, strcmp( ) returns a value of zero. If they are not identical,
it will return a value less than zero, considering the ASCII value of the mismatched
character in the first string is less than the mismatched character in the second string. Else, it
will return a value greater than 0.
Here is how we can use the strcmp( ) function:
www.RNWMULTIMEDIA.com Page | 31
3. strcpy():
This function is used to copy the contents of one string into the other. This function expects
two parameters, first, the base address of the source string and then the base address of the
target string.
Here is how we can use the strcpy( ) function:
4. strcat():
This function is used to concatenate the source string to the end of the target string. This
function expects two parameters, first, the base address of the source string and then the base
address of the target string. For example, “Hello” and “World” on concatenation would
result in a string “HelloWorld”.
Here is how we can use the strcat( ) function:
www.RNWMULTIMEDIA.com Page | 32
5. strrev():
This function is used to return the reverse of the string.
Here is how we can use the strrev( ) function:
Mathematical Functions
1. abs()
The C stdlib library abs() function is used to returns the absolute value of the
specified number, where absolute represents the positive number.
This function only returns the positive integer. For example, if we have an integer value
of -2, we want to get the absolute number of -2. We then used the abs() function to
return the positive number 2.
Syntax:
int abs(int x)
www.RNWMULTIMEDIA.com Page | 33
Example:
Example 2
Let's create another example to get the absolute value of both positive and negative
integer. Using the abs() function.
www.RNWMULTIMEDIA.com Page | 34
2. floor()
The C library floor() function of type double accept the single parameter(x) to return
the largest integer value less than or equal to, by the given values.
This function rounds a number down to the nearest integer multiple of the specified
significance.
Syntax
double floor(double x)
Example 1
Following is the basic C library example to see the demonstration of floor() function.
www.RNWMULTIMEDIA.com Page | 35
Example 2
Below the program shows how to use floor() to round down a value.
3. round()
The round() function rounds a number to the nearest integer. If the decimal part is
exactly 0.5 it rounds away from zero, to the integer with largest absolute value.
Syntax
One of the following:
round(double number);
Output:
www.RNWMULTIMEDIA.com Page | 36
4. ceil()
The C library ceil() function of type double accept the single argument(x) that returns
the smallest integer value greater than or equal to, by the given value.
Syntax
double ceil(double x)
Example:
www.RNWMULTIMEDIA.com Page | 37
5. sqrt()
The C library sqrt() function of type double accept the variable x(double) as parameter
to return the result of square root. The square of a number is obtained by multiplying the
number by itself.
Syntax
double sqrt(double x)
Example:
Output:
6. exp()
The C library exp() function of type double accept the single parameter(x) that returns
the value of exponent raised to the base power.
Syntax
double exp(double x)
www.RNWMULTIMEDIA.com Page | 38
Example:
Output:
7. log()
The C library log() function of type double that accept x as parameter to return the
natural logarithm(base-e logarithm).
In programming, log concept is used to monitor and trouble shooting the system issues
and tracking events, random user activity, and security incidents.
Example:
www.RNWMULTIMEDIA.com Page | 39
Output:
8. sin()
The C library sin() function of type double accept the parameter as variable(x) that
returns the sine of a radian angle. This function calculate the sine value of any angle.
A sine is a trigonometric function which is used for finding the sides of a right triangle or
unknown angle.
Syntax: sin(double x)
Example:
Output:
www.RNWMULTIMEDIA.com Page | 40
9.cos()
The C library cos() function of type double accept the parameter as variable(x) that
returns the cosine of a radian angle.
The cos is termed as cosine of an acute angle which define the right triangle.
Example:
Output:
www.RNWMULTIMEDIA.com Page | 41
10. tan()
The tan() function returns tangent of a number (angle in radians).
Example:
11. pow()
The C library pow() function of type double accepts the parameter x and y that simplifies
the x raised to the power of y.
www.RNWMULTIMEDIA.com Page | 42
Example:
Output:
12. trunc()
This function is used to truncate double type value. And return only the integer part.
Output:
www.RNWMULTIMEDIA.com Page | 43