You are on page 1of 28

I.

TYPES OF LANGUAGES

There are basically two types of computer programming languages given below:
1. Low level language
2. High level language
1.Low Level Languages
The programming languages that are very close to machine code (0s and 1s) are called low-level
programming languages.
The program instructions written in these languages are in binary form.
The examples of low-level languages are:
 machine language
 assembly language
1. Machine Language
The instructions in binary form, which can be directly understood by the computer (CPU)
without translating them, is called a machine language or machine code.
Machine language is also known as first generation of programming language. Machine
language is the fundamental language of the computer and the program instructions in this
language is in the binary form (that is 0's and 1's).This language is different for different
computers.It is not easy to learn the machine language.
Advantage of Machine Language
The only advantage of machine language is that the program of machine language runs very fast
because no translation program is required for the CPU.
Disadvantage of Machine Language
Here are some of the main disadvantages of machine languages:
 Machine Dependent - the internal design of every computer is different from every other
type of computer, machine language also differs from one computer to another. Hence,
after becoming proficient in the machine language of one type of computer, if a company
decides to change to another type, then its programmer will have to learn a new machine
language and would have to rewrite all existing program.
 Difficult to Modify - it is difficult to correct or modify this language. Checking machine
instructions to locate errors is very difficult and time consuming.
 Difficult to Program - a computer executes machine language program directly and
efficiently, it is difficult to program in machine language. A machine language
programming must be knowledgeable about the hardware structure of the computer.
Assembly Language
It is another low-level programming language because the program instructions written in this
language are close to machine language.
Assembly language is also known as second generation of programming language.
With assembly language, a programmer writes instructions using symbolic instruction code
instead of binary codes.
Symbolic codes are meaningful abbreviations such as SUB is used for substation operation,
MUL for multiply operation and so on. Therefore this language is also called the low-level
symbolic language.
The set of program instructions written in assembly language are also called as mnemonic code.
Assembly language provides facilities for controlling the hardware.
Advantage of Assembly Language
Here are some of the main advantages of using assembly language:
 Easy to understand and use - due to the use of mnemonic instead of numeric op-codes
and symbolic names for data location instead of numeric addresses, it is much easier to
understand and use in contrast with machine language.
 Easier to locate and correct errors - the programmers need not to keep track of storage
location of the data and instruction, fewer errors are made while writing programs in
assembly language and those that are made, are easier to find and correct.
 Easy to modify - assembly language are easier to understand, it is easier to locate, correct
and modify instruction of an assembly language program.
Disadvantage of Assembly Languages
And here are some of the main disadvantages of using assembly language:
 Machine dependent - each instructions of assembly language program is translated into
exactly one machine language instruction, an assembly language programs are dependent
on machine language.
 Knowledge of hardware required - assembly languages are machine dependent, an
assembly language programmer must have a good knowledge of characteristics and
logical structure of his/her computer to write a good assembly language computer code.
 Machine level coding - assembly language instruction is substituted for one machine
language instruction. Hence like machine language programs, write assembly language
program is also time consuming and difficult.
2.High Level Languages
The programming languages that are close to human languages (example like English languages)
are called the high-level languages.
The examples of high-level languages are:
 Fortran
 COBOL
 Basic
 Pascal
 C
 C++
 Java
The high level languages are similar to English language. The program instructions are written
using English words, for example print, input etc. But each high level language has its own rule
and grammar for writing program instructions. These rules are called syntax of the language.
The program written in high level language must be translated to machine code before to run it.
Each high level language has its own translator program.Compiler And Interpreter are used to
convert high language to machine language.Compiler will convert whole program where as
interpreter will convert line by line code.
The high level programming languages are further divided into:
 Procedural languages
 Non procedural languages
 Object oriented programming languages
Advantages of High Level Languages
There are several advantages of high level programming languages. The most important
advantages are:
 Easy to learn - the high level languages are very easy to learn than low level languages.
The statements written for the program are similar to English-like statements.
 Easy to understand - the program written in high level language by one programmer can
easily be understood by another because the program instructions are similar to the
English language.
 Easy to write program - in high level language, a new program can easily be written in
a very short time. The larger and complicated software can be developed in few days or
months.
 Easy to detect and remove errors - the errors in a program can be easily detected and
removed. mostly the errors are occurred during the compilation of new program.
 Built-in library functions - Each high level language provides a large number of built-in
functions or procedures that can be used to perform specific task during designing of new
programs. In this way, a large amount of time of programmer is saved.
 Machine Independence - program written in high level language is machine
independent. It means that a program written in one type of computer can be executed on
another type of computer.
Limitation of High Level Language
There are two main limitation of high level languages are:
 Low efficiency - a program written in high level languages has lower efficiency than one
written in a machine/assembly language to do the same job. That is, program written in
high level languages result in multiple machine language instruction that may not be
optimize, taking more time to execute and requiring more memory space.
 Less flexibility - high level languages are less flexible than assembly languages because
they do not normally have instructions or mechanism to control a computer's CPU,
memory and register.
BASIC STRUCTURE OF C PROGRAM

Any C program is consists of 6 main sections. Below you will find brief explanation of each of
them.

Basic Structure of C Program


Documentation Section
This section consists of comment lines which include the name of programmer, the author and
other details like time and date of writing the program. Documentation section helps anyone to
get an overview of the program.

Link Section
The link section consists of the header files of the functions that are used in the program. It
provides instructions to the compiler to link functions from the system library.

Definition Section
All the symbolic constants are written in definition section. Macros are known as symbolic
constants.
 

Global Declaration Section


The global variables that can be used anywhere in the program are declared in global declaration
section. This section also declares the user defined functions.

main() Function Section


It is necessary have one main() function section in every C program. This section contains two
parts, declaration and executable part. The declaration part declares all the variables that are used
in executable part. These two parts must be written in between the opening and closing braces.
Each statement in the declaration and executable part must end with a semicolon (;). The
execution of program starts at opening braces and ends at closing braces.

Subprogram Section
The subprogram section contains all the user defined functions that are used to perform a specific
task. These user defined functions are called in the main() function.

III. COMPILING LINKING AND EXECUTING C PROGRAM

Every file that contains a C program must be saved with ‘.c’ extension. This is necessary for the
compiler to understand that this is a C program file. Suppose a program file is named, first.c. The
file first.c is called the source file which keeps the code of the program. Now, when we compile
the file, the C compiler looks for errors. If the C compiler reports no error, then it stores the file
as a .obj file of the same name, called the object file. So, here it will create the first.obj. This .obj
file is not executable. The process is continued by the Linker which finally gives a .exe file
which is executable.

Linker: First of all, let us know that library functions are not a part of any C program but of the
C software. Thus, the compiler doesn’t know the operation of any function, whether it be printf
or scanf. The definitions of these functions are stored in their respective library which the
compiler should be able to link. This is what the Linker does. So, when we write #include, it
includes stdio.h library which gives access to Standard Input and Output. The linker links the
object files to the library functions and the program becomes a .exe file. Here, first.exe will be
created which is in an executable format.
Loader: Whenever we give the command to execute a particular program, the loader comes into
work. The loader will load the .exe file in RAM and inform the CPU with the starting point of
the address where this program is loaded.

CPU Registers

Instruction Register: It holds the current instructions to be executed by the CPU.


Program Counter: It contains the address of the next instructions to be executed by the CPU.
Accumulator: It stores the information related to calculations.

The loader informs Program Counter about the first instruction and initiates the execution. Then
onwards, Program Counter handles the task.
IV.PREPROCESSORS IN C
 Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol.
Below is the list of preprocessor directives that C programming language offers.

Syntax/Description 
 

Preprocessor  

Syntax: #define
This macro defines constant value and can be any of the basic
Macro data types.

Syntax: #include <file_name>
Header file The source code of the file “file_name” is included in the main
inclusion program at the specified place.

Syntax: #ifdef, #endif, #if, #else, #ifndef


Conditional Set of commands are included or excluded in source program
compilation before compilation with respect to the condition. 

Syntax: #undef, #pragma
#undef is used to undefine a defined macro variable. #Pragma is
used to call a function before and after main function in a C
Other directives program.

1.Macros: Macros are piece of code in a program which is given some name. Whenever this
name is encountered by the compiler the compiler replaces the name with the actual piece of
code. The ‘#define’ directive is used to define a macro. Let us now understand macro definition
with the help of a program:
#include <iostream>

// macro definition
#define LIMIT 5
int main()
{
for (int i = 0; i < LIMIT; i++)
{
std::cout << i << "\n";
}

return 0;
}
Output:

0
1
2
3
4
2.File Inclusion: This type of preprocessor directive tells the compiler to include a file in the
source code program. There are two types of files which can be included by the user in the
program:
1. Header File or Standard files: These files contains definition of pre-defined
functions like printf(), scanf() etc. These files must be included for working with these
functions. Different function are declared in different header files. For example standard I/O
funuctions are in ‘iostream’ file whereas functions which perform string operations are in
‘string’ file.
Syntax:
2. #include< file_name >
where file_name is the name of file to be included. The ‘<‘ and ‘>’ brackets tells the compiler to
look for the file in standard directory.
3. user defined files: When a program becomes very large, it is good practice to
divide it into smaller files and include whenever needed. These types of files are user defined
files. These files can be included as:
4. #include"filename"

3.Conditional Compilation: Conditional Compilation directives are type of directives which


helps to compile a specific portion of the program or to skip compilation of some specific part
of the program based on some conditions. This can be done with the help of two preprocessing
commands ‘ifdef‘ and ‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif
If the macro with name as ‘macroname‘ is defined then the block of statements will execute
normally but if it is not defined, the compiler will simply skip this block of statements.

4.Other directives: Apart from the above directives there are two more directives which are not
commonly used. These are:
#undef Directive: The #undef directive is used to undefine an existing macro. This directive
works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement every “#ifdef
LIMIT” statement will evaluate to false.
#pragma Directive: This directive is a special purpose directive and is used to turn on or off
some features. This type of directives are compiler-specific i.e., they vary from compiler to
compiler. Some of the #pragma directives are discussed below:
#pragma startup and #pragma exit: These directives helps us to specify the functions that are
needed to run before program startup( before the control passes to main()) and just before
program exit (just before the control returns from main()).
Note: Below program will not work with GCC compilers.

 #pragma warn Directive: This directive is used to hide the warning


message which are displayed during compilation.
We can hide the warnings as shown below:
 #pragma warn -rvl: This directive hides those warning which are
raised when a function which is supposed to return a value does not returns a value.
 #pragma warn -par: This directive hides those warning which are
raised when a function does not uses the parameters passed to it.
 #pragma warn -rch: This directive hides those warning which are
raised when a code is unreachable. For example: any code written after the return statement in a
function is unreachable.
5.C TOKENS:
 C tokens are the basic buildings blocks in C language which are constructed
together to write a C program.
 Each and every smallest individual units in a C program are known as C
tokens.

C tokens are of six types. They are,


1. Keywords               (eg: int, while),
2. Identifiers               (eg: main, total),
3. Constants              (eg: 10, 20),
4. Strings                    (eg: “total”, “hello”),
5. Special symbols  (eg: (), {}),
6. Operators              (eg: +, /,-,*)

C TOKENS EXAMPLE PROGRAM:

int main()
{
   int x, y, total;
   x = 10, y = 20;
   total = x + y;
   printf ("Total = %d \n", total);
}
where,

 main – identifier
 {,}, (,) – delimiter
 int – keyword
 x, y, total – identifier
 main, {, }, (, ), int, x, y, total – tokens

6. IDENTIFIERS IN C LANGUAGE:
dentifiers
Identifiers are names for entities in a C program, such as variables, arrays,
functions, structures, unions and labels. An identifier can be composed only of
uppercase, lowercase letters, underscore and digits, but should start only with an
alphabet or an underscore. If the identifier is not used in an external link process,
then it is called as internal. Example: Local variable. If the identifier is used in an
external link process, then it is called as external. Example: Global variable

An identifier is a string of alphanumeric characters that begins with an alphabetic


character or an underscore character that are used to represent various
programming elements such as variables, functions, arrays, structures, unions and
so on. Actually, an identifier is a user-defined word. There are 53 characters, to
represent identifiers. They are 52 alphabetic characters (i.e., both uppercase and
lowercase alphabets) and the underscore character. The underscore character is
considered as a letter in identifiers. The underscore character is usually used in the
middle of an identifier. There are 63 alphanumeric characters, i.e., 53 alphabetic
characters and 10 digits (i.e., 0-9).

Rules for constructing identifiers

1.     The first character in an identifier must be an alphabet or an underscore and


can be followed only by any number alphabets, or digits or underscores.
2.     They must not begin with a digit.
3.     Uppercase and lowercase letters are distinct. That is, identifiers are case
sensitive.
4.     Commas or blank spaces are not allowed within an identifier.
5.     Keywords cannot be used as an identifier.
6.     Identifiers should not be of length more than 31 characters.
7.     Identifiers must be meaningful, short, quickly and easily typed and easily
read.

Valid identifiers:      total    sum     average          _x        y_        mark_1           x1

Invalid identifiers    
                                                     1x       -           begins with a digit
                                                    char    -           reserved word
                                                    x+y      -           special character

7. KEYWORDS IN C LANGUAGE:
Keywords are pre-defined words in a C compiler.
 Each keyword is meant to perform a specific function in a C program.
 Since keywords are referred names for compiler, they can’t be used as
variable name.
Keywords are preserved words that have special meaning in C language. The
meaning of C language keywords has already been described to the C compiler.
These meaning cannot be changed. Thus, keywords cannot be used as variable
names because that would try to change the existing meaning of the keyword,
which is not allowed.(Don't worry if you do not know what variables are, you will
soon understand.) There are total 32 keywords in C language.

auto double int struct

break else long switch

case enum register typedef

const extern return union

char float short unsigned

continue for signed volatile

default goto sizeof void

do if static while

8.Types of Constant in C
It is an identifier whose value can not be changed at the execution time of
program. In general constant can be used to represent as fixed values in a C
program. Constants are classified into following types.

If any single character (alphabet or numeric or special symbol) is enclosed


between single cotes ' ' known as single character constant.
If set of characters are enclosed between double cotes " " known as string
character constant.

Declare constant
const keyword are used for declare a constant.
Syntax
const int height = 100;

C supports several types of constants.      


1. Integer Constants 
 An integer constant is a sequence of digits from 0 to 9 without decimal
points or fractional part or any other symbols.
There are 3 types of integers namely decimal integer, octal integers and
hexadecimal integer.
Decimal Integers consists of a set of digits 0 to 9 preceded by an optional +
or - sign. Spaces, commas and non digit characters are not permitted
between digits.
Example for valid decimal integer constants are
     int y=123; //here 123 is a decimal integer constant
Octal Integers constant consists of any combination of digits from 0 through
7 with a O at the beginning. Some examples of octal integers are
     int X=O123; // here 0123 is a octal integer constant .
Hexadecimal integer constant is preceded by OX or Ox, they may contain
alphabets from A to F or a to f. The alphabets A to F refers to 10 to 15 in
decimal digits. Example of valid hexadecimal integers are
     int x=Ox12 // here Ox12 is a Hexa-Decimal integer constant
2. Real Constants 
Real Constants consists of a fractional part in their representation. Integer
constants are inadequate to represent quantities that vary continuously.
These quantities are represented by numbers containing fractional parts like
26.082. 
Example of real constants are
  float x = 6.3; //here 6.3 is a double constant.
  float y = 6.3f; //here 6.3f is a float constant.
  float z = 6.3 e + 2; //here 6.3 e + 2 is a exponential constant.
  float s = 6.3L ; //here 6.3L is a long double constant
Real Numbers can also be represented by exponential notation. The general
form for exponential notation is mantissa exponent. The mantissa is either a
real number expressed in decimal notation or an integer. The exponent is an
integer number with an optional plus or minus sign.
3. Single Character Constants 
A Single Character constant represent a single character which is enclosed in
a pair of quotation symbols.
Example for character constants are
char p ='ok' ;  // p will hold the value 'O' and k will be omitted
char y ='u';    // y will hold the value 'u'
char k ='34' ; // k will hold the value '3, and '4' will be omitted
char e =' ';     // e will hold the value ' ' , a blank space
chars ='\45'; // swill hold the value ' ' , a blank space
All character constants have an equivalent integer value which are called
ASCII Values.
4. String Constants
A string constant is a set of characters enclosed in double quotation marks.
The characters in a string constant sequence may be a alphabet, number,
special character and blank space. Example of string constants are
  "VISHAL"   "1234"  "God Bless" "!.....?"
5. Backslash Character Constants [Escape Sequences]
Backslash character constants are special characters used in output
functions. Although they contain two characters they represent only one
character. Given below is the table of escape sequence and their meanings.
 
Constant Meaning
'\a' .Audible Alert (Bell)
'\b' .Backspace
'\f' .Formfeed
'\n' .New Line
'\r' .Carriage Return
'\t' .Horizontal tab
'\v' .Vertical Tab
'\'' .Single Quote
'\"' .Double Quote
'\?' .Question Mark
'\\' .Back Slash
'\0' .Null

8.Variable in C Language
Variable is an identifier which holds data or another one variable. It is an
identifier whose value can be changed at the execution time of program. It is
used to identify input data in a program.
Syntax:

Syntax

Variable_name = value;

Rules to declare a Variable


To Declare any variable in C language you need to follow rules and regulation
of C Language, which is given below;

 Every variable name should start with alphabets or underscore (_).


 No spaces are allowed in variable declaration.
 Except underscore (_) no other special symbol are allowed in the middle of
the variable declaration (not allowed -> roll-no, allowed -> roll_no).
 Maximum length of variable is 8 characters depend on compiler and
operation system.
 Every variable name always should exist in the left hand side of assignment
operator (invalid -> 10=a; valid -> a=10;).
 No keyword should access variable name (int for <- invalid because for is
keyword).

Variable declarations

This is the process of allocating sufficient memory space for the data in term of
variable.

Syntax
Datatype variable_name; int a;

If no input values are assigned by the user than system will gives a default value
called garbage value.

Garbage value

Garbage value can be any value given by system and that is no way related to
correct programs. This is a disadvantage of C programming language and in C
programming it can overcome using variable initialization.

Variable initialization

It is the process of allocating sufficient memory space with user defined values.

Syntax
Datatype nariable_name=value;
Example
int b = 20;

Example
b = 25; // --> direct assigned variable
b = a; // --> assigned value in term of variable
b = a+15; // --> assigned value as term of expression

9.Scope and life time of a variable

A scope is a region of the program, and the scope of variables refers to the area
of the program where the variables can be accessed after its declaration.

In C every variable defined in scope. You can define scope as the section or
region of a program where a variable has its existence; moreover, that variable
cannot be used or accessed beyond that region.

The variable can be declared in three places. These are:

Position Type

Inside a function or a local variables


block.
Out of all functions. Global variables

In the function parameters. Formal parameters

So, now let's have a look at each of them individually.


Local Variables
Variables that are declared within the function block and can be used only within
the function is called local variables.
Local Scope or Block Scope
A local scope or block is collective program statements put in and declared within
a function or block and variables lying inside such blocks are termed as local
variables. All these locally scoped statements are written and enclosed within left
({) and right braces (}) curly braces. So it can be said that variable(s) that are
declared within a block can be accessed within that specific block and all other
inner blocks of that block, but those variables cannot be accessed outside the block.
Example:
#include <stdio.h>

int main ()
{
/* local variable definition and initialization */ int x,y,z;

/* actual initialization */ x = 20;


y = 30;
z = x + y;

printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;
}
Global Variables
Variables that are declared outside of a function block and can be accessed inside
the function is called global variables.
Global Scope
Global variables are defined outside a function or any specific block, in most of the
case, on the top of the C program. These variables hold their values all through the
end of the program and are accessible within any of the functions defined in your
program.
Any function can access variables defined within the global scope, i.e., its
availability stays for the entire program after being declared.
#include <stdio.h>

Example:

/* global variable definition */int z;

int main ()
{
/* local variable definition and initialization */ int x,y;

/* actual initialization */ x = 20;


y = 30;
z = x + y;

printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;
}

Global Variable Initialization


After defining a local variable, the system or the compiler won't be initializing any
value to it. You have to initialize it by yourself. It is considered good programming
practice to initialize variables before using. Whereas in contrast, global variables
get initialized automatically by the compiler as and when defined. Here's how
based on datatype; global variables are defined.
datatype Initial Default Value

int 0

char '\0'
float 0

double 0

pointer NULL

10. Storage classes

Storage classes in C are used to determine the lifetime, visibility, memory location,
and initial value of a variable. There are four types of storage classes in C

o Automatic
o External
o Static
o Register

Storage Storage Default Scope Lifetime


Classes Place Value

auto RAM Garbage Local Within function


Value

extern RAM Zero Global Till the end of the main program Maybe
declared anywhere in the program

static RAM Zero Local Till the end of the main program,
Retains value between multiple
functions call

register Register Garbage Local Within the function


Value

Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they
are defined.
The scope of the automatic variables is limited to the block in which they are
defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from
the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
1. #include <stdio.h>  
2. int main()  
3. {  
4. int a; //auto  
5. char b;  
6. float c;   
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, 
b, and c.   
8. return 0;  
9. }  

Output:

garbage garbage garbage

Static

o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which
they are defined.
o A same static variable can be declared many times but can be assigned at
only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.

Example
1. #include<stdio.h>  
2. void sum()  
3. {  
4. static int a = 10;  
5. static int b = 24;   
6. printf("%d %d \n",a,b);  
7. a++;   
8. b++;  
9. }  
10.void main()  
11.{  
12.int i;  
13.for(i = 0; i< 3; i++)  
14.{  
15.sum(); // The static variables holds their value between multiple function calls.    
16.}  
17.}  

Output:

10 24
11 25
12 26

Register

o The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator
for the register variable.
o The access time of the register variables is faster than the automatic
variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the
CPU register. However, it is compiler?s choice whether or not; the variables
can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address of
a variable.
o Static variables can not be stored into the register since we can not use more
than one storage specifier for the same variable.

Example 1
1. #include <stdio.h>  
2. int main()  
3. {  
4. register int a; // variable a is allocated memory in the CPU register. The initial def
ault value of a is 0.   
5. printf("%d",a);  
6. }  

Output:

External

o The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
o The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere in
the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize
the external variable within any block or method.
o An external variable can be declared many times but can be initialized at
only once.
o If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program which may be extern or
static. If it is not, then the compiler will show an error.

Example
1. #include <stdio.h>  
2. int a;   
3. int main()  
4. {  
5. extern int a; // variable a is defined globally, the memory will not be allocated to a 
 
6. printf("%d",a);  
7. }  

Output

11.Read and Write Character in C

We can read and write a character on screen using printf() and scanf() function
but this is not applicable in all situations. In C programming language some
function are available which is directly read a character or number of character
from keyboard.
getchar
This is a predefined function in C language which is available in stdio.h header
file. Using this function we can read a single character from keyboard and store
in character variable. When we want to read a number of character form
keyboard the store all the data in a character array.
Example

char ch;
ch=getch();

Note: getchar function has no any parameters.


gets
This is a predefined function in C language which is available in stdio.h header
file. This function is used to read a single string from keyboard.
Example

gets(string);

putchar
putchar function is a same as getchar but is function is used for display a
character value of screen or console. This function must be take one parameters.
Example

char ch='A';
putchar (ch);

putchar is equivalent to printf("%c",ch);


puts
puts is same as gets function but this is used to display a string on screen or
console. This function takes single arguments.
Example

puts(str);

12.C formatted Input and Output functions


The formatted input/output functions read and write, respectively, all
types of data values.
 They require format string to produce formatted results.
 They can be used for both reading and writing of all data values.
 The formatted functions return values after execution. The return value
is equal to the number of variable successfully read/written.
 Using this value the user can find out the error that occurred during
reading or writing of data.
 Example of formatted Function:
 Printf()
 Scanf()
formatted output - PRINTF():
 This function is used to print any text as well as value of the variables on
the standard output device/Console (monitor screen), printf is very basic
library function in c language that is declared in stdio.h header file.
 The printf() function prints all types of data values to the console
 It requires format conversion symbol or format string and variable
names to print the data.The format string symbol
Syntax:
printf(“message text”);
printf(“message text+ format-string”,variable-list);
 First printf() style print the simple text on the monitor, while second
printf() prints the message with values of the variable list.
EXAPLE: USE OF PRINTF()
#include <stdio.h>
int main()
{
printf("C language");
printf("Pradips Apps");
printf("Bitsofcomputer");
return 0;
}
Output
C language Pradips Apps Bitsofcomputer

formatted input - SCANF():


 This Formatted function is used to get (input) value from the keyboard.
 We pass format specifiers, in which format we want to take input.
Syntax: scanf(“format-specifier”, &var-name); scanf(“fromat-specifier-list”,
&var-name-list);
 First type of scanf() takes the single value for the variable and second
type of scanf() will take the multiple values for the variable list.
EXAMPLE:
#include"stdio.h"
#include"conio.h"
int main()
{
int a;
float b;
char c;
printf("Enter an integer number (value of a):");
scanf("%d",&a);
printf("Enter a float number (value of b):");
scanf("%f",&b);
printf("Enter a character (value of c):");
fflush(stdin); // to flush (clear) input buffer
scanf("%c",&c);
printf("\na=%d,b=%f,c=%c " ,a,b,c);
getch();
}
Output
Enter an integer number (value of a):1234
Enter a float number (value of b):1.2345
Enter a character (value of c):G
a=1234,b=1.234500,c=G

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

Program to Print ASCII Value


#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");

// Reads character input from the user


scanf("%c", &c);

// %d displays the integer value of a character


// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}
Output
Enter a character: G
ASCII value of G = 71

You might also like