0% found this document useful (0 votes)
42 views43 pages

VU-BCA-SEM-1 Unit 2 InputOutput Statements and Operators

Uploaded by

kirtanjaviya102
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)
42 views43 pages

VU-BCA-SEM-1 Unit 2 InputOutput Statements and Operators

Uploaded by

kirtanjaviya102
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
You are on page 1/ 43

VIDHYADEEP UNIVERSITY

Stream: BCA 1st Sem

Subject: INTRODUCTIONS TO PROGRAMMING USING C [1142104]

www.RNWMULTIMEDIA.com Page | 1
Unit - 2 | Input/Output Statements and Operators

2.1 Input/Output statements

 Concepts of Header files (STDIO,CONIO)


 Concepts of pre-compiler directives
 Use of #inlcude and #define
2.2 Input/Output Statements

 Input statements : scanf(), getc(), getch(), gets(), getchar()


 Output Statements: printf(), putc(),puts(), putchar()
2.3 Type specifiers (formatting strings) : %d, %ld, %f, %c, %s, %lf
2.4 Operators
 Arithmetic operators
 Logical Operators
 Relational Operators
 Bit-wise operators
 Assignment operators
 Ternary Operator
 use of sizeof() function
2.5 Important Built-in functions
 Use of : ( strlen, strcmp, strcpy, strcat,strrev) , Use of : (abs(), floor(), round(), ceil(), sqrt(), exp(),
log(), sin(), cos(), tan(), pow() and trunc())

www.RNWMULTIMEDIA.com Page | 2
2.1 Input/Output statements

 Concepts of Header files (STDIO,CONIO)

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”.

Syntax of Header Files in C


We can include header files in C by using one of the given two syntax whether it is a pre-
defined or user-defined header file.

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.

Example of Header File in C


The below example demonstrates the use of header files using standard input and output
stdio.h header file

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;
}

Types of C Header Files


There are two types of header files in C:
1. Standard / Pre-existing header files
2. Non-standard / User-defined header files

 Concepts of pre-compiler directives


The pre-processor is a tool that processes the source code before it passes through
the compiler. It work as an initial phase of compilation where it operates under the
control of different command lines or directives.

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.

The commonly used pre-processor directives are –

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.

Types of Header Files


There are two types of files that can be included using #include:

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.

2.2 Input/Output Statements


Input statements : scanf(), getc(), getch(), gets(), getchar()
C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.

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.

getc(), getch(), getchar()


All of these functions read a character from input and return an integer value. The integer is
returned to accommodate a special value used to indicate failure. The value EOF is generally
used for this purpose.
www.RNWMULTIMEDIA.com Page | 8
getc()
It reads a single character from a given input stream and returns the corresponding integer
value (typically ASCII value of read character) on success. It returns EOF on failure.

Syntax

int getc(FILE *stream);

Example

// Example for getc() in C


#include <stdio.h>
int main()
{
printf("%c", getc(stdin));
return (0);
}

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

// Example for getch() in C


#include <conio.h>
#include <stdio.h>
int main()
{
printf("%c", getch());
return 0;
}

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

Following is the C library syntax of the gets() function −

char *gets(char *str);

Example 1: Reading a String from Standard Input

This example reads a string from the standard input using gets() and then prints the
entered string.

Below is the illustration of C library gets() function.

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.

output Statements : printf(), putc(),puts(), putchar()

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:

int num = 42;


printf("The value of num is: %d\n", num);

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.

 How to take the input and output of basic types in C?

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.

 is used for integers (e.g., int).


%d
 is used for floating-point numbers (e.g., float or double).
%f
 is used for characters (e.g., char).
%c
 is used for strings (arrays of characters).
%s
For example, to read an integer using scanf(), you would use %d:

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()
{

// Declare the variables


int num;
char ch;
float f;

// --- Integer ---

// Input the integer


printf("Enter the integer: ");
scanf("%d", &num);

// Output the integer


printf("\nEntered integer is: %d", num);

// --- Float ---

//For input Clearing buffer


while((getchar()) != '\n');

// Input the float


printf("\n\nEnter the float: ");
scanf("%f", &f);

// Output the float


printf("\nEntered float is: %f", f);

// --- Character ---

// Input the Character


printf("\n\nEnter the Character: ");
scanf("%c", &ch);

// Output the Character


printf("\nEntered character is: %c", ch);

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

 ch – This is the character to be written.


 stream – This is a pointer to a FILE object that identifies the stream where the
character is to be written.

Return Value

 If the operation is successful, the function returns the character written.


 If an error occurs or the end of the file is reached, it returns EOF.

Example 1:

In this example, we will write a single character to a file using putc().

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)

Parameters: This method accepts a mandatory parameter ch which is the character to be


written to stdout.

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.

List of Format Specifiers in C


The below table contains the most commonly used format specifiers in C

www.RNWMULTIMEDIA.com Page | 21
Examples of Format Specifiers in C

1. Character Format Specifier – %c in C


The %c is the format specifier for the char data type in C language. It can be used for
both formatted input and formatted output in C language.
Syntax:

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);

// using %c for character output


printf("The entered character: %c", &c);
return 0;
}

2. Integer Format Specifier (signed) – %d in C


We can use the signed integer format specifier %d in the scanf() and print() functions or other
functions that use formatted string for input and output of int data type.
www.RNWMULTIMEDIA.com Page | 22
Syntax:
scanf("%d...", ...);

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);

// printing integer output


printf("Printed using %%d: %d\n", x);
printf("Printed using %%i: %3i\n", x);
return 0;
}

3. Unsigned Integer Format Specifier – %u in C


The %u is the format specifier for the unsigned integer data type. If we specify a negative
integer value to the %u, it converts the integer to its 2’s complement.

www.RNWMULTIMEDIA.com Page | 23
Syntax:
printf("%u...", ...);

scanf("%u...", ...);

Example: The following C Program demonstrates how to use %u in C.

4. Floating-point format specifier – %f in C


The %f is the floating point format specifier in C language that can be used inside the
formatted string for input and output of float data type. Apart from %f, we can
use %e or %E format specifiers to print the floating point value in the exponential form.
www.RNWMULTIMEDIA.com Page | 24
Syntax:
printf("%f...", ...);

scanf("%e...", ...);

printf("%E...", ...);

Example:

5. String Format Specifier – %s in C


The %s in C is used to print strings or take strings as input.
Syntax:
printf("%s...", ...);

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.

Input and Output Formatting


C language provides some tools using which we can format the input and output. They are
generally inserted between the % sign and the format specifier symbol Some of them are as
follows:
1. A minus(-) sign tells left alignment.
2. A number after % specifies the minimum field width to be printed if the characters
are less than the size of the width the remaining space is filled with space and if it is
greater then it is printed as it is without truncation.
3. A period( . ) symbol separates field width with precision.
Precision tells the minimum number of digits in an integer, the maximum number of characters
in a string, and the number of digits after the decimal part in a floating value.

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():

This function is used to count the number of characters present in a string.


Here is how we can use the strlen( ) function:

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.

The round() function is defined in the <math.h> header file.

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.

This method rounded up the nearest integer.

Syntax

Following is the syntax of the C library function ceil() −

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

Following is the syntax of the C library function sqrt() −

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.

In mathematics, an exponent is a small integer that positioned in the upper right of a


base number.

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.

Syntax : double log(double x)

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.

Syntax: double cos(double x)

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.

This function allows programmers to calculate a base number raised to a specified


exponent without the usage of implementing complex multiplication loops manually.

Syntax: double pow(double x, double 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.

Syntax : double trunc(double argument)

Output:

www.RNWMULTIMEDIA.com Page | 43

You might also like