0% found this document useful (0 votes)
18 views44 pages

Introduction to C Programming Basics

The document provides an introduction to the C programming language, covering its history, compilers, interpreters, algorithms, flowcharts, program structure, tokens, keywords, variables, data types, and operators. C, developed in 1972, is a powerful general-purpose language that serves as the foundation for many other programming languages. It emphasizes structured programming and is widely used in operating systems and application development due to its reliability and simplicity.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views44 pages

Introduction to C Programming Basics

The document provides an introduction to the C programming language, covering its history, compilers, interpreters, algorithms, flowcharts, program structure, tokens, keywords, variables, data types, and operators. C, developed in 1972, is a powerful general-purpose language that serves as the foundation for many other programming languages. It emphasizes structured programming and is widely used in operating systems and application development due to its reliability and simplicity.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Programming C

1. History
C is a programming language developed at AT& T’s (American Telephone & Telegraph)
Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis
Ritchie. It is developed to overcome the problems of previous languages such as B, BCPL,
etc.

C as a language was in use by 1973, although extra functionality such as new types was
introduced up until 1980. In 1978 the publication of The C ProgrammingLanguage by
Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C. The resulting definition, the ANSI
standard, or "ANSI C", was completed late 1988.

It is very powerful and general purpose high level language.


C programming is considered as base for other languages, that is why it is known as mother
language.
C is procedure oriented programming language and structure programming language.
C is conmsidered as very powerful because it supports the features of both low level and
high level language.
It was initially designed for programming UNIX operating system.
Major parts of popular operating systems like Windows, UNIX, Linux is still written in C.
C seems so popular is because it is reliable, simple and easy to use.
2. Compilers and Interpreters

Compilers: It is a program which is used to convert the high level language programs
into machinelanguage. The code in a source file stored on the disk must be translated
into machine language. This is the job of the compiler. The Compiler is a computer
program that translates the source code written in a high-level language into the
corresponding object code of the low-level language. This translation process is called
compilation. The entire high level program is converted into the executable machine
code file. The Compiler which executes C programs is called as C Compiler. Example
Turbo C, Borland C, GC etc.,

Interpreters: It is a program, it takes one statement of a high level language program,


translates it into machine language instruction and then immediately executes the resulting
machine language instruction and soon.

Comparison between a Compiler and Interpreter


Compiler Interpreter

A Compiler is used to compile An interpreter is used to translate


an entire program and an each line of the program code
executable program is immediately as it is entered
generated through the object program
Converts whole program at a time Converts program line by line
After conversion object code is stored After conversion object code is not
in memory stored in memory

To execute same program repeated To execute same program repeated


compilation is not required interpretation is required
The compiled programs run faster The Interpreted programs run slower
It will not participate in execution It will help to execute the program
It is Hard to detect syntax errors It is easy to detect syntax errors

It is hard to write It is easy to write


3. Algorithms

Algorithm is a finite sequence of instructions, each of which has a clear meaning and
can be performed with a finite amount of effort in a finite length of time. No matter
what the input values may be, an algorithm terminates after executing a finite number
of [Link] represent an algorithm using a pseudo language that is a
combination of the constructs of a programming language together with informal
English [Link] ordered set of instructions required to solve a problem is known
as an algorithm.
The characteristics of a good algorithm are:
 Precision – the steps are precisely stated(defined).

 Uniqueness – results of each step are uniquely defined and only depend on
theinput and the result of the precedingsteps.
 Finiteness – the algorithm stops after a finite number of instructions areexecuted.

 Input – the algorithm receives input.

 Output – the algorithm producesoutput.

 Generality – the algorithm applies to a set ofinputs.

Example

Write aalgorithem to find out number is odd or even?


step 1 : start
step 2 : inputnumber
step 3 : rem=number mod 2
step 4 : if rem=0then
print "number even" else
print "number odd" endif
step 5 :stop
4. Flowcharts

Flowchart is a diagrammatic representation of an algorithm. Flowchart is very


helpful in writing program and explaining program to others.

Symbols Used In Flowchart

Different symbols are used for different states in flowchart, For example: Input/Output
and decision making has different symbols. The table below describes all the symbols
that are used in making flowchart

Symbol Purpose Description

Used to indicate the flow of logic


Flow line by connecting symbols.

Terminal(Stop/Start) Used to represent start and end of


flowchart.

Input/Output Used for input and output operation.

Used for airthmetic


Processing
operations and data-
manipulations.

Used to represent the operation in


Desicion which there are two alternatives,
true and false.

On-page Connector Used to join different flowline


Off-page Connector Used to connect flowchart portion on
different page.

Predefined Used to represent a group of


Process/Function statements performing one
processing task.

Examples of flowcharts in programming

Draw a flowchart to add two numbers entered by user.


Draw flowchart to find the largest among three different numbers entered by user.
5. Structure of C Program
The structure of C program looks as follows:

Source Code

Documentation Section

Header Files:

#include

Manifest Constants:

#defines

User Supplied Function Prototypes

Global Varibale Definitions

Int main(void)

Local variable definitions

--body of program—

User written functions

Documentation section: The documentation section consists of a set of comment lines


giving the name of the program, the author and other details, which the programmer
would like to uselater.

Comments in C language are used to provide information about lines of code. It is


widely used for documenting code. There are 2 types of comments in the C language.
1. Single Line Comments:-Single line comments are represented by double slash \\. Let's see
an example of a single line comment in C.
#include<stdio.h>

int main(){

//printing information

printf("Hello C");

return 0;

2. Multi-Line Comments:-Multi-Line comments are represented by slash asterisk \* ... *\.


It can occupy many lines of code, but it can't be nested.

Syntax:
/* code
to be commented */

Example:
#include<stdio.h>
int main(){
/*printing information
Multi-Line Comment*/
printf("Hello C");
return 0;
}

Header Files (.h):


Header files contains declaration information for function or constants that are
referred in programs. They are used to keep source-file size to a minimum and to reducethe
amount of redundant information that must be coded.
# includes:
An include directive tells the preprocessor to include the contents of the specified file at
the point in the program. Path names must either be enclosed by double quotes or angle
brackets.
Example:
1: # include <stdio.h>
2: # include “mylib.h”
3: # include “mine\include\mylib.h”
In the example (1) above, the <> tells the preprocessor to search for the included file in
a special known \include directory or directories.
In the example (2), the double quotes (“ ”) indicate that the current directory should be
checked for the header file first. If it is not found, the special directory (or directories)
should be checked.
The example (3) is similar, but the named relative directory \mine\include is checked for
the header file mylib.h.
Relative paths can also be proceeded by the .\ or ..\ notation; absolute paths always
begin with a \.

# defines:
ANSI C allows you to declare constants. The # define directive is used to tell the
preprocessor to perform a search-and-replace operation.
Example:
# define Pi 3.14159
# define Tax-rate 0.0735
In the example above, the preprocessor will search through the source file and replace
every instance of the token Pi with 3.14159
After performing the search and replace operation, the preprocessor removes the
# define line.
User supplied function prototypes:
Declares the user-written functions actually defined later in the source file. A function
prototype is a statement (rather than an entire function declaration) that is placed a
head of a calling function in the source code to define the function's label before it is
used. A function prototype is simply a reproduction of a function header (the first line of
a function declaration) that is terminated with a semi-colon.

Global variable definitions:


Create the Global variables before main ().

The main function:


main ():The main function is the entry point in the C program. All C programs
begin execution by calling the main () function. When the main function
returns, your program terminates execution and control passes back to
the operating system.
Every C/C++ program must have one and only one main function.
{:The next line consists of a single curly brace which signifies the start of
main () function.
int age ; :The first line of code inside function main () is declaration of variables. In
C all variables must be declared before they are used.
} :which signifies the end of main () function.

User-written functions:
Divide the application into logical procedural units and factor out commonly used code to
eliminate repetition
6. C Tokens

C tokens are the basic buildings blocks in C language which are constructed together to
write a C [Link] and every smallest individual unit in a C program is known as C
tokens. C tokens are of six types.
They are
Keywords (eg: int,while),

Identifiers (eg: main,total),

Constants (eg: 10,20),

Strings (eg: ―total‖,―hello‖),

Special symbols (eg: (), {}),


Operators (eg: +, /,-,*)

Keywords

C keywords are the words that convey a special meaning to the c compiler. The
keywords cannot be used as variable names. 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.

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.

The list of C keywords is given below:

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

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:

Data type = variable list;

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.

Primary Data types

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.

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

Type Description

char Typically a single octet(one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.


double A double-precision floating point value.

void Represents the absence of type.

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

int will be 2 bytes or 16 bits in the case of an environment that is 16-bit. However, int will
be 4 bytes or 32 bits in case of an environment that is 32-bit.

Syntax:

int

int num1;

short int num2;

long int num3;

Example: 5, 6, 100, 2500.

2. Floating Point data type

Floating-point data types are a set of numbers with the decimal value. Every floating-point
value must contain the decimal value. We use the keyword "float" to represent floating-point
data type. The float value contains 6 decimal places. The size of the float data type is
basically 32 bits or 4 bytes.
Syntax:

float ;

float num1;

Example: 9.125,

3. Double data type

double data type are a set of numbers with the decimal value. double is same as float but
with longer precision and takes double space (8 bytes) than float. To extend the precision
further we can use long double which occupies 10 bytes of memory space. It is capable of
storing values that are comparatively double the size of the bytes that the float data type can
store. This is the reason why it is known as the double. This data type is capable of holding
about 15-17 digits, both after and before the decimal of the data type.

Syntax:

double num2;

long double num3;

Example: 3.1254.

4. Character data type

Character type variable can hold a single character and are declared by using the keyword
char. The character data type is a set of characters enclosed in single quotations. The size of
the char data type is basically 8 bits or 1 byte.

Syntax:

char ;

char ch = ‘a’;
Example: a, b, g, S, j.

Void Type:

Void data type is a data type used to indicate nothing or null. Void doesn't have any
meaning. Void data type cannot hold any data type because it is an empty data type. Void
data type is not useful for declaring variables or identifiers but it is useful in the case of
functions while returning a value. You can find the importance of void data type in functions
in the next articles.

Operators

C language offers many types of operators. They are,


1. Arithmeticoperators
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.

Arithmetic
[Link] Operators Operation Example

1 + Addition A+B

2 – Subtraction A-B

3 * multiplication A*B

4 / Division A/B

5 % Modulus A%B
Example:
#include <stdio.h>int
main()
{
int a=40,b=20,add,sub,mul,div,mod;
add =a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n",
mul); printf("Division of a, b is : %d\n",
div); printf("Modulus of a, b is : %d\n",
mod);
}
Output:

Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0

2. Assignmentoperators

In C programs, values for the variables are assigned using assignment operators.
Forexample,ifthevalue10istobeassigned forthevariable sum,itcanbe assignedas
sum= 10;
Other assignment operators in C language are given below.

Operators Example Explanation

Simple
= sum = 10
assignme
10 is assigned to variable sum
nt
operator

+= sum += 10 This is same as sum = sum + 10

-= sum -= 10 This is same as sum = sum – 10

*= sum *= 10 This is same as sum = sum * 10

/+ sum /= 10 This is same as sum = sum / 10

This is same as sum = sum % 10


sum %= 10
%=

Example:
# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Toatal+i
}
printf("Total = %d", Total);
}

Output:

Total = 45

3. Relationaloperators

Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a Cprogram.

[Link] Operators Example Description

x is greater than y
1 > x>y

2 < x<y x is less than y

x is greater than or equal to y


3 >= x >= y

x is less than or equal to y


4 <= x <= y

5 == x == y x is equal to y

x is not equal to y
6 != x != y

Example:
#include<stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}

Output:

m and n are not equal

4. Logicaloperators

These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||)
and logical NOT (!).

[Link] Operat Name Example Description


ors
logical It returns true when both
1 && (x>5)&&(y<5)
AND conditions aretrue

2 || logical OR (x>=10)||(y>=10) It returns true when at-least


one of the condition is true
3 ! logical !((x>5)&&(y<5)) It reverses the state of the
NOT operand
―((x>5)&&
(y<5))‖

If―((x>5)
&& (y<5))‖ is true, logical
NOT operator makes
itfalse

Example:

#include <stdio.h>

int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n &&m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true.
" \ "But, status is inverted as false\n");
}
}

Output:

&&Operator : Both conditions are true


|| Operator : Only one condition is true

! Operator : Both conditions are true. But, status is inverted as false

5. Bitwiseoperators
The bitwise operators are the operators used to perform the operations on the data at the
bit-level. When we perform the bitwise operations, then it is also known as bit-level
programming. It consists of two digits, either 0 or 1. It is mainly used in numerical
computations to make the calculations faster.
We have different types of bitwise operators in the C programming language.
The followingis the list of the bitwise operators:
Operator Meaning of operator
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive ORoperator
~ One's complement operator(unary operator)
<< Left shift operator

>> Right shift operator

Let's look at the truth table of the bitwise operators.


X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1

1 1 1 1 1

Bitwise AND operator


Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands
are written on both sides of the (&) operator. If the corresponding bits of both the operands
are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0.
For example,
We have two variables a and b.
a =6;
b=4;
The binary representation of the above two variables are given below:
a = 0110
b = 0100
When we apply the bitwise AND operation in the above two variables, i.e., a&b, the output
would be:
Result = 0100

Example :
#include <stdio.h>
int main()
{
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b is %d",a&b);
return 0;
}
Output:
The output of Bitwise AND operator a&b is 6

Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands
are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the
output would be 1, otherwise 0.
For example,
We consider two variables,
a = 23;
b = 10;
The binary representation of the above two variables would be:
a = 0001 0111
b = 0000 1010
When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the output
would be:
Result = 0001 1111

Example:
#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is %d",a|b);
return 0;
}
Output:
The output of the Bitwise OR operator a|b is 31
Bitwise exclusive OR operator
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both
sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then
the output would be 1, otherwise 0.
For example,
We consider two variables a and b,
a = 12;
b = 10;
The binary representation of the above two variables would be:
a = 0000 1100
b = 0000 1010
When we apply the bitwise exclusive OR operator in the above two variables (a^b), then the
result would be:
Result = 0000 1110

Example:
#include <stdio.h>
int main()
{
int a=12,b=10; // variable declarations
printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
return 0;
}
Output:
The output of the Bitwise exclusive OR operator a^b is 6
Bitwise complement operator
The bitwise complement operator is also known as one's complement operator. It is
represented by the symbol tilde (~). It takes only one operand or variable and performs
complement operation on an operand. When we apply the complement operation on any
bits, then 0 becomes 1 and 1 becomes 0.
For example,
If we have a variable named 'a',
a = 8;
The binary representation of the above variable is given below:
a = 1000
When we apply the bitwise complement operator to the operand, then the output would be:
Result = 0111

Example:
#include <stdio.h>
int main()
{
int a=8; // variable declarations
printf("The output of the Bitwise complement operator ~a is %d",~a);
return 0;
}
Output
The output of the Bitwise complement operator ~a is 7
Bitwise shift operators
Two types of bitwise shift operators exist in C programming. The bitwise shift operators will
shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise shift
operator is divided into two categories:
Left-shift operator
Right-shift operator

Left-shift operator
It is an operator that shifts the number of bits to the left-side.
Syntax of the left-shift operator is given below:
Operand << n
Where,Operand is an integer expression on which we apply the left-shift operation.
n is the number of bits to be shifted.
In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n' bits on the
left
side will be popped out, and 'n' bits on the right-side are filled with 0.
For example,
Suppose we have a statement:
int a = 5;
The binary representation of 'a' is given below:
a = 0101
If we want to left-shift the above representation by 2, then the statement would be:
a << 2;
0101<<2 = 00010100

Example :
#include <stdio.h>
int main()
{
int a=5; // variable initialization
printf("The value of a<<2 is : %d ", a<<2);
return 0;
}
Output
The value of a<<2 is : 20

Right-shift operator
It is an operator that shifts the number of bits to the right side.
Syntax of the right-shift operator is given below:
Operand >> n;
Where,Operand is an integer expression on which we apply the right-shift operation.
N is the number of bits to be shifted.
In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits on
the right-side will be popped out, and 'n' bits on the left-side are filled with 0.
For example,
Suppose we have a statement, int a = 7;
The binary representation of the above variable would be: a = 0111
If we want to right-shift the above representation by 2, then the statement would be:
a>>2;
0000 0111 >> 2 = 0000 0001
Let's understand through a program.
#include <stdio.h>
int main()
{
int a=7; // variable initialization
printf("The value of a>>2 is : %d ", a>>2);
return 0;
}
Output : The value of a>>2 is : 1

6. Conditional operators (ternaryoperators)

Conditional operators return one value if condition is true and returns another value is
condition is false.

This operator is also called as ternary operator.

Syntax : (Condition? true_value:false_value);

Example: (A >100 ? 0 :1);

In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if
else conditional statements.

Example

#include <stdio.h>int
main()
{
int x=1, y;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Output:

x value is 1

y value is 2
7. Increment/decrementoperators

Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in
Cprograms.
Below table will explain the difference between pre/post increment and decrement operators
in C.

[Link] Operator type Operator Description

1 Pre increment ++i Value of i is incremented before


assigning it to variable i.

i++ Value of i is incremented after


2 Post–increment
assigning it to variable i.
— –i Value of i is decremented before
3 Pre decrement
assigning it to variable i.
i– — Value of i is decremented after
4 Post_decrement
assigning it to variable i.

Syntax:
Increment operator: ++var_name ;( or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;

Example:

Increment operator : ++i; i ++ ;


Decrement operator : – – i ; i – – ;
//Example for increment operators

#include <stdio.h>
int main()
{

int i=1;
while(i<10)
{

printf("%d ",i); i++;


}
}
Output:

123456789

//Example for decrement operators


#include <stdio.h>
int main()
{

int i=20;
while(i>10)
{

printf("%d ",i); i--;


}
}
Output:

20 19 18 17 16 15 14 13 12 11
8. Specialoperators
Below are some of special operators that C language offers.

[Link] Operators Description

1 & This is used to get the address of the variable.

Example : &a will give address of a.

2 * This is used as pointer to a variable.

Example : * a where, * is pointer to the


variablea.

3 Sizeof () This gives the size of the variable.

Example : size of (char) will give us 1.

Formatted I/O Statements

Formatted Output

The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the
parameters to the printf() function.
Syntax:

printf (format,data1,data2,…);
In this syntax format is the format specification string. This string contains, for each
variable to be output, a specification beginning with the symbol % followed by a
character called the conversion character.
Example:

printf(―%c‖, data1);
The character specified after % is called a conversion character because it allows one
data type to be converted to another type and printed.
See the following table conversion character and their meanings.

Conversion Meaning

Character
d The data is converted to decimal (integer)
C The data is taken as a character.
S The data is a string and character from the string , are printed
until a NULL,

character is reached.
F The data is output as float or double with a default Precision 6.
Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)
Example

printf(―%c\n‖,data1);

The format specification string may also have text.

Example

printf(―Character is:‖%c\n‖, data1);

The text "Character is:" is printed out along with the value of data1.

Example with program


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

Main()

{
Char alphabh="A";

int number1= 55;

float number2=22.34;
printf(“char= %c\n”,&alphabh);
printf(“int= %d\n”,&number1);
printf(“float= f\n”,&number2);
getch();
clrscr();
retrun 0;
}

Output Here…

char =A

int= 55
flaot=22.340000
Formatted Input

The function scanf() is used for formatted input from standard input and provides
many of the conversion facilities of the function printf().
Syntax

scanf (format, num1, num2,……);

The function scnaf() reads and converts characters from the standards input depending
on the format specification string and stores the input in memory locations represented
by the other arguments (num1, num2,….).
For Example:
scanf(―%c %d‖,&Name,&Roll No);
Unformatted I/O Statements

Unformatted I/O refers to operations that reads or writes data without any format.

Unformatted input and output functions read a single input sent by the user.

Unformatted Input and Output functions take the character, character array, and strings as
input. We can read-only character data types with these functions. These functions are
already defined in the libraries. It reads only a single input from the user and displays the
value on the console output screen.

Types of Unformatted Input and Output Function in C

1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()

1. getch():
getch() function is a built-in function declared in conio.h header file. It reads a single
character from the keyboard. The input character won't be displayed on the console Output
screen. getch() function immediately returns the input character without pressing the enter
key.
getch() is also used for hold the output screen.

In this function we won't pass any parameters,

Syntax:
getch() or variable name= getch();
Example:
#include <conio.h>
#include <stdio.h>
int main()
{
Char ch;
printf("Enter any character: ");
ch=getch(); // A character is entered, but it won't be displayed on the screen
printf(“character is %c”,ch);
return 0;
}

getche():
getche() function is a built-in function declared in conio.h header file. It reads a single
character from the keyboard. The input character will be displayed on the console Output
screen. getch() function immediately returns the input character without pressing the enter
key.
In this function, we won't pass any parameters
Syntax:
getche() or variable name= getche();

Example:
#include <conio.h>

#include <stdio.h>

int main()

Char ch;
printf("Enter any character: ");

ch=getche(); // A character is entered but it will be displayed on the screen immediately

printf(“character value:%c”,ch);

return 0;

getchar():
getchar() function is a built-in function declared in stdio.h header file. It reads a single
character from the keyboard if the user enters multiple characters or a single character.
In this function, we won't pass any parameters
Syntax

Variable name= getchar();

Example

#include <stdio.h>

int main()

charch; // declaring a character variable

printf("Enter the character: ");

ch = getchar(); // reading the character from the keyboard

printf(" \nThe entered character is: %c", ch); // printing the entered character

return 0;

}
In the output, we gave the input as "Hello", but in the output, it displayed only H. By this,
we can say only the first character is considered in the getchar() function.

gets():
gets() is a built-in function present stdio.h header file. By using gets() function, we can read
the collection of characters or a string. We should have to declare a character array to store
the string. This function allows spaces in the string.
This function takes a character or a string as a parameter
Syntax:

Charstr[ size ]; //declaration of character array

gets(str);

Example

#include <stdio.h>

int main()

Charstr[100]; // declaration of character array str of size 100

printf("Please enter a string: ");

gets(str); // reading the string using gets() function

printf(" \nThe Entered string is: %s",str); // printing the string

return 0;

}
putchar():
putchar() is a built-in function present stdio.h header file. It displays a single character from
the keyboard if the user enters multiple characters or a single character.
We can pass the character into the function or by passing a variable which has stored a
[Link]() prints a single character.
It takes a single character or a variable as parameter. And return a character on the console
output screen.
Syntax:
putchar(variable_name);
It takes a single character or a variable as parameter. And return a character on the console
output screen.

Example

#include <stdio.h>

int main()

charch; // declaring the character

printf("Enter any character: ");// Reads a character

scanf("%c",&ch);// Displays that character using putchar function

printf(" \nThe entered character is: ");

putchar(ch); // method 1

printf("\n second method\n The passed character is: ");

putchar('A'); // Method 2

return 0;

}
puts():
puts() is a built-in function present stdio.h header file. By using puts() function, we can print
the collection of characters or a string. We should have to declare a character array to store
the string. This function also prints spaces between the characters.

Syntax:
puts( character array);
This function takes a character array or a string as a parameter. And returns a string or a
character array on the console output screen.
Example:// program to implement the gets() function in C

#include <stdio.h>

int main()

charstr[100]; // declaration of character array str of size 100

printf("Please enter a string: ");

gets(str); // reading the string using gets() function

printf(" \nThe Entered string is: %s",str); // printing the string using printf()

printf(" \nThe Entered string is: ");

puts(str); // printing the string using puts function

return 0;

}
Output:

7. putch():
putch() function is a built-in function in C present in conio.h header file. It is used to display
a single character on the console output screen.
Syntax:
putch( variable name );
This function takes a single character or a variable as a parameter. And it returns a single
character on the console output screen.
Example program:// program to implement the putch() function in C

#include <stdio.h>

int main()

Charch;

printf("Enter any character:\n ");

ch = getch(); // reading the character using getch() function

printf("\nTheEntered character is: "); // Displays that character on the console output screen

putch(ch); // using putch() function

return 0;

}
Output:

Enter any character:

The Entered character is: H

You might also like