0% found this document useful (0 votes)
7 views

C programming for jhatu

Uploaded by

bhupikrishan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C programming for jhatu

Uploaded by

bhupikrishan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

C PROGRAMMING

Dept. of Computer Science and Engineering


National Institute of Technology, Durgapur
West Bengal, India
FORMATTED AND UNFORMATTED INPUT AND OUTPUT IN C
• Input means to provide the program with some data to be used in the program.
• Output means to display data on screen or write the data to a printer or a file.
• C programming language provides many built-in functions to read any given
input and to display data on screen when there is a need to output the result.
• C programming 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.
• Input output built-in functions in C falls into two categories,
• formatted input output (I/O) functions
• unformatted input output (I/O) functions.
• printf() and scanf() are examples for formatted input and output functions
• getch(), getche(), getchar(), gets(), puts(), putchar() etc. are examples of
unformatted input output functions.
INPUT OUTPUT FUNCTIONS
• Functions, which can be used in our program to take input from user and to output
the result on screen.
• These are built-in functions present in C header files.
• We need to specify the name of header files in which a particular function is
defined while using it in a program.
• printf() and scanf() functions are inbuilt input output library functions in C
programming language which are available in C library by default. These
functions are declared and related macros are defined in “stdio.h” which is a
header file in C language.
printf() AND scanf()
• The standard input-output header file, named stdio.h contains the definition #include<stdio.h>
of the functions printf() and scanf().
void main()
• These two functions are used to display output on screen and to take input {
from user respectively. // defining a variable
int i;
/*
• Now then what is the purpose of %d inside the scanf() or printf() functions. displaying message on the screen
It is known as format string and this informs the scanf() function, what asking the user to input a value
type of input to expect and in printf() it is used to give a heads up to the */
compiler, what type of output to expect. printf("Please enter a value...");
/*
reading the value entered by the user
*/
Format String Meaning scanf("%d", &i);
/*
%d Scan or print an integer as signed displaying the number as output
decimal number */
printf( "\nYou entered: %d", i);
}
%f Scan or print a floating point number
• When the code is compiled, it will ask to enter a value. When the
%c To scan or print a character value is entered, it will display the value you have entered on screen .
%s To scan or print a character string. The
int i = printf("studytonight");
scanning ends at whitespace.
• In this program printf("studytonight"); will return 12 as result,
which will be stored in the variable i, because studytonight has 12
• The number of digits or characters that can be input or output can be characters.
limited, by adding a number with the format string specifier,
like "%1d" or "%3s", the first one means a single numeric digit and the
second one means 3 characters,
• Hence if we try to input 42, while scanf() has "%1d", it will take only 4 as
input. Same is the case for output.
• printf() function returns the number of characters printed by it
• scanf() returns the number of characters read by it.
C printf() Function
• EXAMPLE PROGRAM FOR C PRINTF() FUNCTION PRINTF() FUNCTION IN C LANGUAGE:
1
• In C programming language, printf() function is used to print the
2
3 “character, string, float, integer, octal and hexadecimal values”
4 onto the output screen.
5 #include <stdio.h>
6 int main()
• We use printf() function with %d format specifier to display the
7{ value of an integer variable.
8 char ch = 'A';
• Similarly %c is used to display character, %f for float
9 char str[20] = "fresh2refresh.com";
1 float flt = 10.234; variable, %s for string variable, %lf for double and %x for
0 int no = 150; hexadecimal variable.
1 double dbl = 20.123456;
1 printf("Character is %c \n", ch);
• To generate a newline,we use “\n” in C printf() statement.
1 printf("String is %s \n" , str); • C language is case sensitive. For example, printf() and scanf() are
2 printf("Float value is %f \n", flt);
1 printf("Integer value is %d\n" , no);
different from Printf() and Scanf(). All characters in printf() and
3 printf("Double value is %lf \n", dbl); scanf() functions must be in lower case.
1 printf("Octal value is %o \n", no); OUTPUT:
4 printf("Hexadecimal value is %x \n", no); We can see the output with the same data which are placed within
1 return 0;
5}
the double quotes of printf statement in the program except
1 •%d got replaced by value of an integer variable (no),
6 •%c got replaced by value of a character variable (ch),
1 •%f got replaced by value of a float variable (flt),
Character is A
7
String is fresh2refresh.com •%lf got replaced by value of a double variable (dbl),
Float value is 10.234000
Integer value is 150 •%s got replaced by value of a string variable (str),
Double value is 20.123456 •%o got replaced by a octal value corresponding to integer
Octal value is 226 variable (no),
Hexadecimal value is 96
•%x got replaced by a hexadecimal value corresponding to integer
variable
C printf() Function
• C Output
• In C programming, printf() sends formatted output to the screen.
• Example 1: C Output
#include <stdio.h>
int main()
{
How does this program work?
// Displays the string inside quotations All valid C programs must contain the main() function. The code execution begins from
printf("C Programming"); the start of the main() function.
return 0;
} The printf() is a library function to send formatted output to the screen. The function
prints the string inside quotations.
• Example 2: Integer Output
#include <stdio.h> To use printf() in our program, we need to include stdio.h header file using the #include
int main() <stdio.h> statement.
{ The return 0; statement inside the main() function is the "Exit status" of the program.
int testInteger = 5;
printf("Number = %d", testInteger); It's optional.
return 0;
} Output
• Example 3: float and double Output Number = 5
#include <stdio.h> We use %d format specifier to print int types. Here, the %d inside the quotations
int main()
{ will be replaced by the value of testInteger.
float number1 = 13.5;
double number2 = 12.4;
Output
printf("number1 = %f\n", number1); number1 = 13.500000
printf("number2 = %lf", number2); number2 = 12.400000
return 0;
} To print float, we use %f format specifier. Similarly, we use %lf to
print double values.
• Example 4: Print Characters
#include <stdio.h>
int main() Output
{ character = a
char chr = 'a'; To print char, we use %c format specifier.
printf("character = %c", chr);
return 0;
C scanf() Function
SCANF() FUNCTION IN C LANGUAGE: 1
• In C programming language, scanf() function is used to read 2
#include <stdio.h>
character, string, numeric data from keyboard 3
int main()
4
{
• Consider the example program byside where user enters a 5
char ch;
character. This value is assigned to the variable “ch” and then 6
char str[100];
displayed. 7
printf("Enter any character \n");
8
• Then, user enters a string and this value is assigned to the scanf("%c", &ch);
9
variable “str” and then displayed. printf("Entered character is %c \n", ch);
1
printf("Enter any string ( upto 100 character ) \n");
0
• The format specifier %d is used in scanf() statement. So that, scanf("%s", &str);
1
the value entered is received as an integer and %s for string. printf("Entered string is %s \n", str);
1
}
• Ampersand is used before variable name “ch” in scanf() 1
statement as &ch. 2

• It is just like in a pointer which is used to point to the variable.


OUTPUT

Enter any character


a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai
C scanf() Function
• C Input
• In C programming, scanf() is one of the commonly used function to take input from the user.
• The scanf() function reads formatted input from the standard input device such as keyboards
• Example 1: Integer Input/Outpu t Output
#include <stdio.h> Enter an integer: 4
int main() Number = 4
{ Here, we have used %d format specifier inside the scanf() function to take int input from the
int testInteger; user. When the user enters an integer, it is stored in the testInteger variable.
printf("Enter an integer: ");
scanf("%d", &testInteger);
Notice, that we have used &testInteger inside scanf().
printf("Number = %d",testInteger); It is because &testInteger gets the address of testInteger, and the value entered by the user is
return 0; stored in that address
}
• Example 2: Float and Double Input/Output Output
#include <stdio.h>
int main() Enter a number: 12.523
{ Enter another number: 10.2
float num1; num1 = 12.523000
double num2;
printf("Enter a number: "); num2 = 10.200000
scanf("%f", &num1); We use %f and %lf format specifier for float and double respectively
printf("Enter another number: ");
scanf("%lf", &num2);
printf("num1 = %f\n", num1);
printf("num2 = %lf", num2); Output
return 0; Enter a character: g
} You entered g
• Example 3: C Character I/O
#include <stdio.h> When a character is entered by the user in the above program, the
int main() character itself is not stored. Instead, an integer value (ASCII value)
{ is stored.
char chr;
printf("Enter a character: "); And when we display that value using %c text format, the entered
scanf("%c",&chr); character is displayed. If we use %d to display the character, it's
printf("You entered %c.", chr);
return 0;
ASCII value is printed.
}
• Example 4: I/O Multiple Values
Here's how you can take multiple inputs from the user and display them.
Output
#include <stdio.h> Enter integer and then a float: -3 3.4
int main() You entered -3 and 3.400000
{
int a;
float b;
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
return 0;
getchar() & putchar() functions
• getchar()
• The getchar() function reads a character from the terminal and returns it as
an integer. #include <stdio.h>
• This function reads only single character at a time.

void main( )
This getchar() can be used in a loop in case there is a need to read more than {
one character. int c;
• The getchar() function is a part of the standard C input/output library. printf("Enter a character");
• It returns a single character from a standard input device (typically a /*
keyboard). The function does not require any arguments, though a pair of Take a character as input and store it in variable c
empty parentheses must follow the word getchar() */
• In general, a function reference would be written as: c = getchar();
• character variable = getchar( ); where character variable refers to some /*
previously declared character variable. display the character stored in variable c
*/
• putchar() putchar(c);
• The putchar() function displays the character passed to it on the screen and
returns the same character.
• This function too displays only a single character at a time.
• In case there is a need to display more than one characters,
use putchar() method in a loop.
• Function putchar(). This function is complementary to the character input
function getchar(). When you will compile the above code, it will ask you to
• The putchar() function like getchar() is a part of the standard C enter a value. When you will enter the value, it will
input/output library. It transmits a single character to the standard output display the value you have entered.
device (the computer screen).
• It must be expressed as an argument to the function, enclosed in parentheses,
following the word putchar() .
• In general, a function reference would be written as:
• putchar(character variable) where character variable refers to some
previously declared character variable.
gets() & puts() functions
• gets() #include<stdio.h>

 The gets() function reads a line from stdin(standard input)


void main()
{
into the buffer pointed to by str pointer, until either a /* character array of length 100 */
terminating newline or EOF (end of file) occurs. char str[100];
printf("Enter a string");
gets( str );
• puts() puts( str );
getch();
}
 The puts() function writes the string str and a trailing newline
to stdout.

 str → This is the pointer to an array of chars where the C


When you will compile the above code, it will ask you to enter a string. When
string is stored. (Ignore if you are not able to understand you will enter the string, it will display the value you have entered.
this now.)

• Difference between scanf() and gets()


 The main difference between these two functions is that scanf() stops
reading characters when it encounters a space, but gets() reads space
as character too.

 If you enter name as Study Tonight using scanf() it will only read
and store Study and will leave the part after space.
But gets() function will read it completely
DATA TYPE FORMATS
• Here's a list of commonly used C data types and their format
Data Type Format Specifier
int %d

char %c

float %f

double %lf

short int %hd

unsigned int %u

long int %li

long long int %lli

unsigned long int %lu

unsigned long long int %llu

signed char %c

unsigned char %c

long double %Lf


C PREPROCESSOR
C PREPROCESSOR
• As the name suggests Preprocessors are programs that process our
source code before compilation. There are a number of steps involved
between writing a program and executing a program in C . Let us have a
look at these steps before we actually start learning about Preprocessors.
• The intermediate steps are shown in the diagram. The source code written
by programmers is stored in the file program.c.
• This file is then processed by preprocessors and an expanded source
code file is generated named program.
• This expanded file is compiled by the compiler and an object code file is
generated named program .obj.
• Finally, the linker links this object code file to the object code of the
library functions to generate the executable file program.exe.
• Preprocessor programs provide preprocessors directives which tell the
compiler to preprocess the source code before compiling.
• All of these preprocessor directives begin with a ‘#’ (hash) symbol. The
‘#’ symbol indicates that, whatever statement starts with #, is going to
the preprocessor program, and preprocessor program will execute this
statement.
• Examples of some preprocessor directives
are: #include, #define, #ifndef etc.
• Remember that # symbol only provides a path that it will go to the
preprocessor, and command such as include is processed by
preprocessor program. For example, include will include extra code to
your program. We can place these preprocessor directives anywhere in
our program.
C PREPROCESSOR
• A preprocessor is a program that processes Source Code before it passes through the
compiler for compilation.
• There are some preprocessor commands and directives that are used to instruct
Preprocessor and mostly placed at the starting of the C source code.
• To include the various instructions to the compiler in the C source code, some directives are
used called as Preprocessor Directives.
• Preprocessor expands the scope of the programming environment.
• Preprocessor commands are executed before the compiler compiles the source code.
• These commands will change the original code according to the operating environment and
adds the code that will be required by calls to library functions.
• A preprocessor is a language that takes as input a text file written using some programming
language syntax and output another text file following the syntax of another programming
language
• The C preprocessor is a macro processor that is used automatically by the C compiler to
transform your program before actual compilation. It is called a macro processor because it
C PREPROCESSOR
• Advantages of preprocessor are that it makes-
1) the program easier to develop.
2) easier to read. C Preprocessor improves the readability of C program.
3) easier to modify. C Preprocessor makes the C program easy to maintain.
4) C code more transportable between different machine architecture. C
Preprocessor makes the C program more portable.
• The facilities provided by a preprocessor are given below-
1) File inclusion
2) Substitution facility
3) Conditional compilation.
• To maintain the portability of C programming language in different architectures or
compilers,the concept of Preprocessor is introduced.
• All the preprocessor processed before the staring of actual compilation and create
an intermediate file.
• In the intermediate file all preprocessor statement/commands are replaced by
corresponding C code. During the process of compilation that intermediate file is deleted by
C PREPROCESSOR
• Preprocessing Directives
• Most preprocessor features are active only if we use preprocessing directives to request their use.
• Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is
the directive name. For example, `#define' is the directive that defines a macro. Whitespace is also allowed before
and after the `#'.
• The `#include' Directive
• Both user and system header files are included using the preprocessing directive `#include'.
It has three variants:
• #include <file>
• This variant is used for system header files. It searches for a file named file in a list of directories specified, then
in a standard list of system directories.
• #include "file"
• This variant is used for header files of your own program. It searches for a file named file first in the current
directory, then in the same directories used for system header files. The current directory is the directory of
the current input file.
• #include anything else
• This variant is called a computed #include. Any `#include' directive whose argument does not fit the above two
• Preprocessing Directives
C PREPROCESSOR
• Most preprocessor features are active only if we use preprocessing directives to request their use.
• Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name. For example, `#define' is the directive that
defines a macro. Whitespace is also allowed before and after the `#'.
• The #define Directive
• Use this to define constants or any macro substitution. Use as follows:
#define <macro> <replacement name>
For Example #define FALSE 0
#define TRUE !FALSE
• We can also define small "functions" using #define. For example max. of two variables:
#define max(A,B) ( (A) > (B) ? (A):(B))
? is the ternary operator in C.
• Other examples of #define could be:
#define Deg_to_Rad(X) (X*M_PI/180.0) /* converts degrees to radians, M_PI is the value of pi and is defined in math.h library */
• Example 1: #define Directive
#include <stdio.h>
#define PI 3.1415
int main()
{ float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;}
C PREPROCESSOR DIRECTIVES
Sr.No. Directive & Description
1 #define
All preprocessor commands begin with a hash Substitutes a preprocessor macro.

symbol (#). It must be the first nonblank character, 2 #include


Inserts a particular header from another file.
and for readability, a preprocessor directive should
begin in the first column. The table beside lists 3 #undef
Undefines a preprocessor macro.
down all the important preprocessor directives −
4 #ifdef
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not defined.

6 #if
Tests if a compile time condition is true.

7 #else
The alternative for #if.
8 #elif
#else and #if in one statement.
9 #endif
Ends preprocessor conditional.
10 #error
Prints error message on stderr.
11 #pragma
Issues special commands to the compiler, using a standardized method.
MACROS
• A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the
macro.
• There are two kinds of macros.
• They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-
like macros resemble function calls.
• Any valid identifier may be defined as a macro, even if it is a C keyword. The preprocessor does not know anything about
keywords. This can be useful if you wish to hide a keyword such as const from an older compiler that does not understand it.
However, the preprocessor operator defined can never be defined as a macro
• A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two
types of macros:
1. Object-like Macros
2. Function-like Macros
1. Object-like Macros
• The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For
example:
1. #define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.

2.Function-like Macros
• The function-like macro looks like function call. For example:
1. #define MIN(a,b) ((a)<(b)?(a):(b))
Here, MIN is the macro name.
MACROS
• Predefined Macros
• Here are some predefined macros in C programming
C predefined macros example No. Macro Description
File: simple.c 1 _DATE_ represents current
#include<stdio.h> date in "MMM
DD YYYY"
int main(){ format.
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ ); 2 _TIME_ represents current
time in
printf("Time :%s\n", __TIME__ ); "HH:MM:SS"
printf("Line :%d\n", __LINE__ ); format.
printf("STDC :%d\n", __STDC__ );
3 _FILE_ represents current
return 0; file name.
}
4 _LINE_ represents current
line number.
Output:
File :simple.c 5 _STDC_ It is defined as 1
Date :Jan 5 2021 when compiler
complies with the
Time :12:28:46 ANSI standard.
Line :6
STDC :1
PREPROCESSORS vs MACROS
• Macro: a word defined by the #define preprocessor directive that evaluates to some other expression.
• Preprocessor directive: a special #-keyword, recognized by the preprocessor.
• preprocessor modifies the source file before handing it over to the compiler. Consider preprocessor as
a program that runs before compiler.
• Preprocessor directives are like commands to the preprocessor program. Some common preprocessor
directives in C are
1.#include <header name> - Instructs the preprocessor to paste the text of the given file to the current file.
2.#if <value> - Checks whether the value is true if so it will include the code until #endif
3.#define - Useful for defining a constant and creating a macro
• macros are name for some fragment of code. So wherever the name is used it get replaced by the
fragment of code by the preprocessor program.
eg:
#define BUFFER_SIZE 100
In your code wherever you use BUFFER_SIZE it gets replaced by 100
int a=BUFFER_SIZE;
a becomes 100 here
THANK
YOU!!

You might also like