PC Unit II Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

U23CSTC01–Programming In C Regulation 2023

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Subject Name: Programming in C


Subject Code: U23CSTC01
Year/Sem/Sec: I / I / E

Prepared by:
Ms. V. SWATHILAKSHMI / AP /CSE

Verified by: Approved by:

UNIT II
I
C PROGRAMMING BASICS
Introduction to ‘ C’ Programming – Basic structure of a ‘C’ program – compilation
and linking processes – Constants, Variables – Data Types – Expressions using
operators in ‘C’ – Managing Input and Output operations – Decision Making and
Branching – Looping statements.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

INTRODUCTION TO ‘C’ PROGRAMMING


C is a general-purpose high level language that was originally developed by Dennis
Ritchie at AT & T’s Bell Laboratories in 1972. Many of the important ideas of C stem from the
language
BCPL (Basic Combined Programming Language), developed by Martin
Richards.
C is a general-purpose high level language that was originally developedby Dennis Ritchie for the
UNIX operating system. It was first implemented on the Digital Equipments Corporation PDP-11
computer in 1972.
C has now become a widely used professional language for variousreasons.

• Easy to learn
• Structured language
• It produces efficient programs.
• It can handle low-level activities.
• It can be compiled on a variety of computers.
History of C language
C is one of the most popular programming languages; it was developed by Dennis
Ritchie at AT & T‟s Bell Laboratories of USA in 1972.

Programming Language Year Founder

ALGOL 1960 International Group


BCPL 1967 Martin Richards
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&R C 1978 Brain Kernighan andDennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

C is a middle language
• Low level language-0 and 1‟s.
• High level language: eg FORTRAN, PASCAL, COBOL, BASIC,C, C++……etc.
• C stands in between these two categories. It is neither a low levellanguage nor a high level
language. It is a middle level language.
Features and applications of C language
• C is a general purpose, structured programming language.
• It is powerful, efficient, compact and flexible.
• It is highly portable.
• It is a robust language.
• C is a middle level language, i.e. it supports both the low level language and high level
language features.
• C language allows dynamic memory allocation.
• C programs are fast and efficient.
• C has got rich set of operators.
• It can be applied in systems programming areas like compilers,interpreters and assemblers,
etc.

BASIC STRUCTURE OF A ‘C’ PROGRAM

The basic structure of a C program is divided into 6 parts which makes it easy to read,
modify, document, and understand in a particular format. C program must follow the below-

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

mentioned outline in order to successfully compile and execute. Debugging is easier in a well-
structured C program.
Sections of the C Program
There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:
1. Documentation
2. Pre-processor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Documentation can be represented as:
2. Pre-processor Section
All the header files of the program will be declared in the pre-processor section of the
program. Header files help us to access other’s improved code into our code. A copy of these
multiple files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
Pre-processors are the programs that process our source code before the process of
compilation. There are multiple steps which are involved in the writing and execution of the
program. Pre-processor directives start with the ‘#’ symbol. The #define pre-processor is used to
create a constant throughout the program. Whenever this name is encountered by the compiler, it
is replaced by the actual piece of defined code.
Example:
#define long long ll
4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

program.
Example:
int num = 18;
5. Main () Function
Every C program must have a main function. The main() function of the program is written
in this section. Operations like declaration and execution are performed inside the curly braces of
the main program. The return type of the main() function can be int as well as void too. void()
main tells the compiler that the program will not return any value. The int main() tells the compiler
that the program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function. These are specified as per the requirements of the programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
Structure of C Program with example
Example: Below C program to find the sum of 2 numbers:

// Documentation
/*program to find sum.*/
#include <stdio.h> // Definition
#define X 20 // Global Declaration
int sum(int y); // Main() Function
int main(void)

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}

Output
Sum: 75
Explanation of the above Program

Sections Description

/*program to find sum. It is the comment section and is part of the description section of
*/ the code.

Header file which is used for standard input-output. This is the


#include<stdio.h> preprocessor section.

This is the definition section. It allows the use of constant X in the


#define X 20 code.

This is the Global declaration section includes the function


int sum(int y) declaration that can be used anywhere in the program.

int main() main() is the first function that is executed in the C program.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Sections Description

These curly braces mark the beginning and end of the main
{…} function.

printf(“Sum: %d”, sum(y)); printf() function is used to print the sum on the screen.

We have used int as the return type so we have to return 0 which


states that the given program is free from the error and it can be
return 0; exited successfully.

int sum (int y)


{ This is the subprogram section. It includes the user-defined
return y + X; functions that are called in the main() function.
}

COMPILATION AND LINKING PROCESSES


The compilation is the process of converting the source code of the C language into
machine code. As C is a mid-level language, it needs a compiler to convert it into an executable
code so that the program can be run on our machine.
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.
The pre-processor takes the source code as an input, and it removes all the comments from the
source code. The pre-processor takes the pre-processor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the pre-processor interprets the
directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into an
executable form:
o Pre-processor
o Compiler
o Assembler
o Linker

Pre-processor
The source code is the code which is written in a text editor and the source code file is
given an extension ".c". This source code is first passed to the pre-processor, and then the pre-
processor expands this code. After expanding the code, the expanded code is passed to the
compiler.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Compiler
The code which is expanded by the pre-processor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the
object file generated by the assembler is the same as the source file. The extension of the object
file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file
is 'hello.c', then the name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code of our
program. Sometimes the situation arises when our program refers to the functions defined in other
files; then linker plays a very important role in this. It links the object code of these files to our
program. Therefore, we conclude that the job of the linker is to link the object code of our program
with the object code of the library files and other files. The output of the linker is the executable
file. The name of the executable file is the same as the source file but differs only in their
extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the executable file
can be named as 'a.out'. For example, if we are using printf() function in a program, then the linker
adds its associated code in an output file.

CONSTANTS
The constants in C are the read-only variables whose values cannot be modified once
they are declared in the C program. The type of constant can be an integer constant, a floating
pointer constant, a string constant, or a character constant. In C language, the const keyword is
used to define the constants.
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is declared in
the program. We can not make any change in the value of the constant variables after they are
defined.
How to define a constant in C?
We define a constant in C language using the const keyword. Also known as a const type qualifier,

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

the const keyword is placed at the start of the variable declaration to declare that variable as a
constant.
Syntax to Define Constant

const data_type var_name = value;

Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the
list of the types of constants
• Integer Constant
• Character Constant
• Floating Point Constant
• Double Precision Floating Point Constant
• Array Constant
• Structure Constant
Properties of Constant in C
The important properties of constant variables in C defined using the const keyword are as
follows:
1. Initialization with Declaration
We can only initialize the constant variable in C at the time of its declaration. Otherwise, it will
store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be initialized only once
in the whole program. After that, we cannot modify the value stored inside that variable.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

VARIABLES
In C, a variable is a data name used for storing a data value. Its value may be changed
during program execution. The value of variables keeps on changing during the execution of a
program. In other words, a variable can be assigned different values at different times during the
execution of a program.
The variable can be of different data types. They can be integer, float or character data types.
These data are stored in the memory and at the time of execution different operations are
performed on them.

Rules for naming the variables:


• A variable name can be any combination of alphabets, digits or underscore.
• But first character should be alphabets or an underscore (_).
• The length of the variable cannot exceed up to 8 characters long.
• Some of the c compilers can be recognized up to 31 characters long.
• The variable should not be a C keyword.
• Both lowercase and uppercase are permitted.
• The special symbols are not permitted except underscore.

Variable declaration:
Syntax:

datatype v1,v2,v3,….,vn;

Description:
data_type - It is the type of data.
v1, v2, v3 ,…, vn - list of variables.
Example 1:
int regno;
float cgpa;
char name[10];
Variables are declared at three basic places:
• When the variables are declared inside a function, they are called local variables.
• When the variables are declared in the definition of function parameters, these variables are
called formal parameters.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

• When the variables are declared outside all functions, they are called global
variables.“Variables used in expressions are also known as operands”
Initializing variables:
Initialization of variables can be done using the assignment operator(==).
Syntax:
Variable = constant;
Or
Datatype variable = constant;
Example:
A=5; B=8;
int i =23; float s=3.14;
Scope of variables
Scope of a variable implies the availability of variables within the program.
Two types:
• Local variables
• Global variables
(i)Local variable
Scope of a variable implies the availability of variables within the program..
Example
#include<stdio.h>
#include<conio.h>
void main()
/*local variable declaration */
int a,b;
int c;
/*actual initialization*/
a=10;
b=20;
c=a+b;
printf(“value of local variable\n a=%d\nb=%dc=%d\n”,a,b,c); getch();
}

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Output
value of local variable a=10
b=20 c=30
Here all the variables a,b,c are local to main() function.

2.Global Variable
Global variable are variable defined outside the function, usually on the top of the program. The
global variable will hold their value throughout the lifetime of the program and it can be accessed
by the function defined in the program.
Example
#include<stdio.h>
#include<conio.h>
/*global variable declaration*/
int g;
void main()
int a,b;
clrscr();
/*actual initialization*/
a=10;
b=20;
g=a+b;
printf(“value of local variable\n a=%d\nb=%dg=%d\n”,a,b,g);
getch();
}
Output
value of local variable
a=10 b=20 g=30

DATA TYPES
Data type is the type of the data, that are going to access within the program. C supports
different data types, each data may have predefined memory requirement and storage
representation.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

C supports the following 4 classes of data types

(i) Primary data types:


C has the following basic built-in primary data types.
• int
• float
• double
• char
Int (Integer)
Integer data type is used to store numeric values without any decimalpoint
e.g. 7, - 101, 107, etc.

Syntax: int variable name;

Example:
int roll, marks, age;
Float
Float data type is used to store numeric values with decimal point. In other words, float
data type is used to store real values, e.g. 3.14, 7.67 etc. e.g. percentage, price, pi, area etc. may
contain real values.

Syntax: float variable name;

Example: float per, area;

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Char (Character)
Char (Character) data type is used to store single character, within singlequotes e.g. 'a', 'z','e' etc.
e.g. Yes or No Choice requires only 'y' or 'n' as an answer.

Syntax: char variable name;

Example: char chi='a', cha;


Double
Double is used to define BIG floating point numbers. It reserves twicethe storage for the
number. It contains 8 bytes.

Syntax: double variable name;

Example: double Atoms;


(ii) User defined data type: User defined data type is used to create newdata types. The new
data types formed are fundamental data types.
Typedef:
The 'typedef' allows the user to define new data-types that are equivalentto existing data types.
Once a user defined data type has been established, then new variables, array, structures, etc. can
be declared in terms of this new data type.

Syntax: typedef type new-type;

Type refers to an existing data type. New-type refers to the new user-defined data type.
Example: typedef int number;
Declare integer variables as: number roll, age, marks;It is equivalent to: int roll, age, marks;
Enum:
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names
to integral constants, the names make a program easy to read and maintain.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

(iii) Derived Data type:


Data types that are derived from fundamental data types are called derived data types.
Derived data types don't create a new data type;instead, they add some functionality to the basic
data types.

Array
An array is a collection of variables of same type i.e. collection ofhomogeneous data referred
by a common name. In memory, arrayelements are stored in a continuous location.
Syntax: datatype arrayname [Size of the array];

Pointer
A pointer is a special variable that holds a memory address (location inmemory) of another
variable.

Syntax: datatype *var_name;

* is a pointer variable. 'var_ name' is the name where the variable is tobe stored.
Example:
int a,*b; variable 'b' stores the address of variable 'a'.
Function:
A function in C is a set of statements that when called perform some specific task. It is the
basic building block of a C program that provides modularity and code reusability. The
programming statements of a function are enclosed within { } braces, having certain meanings and
performing certain operations. They are also called subroutines or procedures in other languages.

Struct
A struct is a user defined data type that stores multiple values of sameor different data types
under a single name. In memory, the entire structure variable is stored in sequence.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Syntax:
struct < structure name>
{
member1;member2;

};

Structure name is the name of structure


e.g. store details of a student as-name, roll, marks.
struct student
{
char name [20];
int roll, float marks;
};
Union
A union is a user defined data type that stores multiple values of same ordifferent data types
under a single name. In memory, union variables arestored in a common memory location.
Tag name is the name of union, e.g, store details of a student as- name,roll, and marks.
Union student
{
char name [20];int roll;
float marks;
};

(iv) EMPTY DATA TYPE


Void
Void data type is used to represent an empty value (or) null value. It is used as a return type if
a function does not return any value.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

EXPRESSIONS USING OPERATORS IN ‘C’


OPERATORS
An operator is a symbol or a special character used to perform certain mathematical or
logical manipulations.
Operands
Operands are variable or expressions used in operators to evaluate the expression.
Combination of operands and operators forms an expression.
Various types of Operators

S.no Types of operators Descriptions

Used to perform mathematical calculations like addition


1. Arithmetic operators
subtraction, multiplication division and modulus

2. Assignment operators Used to assign the values for the variable in C programs

3. Relational operators Used to compare the value of two variables

Used to perform logical operations on the given two


4. Logical operators
variable

5. Bitwise operators Used to perform bit operations on the given two variable

6. Conditional (ternary) operators Used to check whether the statement is true or false

Used to increase or decrease the value of the variable by


7. Increment/Decrement operator
1

8. Special operators &,*,sizeof() and ternary operators

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

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

S no Arithmetic 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>
#include<conio.h>
void main()
{
int 40, b=20,
float add,sub,mul,div,mod;
clrscr();
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);
getch();
}

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

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. Assignment Operators
In C program, values for the variables are assigned using assignment operators

Operators Example Explanation


Simple assignment
= Sum=10 10 is assigned to variable sum
operators

+= 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

Compound Assignment
/= Sum/=10 This is same as sum=sum/10
Operators

%= 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

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

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

int total=0,i;
for(i=0;i<10;i++)
{
total+=i;
}
printf("total=%d",total);
getch();
}
Output
Total=45
3. Relational operator
Relational operators are used to find the relation between two variables. i.e to compare the value of
two variables in a c program.

S. no Operators Example Description

1. > x>y x is greater than y

2. < x<y x is less than y

3. >= x >=y x is greater than or equal to y

4. <= x <=y x is lesser than or equal to y

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

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

Example
#include<stdio.h>
#include<conio.h>
void main()
{
int m=40,n=20;
if(m==n)

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
getch();
}

Output
m and n are not equal
1. Logical operators
These operators are used to perform logical operators on the given expression

SNO OPERATORS NAME EXAMPLE DESCRIPTION

It returns true when both conditions


1. && logical AND (x>5)&&(y<5)
are true

It returns true when atleast one of the


2. || logical OR (x>=10)||(y>=10)
condition is true

It reverses the state of the operand


“((x>5)&&(y<5)”
3. ! logical NOT !((x>5)&&(y<5) If “((x>5)&&(y<5)”
is true, logical NOT operator makes
it false.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Example
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0 (a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
4. Bitwise Operators
These operators are used to perform bitwise operations. Decimal values are converted into
binary values and bitwise operators work on these bits.

OPERATOR SYMBOL OPERATOR NAME

& bitwise AND

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

| bitwise OR

~ bitwise NOT

^ XOR

<< Left shift

>> Right shift

5. Conditional or Ternary operators


Conditional operators return one value if condition is true and returns another value
if condition is false. This operator is also called as ternary operator.

(Conditional expression?true_value:false_value);

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

6. Increment /decrement operators


Increment operators are used to increase the value of the variable by one and decrement operator
are used to decrease the value of the variable by one in C programs.

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

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

SNO OPERATOR TYPE OPERATOR DESCRIPTION

1. pre increment ++i value of i is incremented before assigning it to variable i

2. post increment i++ value of i is incremented after assigning it to variable i

3. pre decrement --i value of i is decremented before assigning it to variable i

4. post decrement i-- value of i is decremented after assigning it to variable i

Example
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10;
printf(“a++=%d\n”,a++);
printf(“++a=%d\n”,++a);
printf(“a--=%d\n”,a--);
printf(“--a=%d\n”,--a);
}

Output
a++=10
++a=12 a--=12
--a=10

7. Special Operator
C language supports some of the special operators they are

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

OPERATORS MEANING

, comma operators

Size of Size of operators

& and * Pointer operators

. and -> Member section operators

EXPRESSION
An expression in C is a combination of operands and operators – it computes a single value
stored in a variable. The operator denotes the action or operation to be performed.
The operands are the items to which we apply the operation.

An expression can be defined depending on the position and number of its operator and
operands:
1. Infix Expression (operator is used between the operands) a=x+y
2. Postfix Expression (operator is used after the operands) xy+
3. Prefix Expression (operator is used before the operands) +xy
4. Unary Expression (one operator and one operand) x++
5. Binary Expression (one operator and two operands) x+y
Types of Expression
There are six types of expressions. These are shown below:
Arithmetic Expression
It consists of arithmetic operators ( + , - , * , and / ) and computes values of int, float, or
double type.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Relational Expression
It usually consists of comparison operators (> , < , >= , <= , === , and !== ) and computes
the answer in the bool type, i.e., true (1) or false (0).
Logical Expression
It consists of logical operators (&&, ||, and !) and combines relational expressions to compute
answers in the bool type.
Conditional Expression
It consists of conditional statements that return true if the condition is met
and false otherwise.
Pointer Expression
It may consist of an ampersand (&) operator and returns address values.
Bitwise Expression
It consists of bitwise operators ( >>, <<, ~, &, |, and ^ ) and performs operations at the bit
level.

MANAGING INPUT AND OUTPUT OPERATIONS


Input =Output Statements
In C Language input and output function are available as C compiler functions or C libraries
provided with each C compiler implementation. These all functions are collectively known
as Standard I/O Library function. Here I/O stands for Input and Output used for different
inputting and outputting statements. These I/O functions are categorized into three processing
functions. Console input/output function (deals with keyboard and monitor), disk input/output
function (deals with floppy or hard disk), and port input/output function (deals with a serial or
parallel port). As all the input/output statements deals with the console, so these are also Console
Input/Output functions. Console Input/Output function access the three major files before the
execution of a C Program. These are as follows:

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

• stdin: This file is used to receive the input (usually is keyborad file, but can also take input
from the disk file).
• stdout: This file is used to send or direct the output (usually is a monitor file, but can also
send the output to a disk file or any other device).
• stderr: This file is used to display or store error messages.
Input Ouput Statement

Input and Output statement are used to read and write the data in C programming. These
are embedded in stdio.h (standard Input/Output header file).
Input means to provide the program with some data to be used in the program and Output means
to display data on screen or write the data to a printer or a file.C programming language provides
many built-in functions to read any given input and to display data on screen when there is a need
to output the result.
There are mainly two of Input/Output functions are used for this purpose. These are discussed as:
• Unformatted I/O functions
• Formatted I/O functions

Unformatted I/O functions

There are mainly six unformatted I/O functions discussed as follows:


• getchar()
• putchar()
• gets()
• puts()
• getch()

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

• getche()
getchar()
This function is an Input function. It is used for reading a single character from the keyboard. It is
a buffered function. Buffered functions get the input from the keyboard and store it in the memory
buffer temporally until you press the Enter key.
The general syntax is as:

v = getchar();

where v is the variable of character type.


For example:
char n;
n = getchar();
A simple C-program to read a single character from the keyboard is as:
/*To read a single character from the keyboard using the getchar() function*/
#include <stdio.h>
main()
{
char n;
n = getchar();
}
putchar()
This function is an output function. It is used to display a single character on the screen. The
general syntax is as:

putchar(v);

where v is the variable of character type. For example:


char n;
putchar(n);
A simple program is written as below, which will read a single character using getchar() function
and display inputted data using putchar() function:
/*Program illustrate the use of getchar() and putchar() functions*/
#include <stdio.h>
main()
{

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

char n;
n = getchar();
putchar(n);
}
gets()
This function is an input function. It is used to read a string from the keyboard. It is also a
buffered function. It will read a string when you type the string from the keyboard and press the
Enter key from the keyboard. It will mark null character (‘\0’) in the memory at the end of the
string when you press the enter key. The general syntax is as:

gets(v);

where v is the variable of character type. For example:


char n[20];
gets(n);
A simple C program to illustrate the use of gets() function:
/*Program to explain the use of gets() function*/
#include <stdio.h>
main()
{
char n[20];
gets(n);
}
puts()
This is an output function. It is used to display a string inputted by gets() function. It is also used to
display a text (message) on the screen for program simplicity. This function appends a newline
(“\n”) character to the output.
The general syntax is as:

puts(v);

or
puts("text line");
where v is the variable of character type.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

A simple C program to illustrate the use of puts() function:


/*Program to illustrate the concept of puts() with gets() functions*/
#include <stdio.h>
main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}
The Output is as follows:
Enter the Name
Geek
Name is:
Geek
getch()
This is also an input function. This is used to read a single character from the keyboard like
getchar() function. But getchar() function is a buffered is function, getchar() function is a non-
buffered function. The character data read by this function is directly assigned to a variable rather
it goes to the memory buffer, the character data is directly assigned to a variable without the need
to press the Enter key.
Another use of this function is to maintain the output on the screen till you have not press the
Enter Key. The general syntax is as:

v = getch();

where v is the variable of character type.


A simple C program to illustrate the use of getch() function:
/*Program to explain the use of getch() function*/
#include <stdio.h>
main()
{
char n;

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

puts("Enter the Char");


n = getch();
puts("Char is :");
putchar(n);
getch();
}
The output is as follows:
Enter the Char
Char is L
getche()
All are same as getch(0 function execpt it is an echoed function. It means when you type the
character data from the keyboard it will visible on the screen. The general syntax is as:

v = getche();

where v is the variable of character type.


A simple C program to illustrate the use of getch() function:
/*Program to explain the use of getch() function*/
#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");
putchar(n);
getche();
}
The output is as follows:
Enter the Char L
Char is L
Formatted I/O functions

Formatted I/O functions which refers to an Input or Ouput data that has been arranged in a
particular format. There are mainly two formatted I/O functions discussed as follows:

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

• scanf()
• printf()
scanf()
The scanf() function is an input function. It used to read the mixed type of data from keyboard.
You can read integer, float and character data by using its control codes or format codes. The
general syntax is as:

scanf("control strings",arg1,arg2, .............. argn);

or

scanf("control strings",&v1,&v2,&v3, ................ &vn);

Where arg1,arg2,……….argn are the arguments for reading and v1,v2,v3,……..vn all are the
variables.
The scanf() format code (specifier) is as shown in the below table:
Format Code Meaning
%c To read a single character
%d To read a signed decimal integer (short)
%ld To read a signed long decimal integer
%e To read a float value exponential
%f To read a float (short0 or a single precision value
%lf To read a double precision float value
%g To read double float value
%h To read short integer
%i To read an integer (decimal, octal, hexadecimal)
%o To read an octal integer only
%x To read a hexadecimal integer only
%u To read unsigned decimal integer (used in pointer)
%s To read a string
%[..] To read a string of words from the defined range
%[^] To read string of words which are not from the defined range
Example Program:
/*Program to illustrate the use of formatted code by using the formatted scanf() function */
#include <stdio.h>
main()

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}

printf()
This ia an output function. It is used to display a text message and to display the mixed type
(int, float, char) of data on screen. The general syntax is as:

printf("control strings",&v1,&v2,&v3,................ &vn);

or

printf("Message line or text line");

Where v1,v2,v3, ......... vn all are the variables.


The control strings use some printf() format codes or format specifiers or conversion characters.
These all are discussed in the below table as:
Format Code Meaning
%c To read a single character
%s To read a string
%d To read a signed decimal integer (short)
%ld To read a signed long decimal integer
%f To read a float (short0 or a single precision value
%lf To read a double precision float value
%e To read a float value exponential
%g To read double float value
%o To read an octal integer only
%x To read a hexadecimal integer only
%u To read unsigned decimal integer (used in pointer)
Example Program:

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

/*Below the program which show the use of printf() function*/


#include <stdio.h>
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}
DECISION MAKING AND BRANCHING
C has some kinds of statements that permit the execution of a single statement, or a
block of statements, based on the value of a conditional expression or selection among
several statements based on the value of a conditional expression or a control variable.
These are all the following conditional statements
(i) if statement
(ii) if-else statement
(iii) Nested if-else statement
(iv) if-else ladder (else if ladder)
(I) IF STATEMENT:
It is otherwise known as One-way decisions. It is used to control the flow of
execution of the statements. The decision is based on a „test expression or condition’ that
evaluates to either true or false.
If the test condition is true, the corresponding statement is executed.
If the test condition is false, control goes to the next executable statement.

Syntax:
if(condition is true)
{
Statement;
}

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,a;
clrscr();
printf(“Enter 2 numbers:”);
scanf(“%d%d”,&m,&n);
if(m>n)
{
a=m;
m=n;
n=a;
}
printf(“The interchanged values are: “%d%d”,m,n);
getch();
}
Flowchart:

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

(II) IF-ELSE STATEMENT:


It is otherwise known as Two-way decisions. It is handled with if-else statements. The
decision is based on a „test expression or condition’ that evaluates to either true or false.
If the test condition is true, the true block will be executed then control goes to the next
executable statement.
If the test condition is false, the false block will be executed control goes to the next
executable statement.

Syntax:
if(condition is true)
{
True block;
}
else
{
false block;
}

Flowchart

Program:
#include<stdio.h>
main()

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

{
int a,b;
printf(“Enter two numbers:”);
scanf(“%d%d”,&a,&b);
if(a>b)
{
printf(“A is largest”);
}
else
{
printf(“B is largest”);
}
getch();
}
OUTPUT:
Enter two numbers:12 5
A is largest
(III) NESTED IF-ELSE STATEMENT
It is otherwise known as Two-way with sub-way decisions. If else statement is
enclosed within another if else structure. An if statement can be followed by an optional
else if...else statement, which is very useful to test various conditions using single if...else
if statement
Program:
#include<stdio.h>
main()
{
int a b c;
printf(“Enter the value for A, B and C:”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(a>c))

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

{
printf(“A is largest”);
}
else
{
if(b>c)
{
printf(“B is largest”);
}
else
{
printf(“C is largest”);
}
}
}
Output:
Enter the value for A,B and C:12 13 5
B is largest

Syntax:
if(condition 1)
{
if(condition 2)
{
True statement 2
}
else
{
False statement 2;
}
}

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

else
{
False statement 1;
}
Next Statement;

Flowchart

(IV) IF – ELSE LADDER


It is otherwise known as Multi-way decisions. Each and every else block will have
if statement. Last else block cannot have if block. Last else will have default statement.
Syntax

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

if(condition1)
statement 1;
else
if(condition 2)
statement 2;
else if(condition 3)

statement 3;

else
default statement;
Flowchart

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char x;

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

clrscr();
printf("Enter character: ");
scanf("%c",&x);
if(x>='a' && x<='z')
printf("Small letter");
else if(x>='A' && x<='Z')
printf("Capital letter");
else if(x>='0' && x<='9')
printf("Digit");
else
printf("Special Symbol");
getch();
}
LOOPING STATEMENTS
C LOOPS
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language.
Why use loops in C language?
The looping simplifies the complex problems into the easy ones. It enables us to alter the
flow of the program so that instead of writing the same code again and again, we can repeat the
same code for a finite number of times. For example, if we need to print the first 10 natural
numbers then, instead of using the printf statement 10 times, we can print inside a loop which runs
up to 10 iterations.
Advantage of loops in C
• It provides code reusability.
• sing loops, we do not need to write the same code again and again.
• Using loops, we can traverse over the elements of data structures (array or linkedlists).
Types of C Loops
There are three types of loops in C language that is given below:
• do while
• while
• for

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

DO WHILE LOOP IN C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the
execution of several parts of the statements. The do-while loop is mainly used in the case where
we need to execute the loop at least once. The do-while loop is mostly used in menu-driven
programs where the termination condition depends upon the end user.
do while loop syntax
The syntax of the C language do-while loop is given below:

do{
//code to be executed
}while(condition);

Example 1
#include<stdio.h>
#include<stdlib.h>
void main ()
{
char c;
int choice,dummy;
do{
printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("Hello");break;
case 2: printf("Javatpoint");break;
case 3:
exit(0);break; default:
printf("please enter valid choice");
}
printf("do you want to enter more?");
scanf("%d",&dummy);
scanf("%c",&c);
}while(c=='y');

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

}
Output
1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y

1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
n

Flowchart of do while loop

WHILE LOOP IN C
While loop is also known as a pre-tested loop. In general, a while loop allows a part ofthe
code to be executed multiple times depending upon a given Boolean condition. It can be viewed as
a repeating if statement. The while loop is mostly used in the case where the number of iterations
is not known in advance.
Syntax of while loop in C language
The syntax of while loop in c language is given below:

while(condition){
//code to be executed
}

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Flowchart of while loop in C

Example of the while loop in C language


Let's see the simple program of while loop that prints table of 1.
#include<stdio.h>
int main()
{
int i=1;
while(i<=10)
{
printf("%d \n",i);i++;
}
return 0;
}
Output

1
2
3
4
5
6
7
8
9
10

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Program to print table for the given number using whileloop in C


#include<stdio.h>
int main(){
int i=1,number=0,b=9;
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10)
{
printf("%d \n",(number*i));i++;
}
return 0;
}
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

800
900
1000

Properties of while loop

• A conditional expression is used to check the condition. The statements defined inside the
while loop will repeatedly execute until the given condition fails.
• The condition will be true if it returns 0. The condition will be false if it returnsany non-
zero number.
• In while loop, the condition expression is compulsory.
• Running a while loop without a body is possible.
• We can have more than one conditional expression in while loop.
• If the loop body contains only one statement, then the braces are optional.
Example 1
#include<stdio.h>
void main ()
{
int j = 1;
while(j+=2,j<=10)
{
printf("%d ",j);
}
printf("%d",j);
}
Output
3 5 7 9 11

Infinitive while loop in C


If the expression passed in while loop results in any non-zero value then the loop willrun
the infinite number of times.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

while(1){
//statement
}

FOR LOOP IN C
The for loop in C language is used to iterate the statements or a part of the programseveral
times. It is frequently used to traverse the data structures like the array and linked list.
Syntax of for loop in C
The syntax of for loop in c language is given below:

for(initialization; condition; increment/decrement)


{
Statement; //code to be executed
}

Flowchart of for loop in C

C for loop Examples


Let's see the simple program of for loop that prints table of 1.
#include<stdio.h>
int main()
{
int i=0;

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

for(i=1;i<=10;i++)
{
printf("%d \n",i);
}
return 0;
}
Output

1
2
3
4
5
6
7
8
9
10

NESTED LOOPS IN C
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping
of statements inside another loop. Let's observe an example of nesting loops inC.
Any number of loops can be defined inside another loop, i.e., there is no restriction for
defining any number of loops. The nesting level can be defined at n times. You can define any
type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
Syntax of Nested loop

Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}

Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while'

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

loop.
Nested for loop
The nested for loop means any type of loop which is defined inside the 'for' loop.
for (initialization; condition; update)
{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}

Example of nested for loop


#include <stdio.h>
int main()
{
int n;// variable declaration printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}

Explanation of the above code


• First, the 'i' variable is initialized to 1 and then program control passes to thei<=n.
• The program control checks whether the condition 'i<=n' is true or not.
• If the condition is true, then the program control passes to the inner loop.
• The inner loop will get executed until the condition is true.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

• After the execution of the inner loop, the control moves back to the update ofthe outer loop,
i.e., i++.
• After incrementing the value of the loop counter, the condition is checked again,i.e., i<=n.
• If the condition is true, then the inner loop will be executed again.
• This process will continue until the condition of the outer loop is true.
Output:

Nested while loop


The nested while loop means any type of loop which is defined inside the 'while' loop.
while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}

Example of nested while loop


#include <stdio.h>
int main()
{
int rows; // variable declaration
int columns; // variable declaration
int k=1; // variable initialization

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

printf("Enter the number of rows :"); // input the number of rows.


scanf("%d",&rows);
printf("\nEnter the number of columns :"); // input the number of columns.
scanf("%d",&columns);
int a[rows][columns]; //2d array declaration
int i=1;
while(i<=rows) // outer loop
{
int j=1;
while(j<=columns) // inner loop
{
printf("%d\t",k); // printing the value of k.
k++; // increment counter
j++;
}
i++;
printf("\n");
}
Explanation of the above code.
• We have created the 2d array, i.e., int a[rows][columns].
• The program initializes the 'i' variable by 1.
• Now, control moves to the while loop, and this loop checks whether the condition is true,
then the program control moves to the inner loop.
• After the execution of the inner loop, the control moves to the update of theouter loop, i.e.,
i++.
• After incrementing the value of 'i', the condition (i<=rows) is checked.
• If the condition is true, the control then again moves to the inner loop.
• This process continues until the condition of the outer loop is true.
Output:

Department of CSErmation Technology. SMVEC


U23CSTC01–Programming In C Regulation 2023

Nested do..while loop


The nested do..while loop means any type of loop which is defined inside the 'do..while'loop.
Do
{
do
{
// inner loop statements.
}while(condition);
// outer loop statements.
}while(condition);

Example of nested do..while loop.


#include <stdio.h>
int main()
{
/*printing the pattern
********
********
********
******** */
int i=1;
do // outer loop
{
int j=1;
do // inner loop
{
printf("*");j++;
}while(j<=8);
printf("\n");i++;
}while(i<=4);
}

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Output:

Explanation of the above code.


• First, we initialize the outer loop counter variable, i.e., 'i' by 1.
• As we know that the do..while loop executes once without checking the condition, so the
inner loop is executed without checking the condition in theouter loop.
• After the execution of the inner loop, the control moves to the update of the i++.
• When the loop counter value is incremented, the condition is checked. If thecondition in the
outer loop is true, then the inner loop is executed.
• This process will continue until the condition in the outer loop is true.
SWITCH STATEMENT
Switch case statement evaluates a given expression and based on the evaluated value
(matching a certain condition), it executes the statements associated with it. Basically, it is used to
perform different actions based on different conditions (cases).
• Switch case statements follow a selection-control mechanism and allow a value to
change control of execution.
• They are a substitute for long if statements that compare a variable to several integral
values.
• The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
In C, the switch case statement is used for executing one condition from multiple conditions. It is
similar to an if-else-if ladder.
The switch statement consists of conditional-based cases and a default case.

Syntax of switch Statement in C

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

Flow chart

Rules of the switch case statement


1. In a switch statement, the “case value” must be of “char” and “int” type.
2. There can be one or n number of cases.
3. The values in the case must be unique.
4. Each statement of the case can have a break statement. It is optional.

Department of CSE. SMVEC


U23CSTC01–Programming In C Regulation 2023

5. The default statement is also optional.


Example :
C code to create a simple calculator
#include <stdio.h>
int main()
{
char Operator;
float num1, num2, result = 0;
printf("Enter any one operator like +, -, *, / : ");
scanf("%c", &Operator);
printf("Enter the values of Operands num1 and num2 : ");
scanf("%f%f", &num1, &num2);
switch(Operator)
{
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
break;
default: printf("Invalid Operator ");
}
printf("The value = %f", result);
return 0;
}
Output
Enter any one operator: +
Enter values of Operands num1 and num2:
23
45
The value = 68.000000

Department of CSE. SMVEC

You might also like