History of C Language

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

History of C language

The base or father of programming languages is ‘ALGOL.’ It was first


introduced in 1960. ‘ALGOL’ was used on a large basis in European
countries. ‘ALGOL’ introduced the concept of structured programming to the
developer community. In 1967, a new computer programming language was
announced called as ‘BCPL’ which stands for Basic Combined Programming
Language. BCPL was designed and developed by Martin Richards, especially
for writing system software. This was the era of programming languages. Just
after three years, in 1970 a new programming language called ‘B’ was
introduced by Ken Thompson that contained multiple features of ‘BCPL.’ This
programming language was created using UNIX operating system at AT&T
and Bell Laboratories. Both the ‘BCPL’ and ‘B’ were system programming
languages.

In 1972, a great computer scientist Dennis Ritchie created a new


programming language called ‘C’ at the Bell Laboratories. It was created from
‘ALGOL’, ‘BCPL’ and ‘B’ programming languages. ‘C’ programming language
contains all the features of these languages and many more additional
concepts that make it unique from other languages.

‘C’ is a powerful programming language which is strongly associated with the


UNIX operating system. Even most of the UNIX operating system is coded in
‘C’. Initially ‘C’ programming was limited to the UNIX operating system, but as
it started spreading around the world, it became commercial, and many
compilers were released for cross-platform systems. Today ‘C’ runs under a
variety of operating systems and hardware platforms. As it started evolving
many different versions of the language were released. At times it became
difficult for the developers to keep up with the latest version as the systems
were running under the older versions. To assure that ‘C’ language will remain
standard, American National Standards Institute (ANSI) defined a commercial
standard for ‘C’ language in 1989. Later, it was approved by the International
Standards Organization (ISO) in 1990. ‘C’ programming language is also
called as ‘ANSI C’.

History of C
Languages such as C++/Java are developed from ‘C’. These languages are
widely used in various technologies. Thus, ‘C’ forms a base for many other
languages that are currently in use.
C programming
C language combines the power of a low-level language and a high-level language.
The low-level languages are used for system programming, while the high-level
languages are used for application programming. It is because such languages are
flexible and easy to use. Hence, C language is a widely used computer language.

basic structure of a C program. A C program is divided into different sections. There are
six main sections to a basic c program.

The six sections are,

 Documentation
 Link
 Definition
 Global Declarations
 Main functions
 Subprograms

Documentation Section
The documentation section is the part of the program where the programmer gives the
details associated with the program. He usually gives the name of the program, the
details of the author and other details like the time of coding and description.

Example
/**

* File Name: Helloworld.c

* Author: Manthan Naik

* date: 09/08/2019

* description: a program to display hello world

*              no input needed

*/

Link Section
This part of the code is used to declare all the header files that will be used in the
program. This leads to the compiler being told to link the header files to the system
libraries.

Example

1 #include<stdio.h>
Moving on to the next bit of this basic structure of a C program article,

Definition Section
In this section, we define different constants. The keyword define is used in this part.

1 #define PI=3.14
Moving on to the next bit of this basic structure of a C program article,

Global Declaration Section


This part of the code is the part where the global variables are declared. All the global
variable used are declared in this part. The user-defined functions are also declared in
this part of the code.

1 float area(float r);


2 int a=7;
Moving on to the next bit of this basic structure of a C program article,

Main Function Section


Every C-programs needs to have the main function. Each main function contains 2
parts. A declaration part and an Execution part. The declaration part is the part where
all the variables are declared. The execution part begins with the curly brackets and
ends with the curly close bracket. Both the declaration and execution part are inside the
curly braces.

1 int main(void)
2 {
3 int a=10;
4 printf(" %d", a);
return 0;
5
}
6

C Character Set

As every language contains a set of characters used to construct words, statements, etc., C

language also has a set of characters which include alphabets, digits, and special symbols. C

language supports a total of 256 characters.

Every C program contains statements. These statements are constructed using words and these

words are constructed using characters from C character set. C language character set contains the

following set of characters...

1. Alphabets

2. Digits

3. Special Symbols

Alphabets

C language supports all the alphabets from the English language. Lower and upper case letters

together support 52 alphabets.

lower case letters - a to z

UPPER CASE LETTERS - A to Z


Digits

C language supports 10 digits which are used to construct numerical values in C language.

Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Symbols

C language supports a rich set of special symbols that include symbols to perform mathematical

operations, to check conditions, white spaces, backspaces, and other special symbols.

Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell

backspace verticaltab etc.,

Every character in C language has its equivalent ASCII (American Standard Code for Information

Interchange) value.
Commonly used characters in C with thier ASCII values
C Tokens

Every C program is a collection of instructions and every instruction is a collection of some individual

units. Every smallest individual unit of a c program is called token. Every instruction in a c program is

a collection of tokens. Tokens are used to construct c programs and they are said to the basic

building blocks of a c program.

In a c program tokens may contain the following...

1. Keywords

2. Identifiers

3. Operators

4. Special Symbols

5. Constants

6. Strings

7. Data values

In a C program, a collection of all the keywords, identifiers, operators, special symbols,

constants, strings, and data values are called tokens.

C Keywords

As every language has words to construct statements, C programming also has words with a

specific meaning which are used to construct c program instructions. In the C programming

language, keywords are special words with predefined meaning. Keywords are also known as

reserved words in C programming language.

In the C programming language, there are 32 keywords. All the 32 keywords have their meaning

which is already known to the compiler.


Keywords are the reserved words with predefined meaning which already known to the

compiler

Whenever C compiler come across a keyword, automatically it understands its meaning.

Properties of Keywords
1. All the keywords in C programming language are defined as lowercase letters so they must
be used only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user-defined names like variable, functions, arrays, pointers,
etc...
4. Every keyword in C programming language represents something or specifies some kind of
action to be performed by the compiler.

Keywords in C Programming

auto break case char

const continue default do

double else enum extern

float for goto if

int long register return

short signed sizeof static

struct switch typedef union

unsigned void volatile while

C Identifiers

In C programming language, programmers can specify their name to a variable, array, pointer,

function, etc... An identifier is a collection of characters which acts as the name of variable, function,

array, pointer, structure, etc... In other words, an identifier can be defined as the user-defined name
to identify an entity uniquely in the c programming language that name may be of the variable name,

function name, array name, pointer name, structure name or a label.

The identifier is a user-defined name of an entity to identify it uniquely during the program

execution

Example

int marks;

char studentName[30];

Here, marks and studentName are identifiers.

Rules for Creating Identifiers

1. An identifier can contain letters (UPPERCASE and

lowercase), numerics & underscore symbol only.

2. An identifier should not start with a numerical value. It can start with a letter or an

underscore.

3. We should not use any special symbols in between the identifier even whitespace. However,

the only underscore symbol is allowed.

4. Keywords should not be used as identifiers.

5. There is no limit for the length of an identifier. However, the compiler considers the first 31

characters only.

6. An identifier must be unique in its scope.

C Variables

Variables in a c programming language are the named memory locations where the user can store

different values of the same datatype during the program execution. That means a variable is a

name given to a memory location in which we can store different values of the same data type. In
other words, a variable can be defined as a storage container to hold values of the same datatype

during the program execution. The formal definition of a data type is as follows...

Variable is a name given to a memory location where we can store different values of the

same datatype during the program execution.

Every variable in c programming language must be declared in the declaration section before it is
used. Every variable must have a datatype that determines the range and type of values be stored
and the size of the memory to be allocated.

A variable name may contain letters, digits and underscore symbol. The following are the rules to
specify a variable name...

1. Variable name should not start with a digit.


2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore(_).
4. A variable name can be of any length but compiler considers only the first 31 characters of
the variable name.

Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified datatype values into that memory location. In C
programming language, the declaration can be performed either before the function as global
variables or inside any block or function. But it must be at the beginning of block or function.

        Declaration Syntax:

datatype variableName;

        Example

                int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.

C data types

Data used in c program is classified into different types based on its properties. In the C

programming language, a data type can be defined as a set of values with similar characteristics. All

the values in a data type have the same properties.


Data types in the c programming language are used to specify what kind of value can be stored in a

variable. The memory size and type of the value of a variable are determined by the variable data

type. In a c program, each variable or constant or array must have a data type and this data type

specifies how much memory is to be allocated and what type of values are to be stored in that

variable or constant or array. The formal definition of a data type is as follows...

The Data type is a set of value with predefined characteristics. data types are used to declare

variable, constants, arrays, pointers, and functions.

In the c programming language, data types are classified as follows...

1. Primary data types (Basic data types OR Predefined data types)


2. Derived data types (Secondary data types OR User-defined data types)
3. Enumeration data types
4. Void data type
Primary data types
The primary data types in the C programming language are the basic data types. All the primary
data types are already defined in the system. Primary data types are also called as Built-In data
types. The following are the primary data types in c programming language...

1. Integer data type


2. Floating Point data type
3. Double data type
4. Character data type

Integer Data type


The integer data type is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer data type in c. We use the keyword int to
declare the variables and to specify the return type of a function. The integer data type is used with
different type modifiers like short, long, signed and unsigned. The following table provides complete
details about the integer data type.
Floating Point data types
Floating-point data types are a set of numbers with the decimal value. Every floating-point value
must contain the decimal value. The floating-point data type has two variants...

 float
 double

We use the keyword "float" to represent floating-point data type and "double" to represent double
data type in c. Both float and double are similar but they differ in the number of decimal places. The
float value contains 6 decimal places whereas double value contains 15 or 19 decimal places. The
following table provides complete details about floating-point data types.
Character data type
The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.

The following table provides complete information about all the data types in c programming
language...
void data type
The void data type means nothing or no value. Generally, the void is used to specify a function
which does not return any value. We also use the void data type to specify empty parameters of a
function.

Enumerated data type


An enumerated data type is a user-defined data type that consists of integer constants and each
integer constant is given a name. The keyword "enum" is used to define the enumerated data type.
Derived data types
Derived data types are user-defined data types. The derived data types are also called as user-
defined data types or secondary data types. In the c programming language, the derived data types
are created using the following concepts...

 Arrays
 Structures
 Unions
 Enumeration

C Constants

In C programming language, a constant is similar to the variable but the constant hold only one

value during the program execution. That means, once a value is assigned to the constant, that

value can't be changed during the program execution. Once the value is assigned to the constant, it

is fixed throughout the program. A constant can be defined as follows...

A constant is a named memory location which holds only one value throughout the program

execution.

In C programming language, a constant can be of any data type like integer, floating-point,
character, string and double, etc.,

Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal
integer value is specified as direct integer value whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer constant.
Unsigned integer constant value is suffixed with 'u' and long integer constant value is suffixed with 'l'
whereas unsigned long integer constant value is suffixed with 'ul'.

Example
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant
Floating Point constants
A floating-point constant must contain both integer and decimal parts. Some times it may also
contain the exponent part. When a floating-point constant is represented in exponent form, the value
must be suffixed with 'e' or 'E'.

Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.

Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a maximum
length of one character.

Example
'A'
'2'
'+'
In the C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape sequence is
prefixed with '\' symbol. These escape sequences are used in output function called 'printf()'.

String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that are
enclosed in double quotations.

We define string constant in a single line as follows...


"This is btechsmartclass"

We can define string constant using multiple lines as follows...


" This\
is\
btechsmartclass "

We can also define string constant by separating it with white space as follows...
"This" "is" "btechsmartclass"

All the above three defines the same string constant.

Creating constants in C
In a c programming language, constants can be created using two concepts...

1. Using the 'const' keyword


2. Using '#define' preprocessor
Using the 'const' keyword
We create a constant of any datatype using 'const' keyword. To create a constant, we prefix the
variable declaration with 'const' keyword.
The general syntax for creating constant using 'const' keyword is as follows...

const datatype constantName ;


OR

const datatype constantName = value ;


Example
const int x = 10 ;
Here, 'x' is a integer constant with fixed value 10.

Example Program
#include<stdio.h>
#include<conio.h>
void main(){

int i = 9 ;
const int x = 10 ;

i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;

}
The above program gives an error because we are trying to change the constant variable value (x =
100).

Using '#define' preprocessor


We can also create constants using '#define' preprocessor directive. When we create constant using
this preprocessor directive it must be defined at the beginning of the program (because all the
preprocessor directives must be written before the global declaration).
We use the following syntax to create constant using '#define' preprocessor directive...

#define CONSTANTNAME value


Example
#define PI 3.14
Here, PI is a constant with value 3.14

Example Program
#include<stdio.h>
#include<conio.h>

#defien PI 3.14

void main(){
int r, area ;

printf("Please enter the radius of circle : ") ;


scanf("%d", &r) ;

area = PI * (r * r) ;

printf("Area of the circle = %d", area) ;


}

C Operators

An operator is a symbol used to perform arithmetic and logical operations in a program. That means

an operator is a special symbol that tells the compiler to perform mathematical or logical operations.

C programming language supports a rich set of operators that are classified as follows.

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Increment & Decrement Operators

5. Assignment Operators

6. Bitwise Operators
7. Conditional Operator

8. Special Operators

Arithmetic Operators (+, -, *, /, %)

The arithmetic operators are the symbols that are used to perform basic mathematical operations

like addition, subtraction, multiplication, division and percentage modulo. The following table

provides information about arithmetic operators.

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the Division 5%2=1

⇒ The addition operator can be used with numerical data types and character data type. When it is

used with numerical values, it performs mathematical addition and when it is used with character

data type values, it performs concatination (appending).

⇒ The remainder of the division operator is used with integer data type only.
Relational Operators (<, >, <=, >=, ==, !=)

The relational operators are the symbols that are used to compare two values. That means the

relational operators are used to check the relationship between two values. Every relational operator

has two results TRUE or FALSE. In simple words, the relational operators are used to define

conditions in a program. The following table provides information about relational operators.

Operator Meaning

< Returns TRUE if the first value is smaller than second value otherwise returns FALSE

> Returns TRUE if the first value is larger than second value otherwise returns FALSE

<= Returns TRUE if the first value is smaller than or equal to second value otherwise returns FALSE

>= Returns TRUE if the first value is larger than or equal to second value otherwise returns FALSE

== Returns TRUE if both values are equal otherwise returns FALSE

!= Returns TRUE if both values are not equal otherwise returns FALSE

Logical Operators (&&, ||, !)

The logical operators are the symbols that are used to combine multiple conditions into one

condition. The following table provides information about logical operators.


Operator Meaning Example

&& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns FALSE 10 < 5 &&

|| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns TRUE 10 < 5 ||

! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is TRUE !(10 < 5 &

⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE

then complete condition becomes FALSE.

⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE

then complete condition becomes TRUE.

Increment & Decrement Operators (++ & --)

The increment and decrement operators are called unary operators because both need only one

operand. The increment operators adds one to the existing value of the operand and the decrement

operator subtracts one from the existing value of the operand. The following table provides

information about increment and decrement operators.

Operator Meaning Ex

++ Increment - Adds one to existing value int


a+

-- Decrement - Subtracts one from existing value int


a--
The increment and decrement operators are used infront of the operand (++a) or after the operand

(a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is

used after the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement

In the case of pre-increment, the value of the variable is increased by one before the expression

evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the

expression evaluation. That means, when we use pre-increment or pre-decrement, first the value of

the variable is incremented or decremented by one, then the modified value is used in the

expression evaluation.

Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int i = 5,j;

j = ++i; // Pre-Increment

printf("i = %d, j = %d",i,j);

Output:
Post-Increment or Post-Decrement

In the case of post-increment, the value of the variable is increased by one after the expression

evaluation. In the case of post-decrement, the value of the variable is decreased by one after the

expression evaluation. That means, when we use post-increment or post-decrement, first the

expression is evaluated with existing value, then the value of the variable is incremented or

decremented by one.

Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int i = 5,j;

j = i++; // Post-Increment

printf("i = %d, j = %d",i,j);

Output:
Assignment Operators (=, +=, -=, *=, /=, %=)

The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side

variable (Lvalue). The assignment operator is used in different variants along with arithmetic

operators. The following table describes all the assignment operators in the C programming

language.

Operator Meaning

= Assign the right-hand side value to left-hand side variable

+= Add both left and right-hand side values and store the result into left-hand side variable

-= Subtract right-hand side value from left-hand side variable value and store the result
into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and store the result
into left-hand side variable
Operator Meaning

/= Divide left-hand side variable value with right-hand side variable value and store the result
into the left-hand side variable

%= Divide left-hand side variable value with right-hand side variable value and store the remainder
into the left-hand side variable

Bitwise Operators (&, |, ^, ~, >>, <<)

The bitwise operators are used to perform bit-level operations in the c programming language. When

we use the bitwise operators, the operations are performed based on the binary values. The

following table describes all the bitwise operators in the C programming language.

Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1

~ the result of Bitwise once complement is negation of the bit (Flipping)

<< the Bitwise left shift operator shifts all the bits to the left by the specified number of positions
Operator Meaning

>> the Bitwise right shift operator shifts all the bits to the right by the specified number of positions

Conditional Operator (?:)

The conditional operator is also called a ternary operator because it requires three operands. This

operator is used for decision making. In this operator, first we verify a condition, then we perform one

operation out of the two operations based on the condition result. If the condition is TRUE the first

option is performed, if the condition is FALSE the second option is performed. The conditional

operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example

A = (10<15)?100:200; ⇒ A value is 100

Special Operators (sizeof, pointer, comma, dot, etc.)

The following are the special operators in c programming language.


sizeof operator

This operator is used to find the size of the memory (in bytes) allocated for a variable. This operator

is used with the following syntax.

sizeof(variableName);

Example

sizeof(A); ⇒ the result is 2 if A is an integer

Pointer operator (*)

This operator is used to define pointer variables in c programming language.

Comma operator (,)

This operator is used to separate variables while they are declaring, separate the expressions in

function calls, etc.

Dot operator (.)

This operator is used to access members of structure or union.

Creating and Running C Program

Generally, the programs created using programming languages like C, C++, Java, etc., are written

using a high-level language like English. But, the computer cannot understand the high-level

language. It can understand only low-level language. So, the program written in the high-level

language needs to be converted into the low-level language to make it understandable for the

computer. This conversion is performed using either Interpreter or Compiler.

Popular programming languages like C, C++, Java, etc., use the compiler to convert high-level

language instructions into low-level language instructions. A compiler is a program that converts

high-level language instructions into low-level language instructions. Generally, the compiler
performs two things, first it verifies the program errors, if errors are found, it returns a list of errors

otherwise it converts the complete code into the low-level language.

To create and execute C programs in the Windows Operating System, we need to install Turbo C

software. We use the following steps to create and execute C programs in Windows OS…

Step 1: Creating a Source Code

Source code is a file with C programming instructions in a high-level language. To create source

code, we use any text editor to write the program instructions. The instructions written in the source

code must follow the C programming language rules. The following steps are used to create a

source code file in Windows OS…

 Click on the Start button

 Select Run
 Type cmd and press Enter

 Type cd c:\TC\bin in the command prompt and press Enter

 Type TC press Enter

 Click on File -> New in C Editor window

 Type the program

 Save it as FileName.c (Use shortcut key F2 to save)

Step 2: Compile Source Code (Alt + F9)

The compilation is the process of converting high-level language instructions into low-level language

instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.

The compilation is the process of converting high-level language instructions into low-level

language instructions.

Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On receiving a
source file, the compiler first checks for the Errors. If there are any Errors then compiler returns List
of Errors, if there are no errors then the source code is converted into object code and stores it as a
file with .obj extension. Then the object code is given to the Linker. The Linker combines both
the object code and specified header file code and generates an Executable file with
a .exe extension.

Step 3: Executing / Running Executable File (Ctrl + F9)


After completing compilation successfully, an executable file is created with a .exe extension. The
processor can understand this .exe file content so that it can perform the task specified in the source
file.

We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the .exe file is
submitted to the CPU. On receiving .exe file, CPU performs the task according to the instruction
written in the file. The result generated from the execution is placed in a window called User Screen.

Step 4: Check Result (Alt + F5)


After running the program, the result is placed into User Screen. Just we need to open the User
Screen to check the result of the program execution. We use the shortcut key Alt + F5 to open the
User Screen and check the result.

Execution Process of a C Program


When we execute a C program it undergoes with the following process…
The file which contains c program instructions in a high-level language is said to be source code.
Every c program source file is saved with .c extension, for example, Sample.c.

Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks for the
errors, if there are any errors, it returns a list of errors, otherwise generates object code in a file with
name Sample.obj and submit it to the linker. The linker combines the code from specified header file
into an object file and generates executable file as Sample.exe. With this compilation process
completes.

Now, we need to run the executable file (Sample.exe). To run a program we press Ctrl + F9. When
we press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs the task
according to the instructions written in that program and place the result into UserScreen.

Then we press Alt + F5 to open UserScreen and check the result of the program.

Important Points
 C program file (Source file) must save with .c extension.
 The compiler converts complete program at a time from high-level language to low-level
language.
 Input to the compiler is .c file and output from the compiler is .exe file, but it also
generates .obj file in this process.
 The compiler converts the file only if there are no errors in the source code.
 CPU places the result in User Screen window.
Overall Process
 Type the program in C editor and save with .c extension (Press F2 to save).
 Press Alt + F9 to compile the program.
 If there are errors, correct the errors and recompile the program.
 If there are no errors, then press Ctrl + F9 to execute/run the program.
 Press Alt + F5 to open User Screen and check the result.

C Input Functions

C programming language provides built-in functions to perform input operations. The input

operations are used to read user values (input) from the keyboard. The c programming language

provides the following built-in input functions.

1. scanf()

2. getchar()

3. getch()

4. gets()

5. fscanf()

scanf() function

The scanf() function is used to read multiple data values of different data types from the keyboard.

The scanf() function is built-in function defined in a header file called "stdio.h". When we want to use

scanf() function in our program, we need to include the respective header file (stdio.h)

using #include statement. The scanf() function has the following syntax...

Syntax:

scanf("format strings",&variableNames);
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
printf("\nYou have entered %d number",i);

Output:

In the above example program, we used the scanf() function to read an integer value from the

keyboard and store it into variable 'i'.

The scanf function also used to read multiple data values of different or the same data types.

Consider the following example program...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value : ");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);

Output:

In the above example program, we used the scanf() function to read one integer value and one float

value from the keyboard. Here 'i' is an integer variable so we have used format string %d, and 'x' is

a float variable so we have used format string %f.

The scanf() function returns an integer value equal to the total number of input values read using

scanf function.
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int i,a,b;
float x;
printf("\nEnter two integers and one float : ");
i = scanf("%d%d%f",&a, &b, &x);
printf("\nTotal inputs read : %d",i);

Output:

getchar() function

The getchar() function is used to read a character from the keyboard and return it to the program.

This function is used to read a single character. To read multiple characters we need to write

multiple times or use a looping statement. Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c\n",ch);

Output:

getch() function

The getch() function is similar to getchar function. The getch() function is used to read a character

from the keyboard and return it to the program. This function is used to read a single character. To
read multiple characters we need to write multiple times or use a looping statement. Consider the

following example program...

Example Program
#include<stdio.h>
#include<conio.h>

void main(){
char ch;
printf("\nEnter any character : ");
ch = getch();
printf("\nYou have entered : %c",ch);

Output:
gets() function

The gets() function is used to read a line of string and stores it into a character array. The gets()

function reads a line of string or sequence of characters till a newline symbol enters. Consider the

following example program...

Example Program
#include<stdio.h>
#include<conio.h>

void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
printf("%s",name);
}

Output:
fscanf() function

The fscanf() function is used with the concept of files. The fscanf() function is used to read data

values from a file. When you want to use fscanf() function the file must be opened in reading mode.

You might also like