0% found this document useful (0 votes)
17 views47 pages

Unit 1

Uploaded by

Bhuvi cse 1998
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)
17 views47 pages

Unit 1

Uploaded by

Bhuvi cse 1998
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
You are on page 1/ 47

UNIT I BASICS OF C PROGRAMMING

Introduction to programming paradigms - Application of C Language - Structure of C


program - C programming: Data Types – Constants – Enumeration Constants -
Keywords – Operators: Precedence and Associativity - Expressions - Input/Output
statements, Assignment statements – Decision making statements - Switch statement
- Looping statements – Pre-processor directives - Compilation process.

History of C language:

C is one of the most popular programming languages.


It is structured programming language.
It was developed by Dennis Ritchie at AT & T's Bell Laboratories at USA in 1972.

FEATURES AND APPLICATIONS OF C LANGUAGE:


1. "C" is a general purpose, structured programming language.
2. C is powerful, efficient, compact, portable and flexible.
3. 'C' is well suited for writing system software as well as application software.
4. C program can be run on different operating systems.
5. "C' is a middle level language. i e, it supports both the features of low level and
high level language
6. C has got rich set of operators
Characteristics of C language:
1. Structured programming language
2. High level programming language allows programmer to concentrate on problem
3. Facilitates low level language. 4. Extensive use of function calls
5. Core language other language are based on "C".
6. Supports pointers to refer computer memory, array, structure and functions.
7. 32 keywords.
Advantages of 'C':
1. Used for system programming and application programming.
2. Portable and efficient.
3. Used to implement end user applications.
4. Compilers, libraries and interpreter of other language are implemented in C.
1.1 PROGRAMMING PARADIGMS

A programming paradigm is a fundamental style of programming that defines how


the structure and basic elements of a computer program will be built. They are
classified as follows:
 Monolithic programming-emphasizes on finding a solution
 Procedural programming-lays stress on algorithms
 Structured programming- -focuses on modules
 Object-oriented programming-emphasizes on classes and objects
 Logic-oriented programming --focuses on goals usually expressed in predicate
calculus.
 Rule-oriented programming makes use of 'if-then-else' rules for computation
 Contraint-oriented programming-utilizes invariant relationships to solve a
problem
i) Monolithic Programming

 Monolithic programs have only one program module. It does not support the
concept of subroutines.
 The global data can be accessed and modified from any part of the program
Ex: BASIC
Drawbacks:

 Used only for very small and simple applications where reusability is not a
concern
 Difficult to debug
 program sure is large
ii) Procedural Programming
 A program is divided into subroutines that can access global data.
 To avoid repetition of code, subroutine can be called when needed.

Ex. FORTRAN and COBOL


Advantages
 The only goal is to write correct programs.
 Programs are easier to write as compared to monolithic programming.
Disadvantages
 No concept of reusability.
 Requires more time and effort to write programs.
 Programs are difficult to maintain.
 Global data is shared and therefore may get altered.
iii) Structured Programming
 Also referred to as modular programming Used in large programs that require
large development team to develop different parts of the same program.
 Employs a top-down approach in which the overall program structure is broken
down into separate modules.

Ex: C, Pascal
Advantages:
 Modularization makes it easier to write, debug and understand the program
 Supports reusability.
 Individual procedures are easy to change as well as understand
Disadvantages:
 Not data centred
 Main focus is on functions.
iv) Object oriented programming:
 It treats data as a critical element in the program development and restricts its
flow freely around the system.
 It is a data and task based.

Ex: C++, JAVA


Features of OOP:
 programs are data centred
 programs are divided into objects.
 Functions that operate on data are tied together with the data.
 Data is hidden
 Follow bottom-up approach
 Supports extendibility
1.2 Applications of C Language
C is regarded as one of the oldest and fundamental languages widely used all over the
world.
Some important applications of C language might be in the development of:
1. Operating systems
The first operating system to be developed using a high-level programming language
was UNIX, which was designed in the C programming language. Later on, Microsoft
Windows and various Android applications were scripted in C.

2. Web Browsers
Google file system and Google chromium browser were developed using C/C++. Not
only this, the Google Open Source community has a large number of projects being
handled using C/C++. Since Mozilla Firefox and Thunderbird were open-source
email client projects, they were written in C/C++.

3. Microcontrollers
C language is used in system programming which replaces the need of assembly
language. The compiler of C directly converts into machine language.

4.Scientific systems
C language is used in building and creating many scientific systems. It is the parent
language for advanced languages.

5. Assemblers
Assemblers executing machine-level hardware-specific systems are created
using C language.

6. Text Editors
No language create better text editor other than C language

7. Print spoolers
The software program which is responsible for sending the jobs to the printer once the
command is given is created with the help of the C programming language.

8. Network Drivers
The network drivers responsible for accessing the internet and running the WIFI and
other kinds of drivers are all written in C language

9. Modern Programs
Various modern programs whose major requirement is to consume less memory and
need hardware communication are written in the C programming language.

10. Databases
There are many databases that are required to store a huge amount of data in them and
thus are written in C language. MySQL, again being an open source project, used in
Database Management Systems was written in C/C++.

11. Language interpreters


The various language interpreters responsible for changing the language type from a
high level to a machine level language is written in C language.

12. Utilities
Various and program system-specific utilities are written in C language.

13. Gaming and Animation


Since the C programming language is relatively faster than Java or Python, as it is
compiler-based, it finds several applications in the gaming sector. Games coded in C
such as Tic-Tac-Toe, The Dino game, Snake game and many more.

1.3 Structure of C program


A C program contains one or more functions, where a function is defined as a group
of statements that perform a well-defined task.
Documentation section

The documentation section consists of a set of comment lines giving the name of
program, the author and other details.

Preprocessor directives:

 It contains special instructions that indicate how to prepare the program for
compilation.

 Preprocessor commands like 'include' tells the compiler that some information
needed from the specified header file.

Example: #include<stdio.h>

Global declaration section:

 The variables are declared outside the main() function and are visible through
program are called global variables.

 Every 'C' program must have one main() function, where the execution begins.

 Functions are divided into 2 parts-declaration section and statement section.

Local declaration section:


 This part is used to declare all the variables that are used in the statement section
of the program and these are called local variables.

Statement section:

 It contains atleast one valid "C" statement.

 Execution of a program begins with opening brace ‘{’and ends with closing ‘}’.

 The closing brace of the main function is the logical end of the program.

 All the statements in the program ends with a semicolon(;) except conditional
and control statements.

 Example:
#include<stdio.h> //header file
int main() //execution begins
{
printf ("Welcome"); //statement
return 0; //return value to the function
}
1.4 C Programming : Data Types
Data type determines the set of values that a data item can take and the operations
that can be performed on the item.
TYPES DATA TYPES
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Userdefined Data Type enum

C language provides four basic data types.


Lists the data types, their size, range, and usage for a C programmer.

Basic Data Types in C


Basic datatypes are integer based and floating point based. C language supports both
signed and unsigned literals.

Basic data types and their variants


1.4.1 Storage classes
Storage classes of a variable determine:
1. Storage area of the variable
2. Initial value of variable if not initialized
3. Lifetime of the variable
4. Linkage of a function or variable

C language provides 4 storage class specifiers:


1. auto
2. register
3. static
4. extern
Syntax:
storageclassspecifier datatype variable name;

1. The auto storage class


 Automatic variables are also called as auto variables, which are defined inside
a function.
 Auto variables are stored in main memory.
 Variables has automatic (local) lifetime.
 Auto variables are not implicitly initialized.
 Auto variables have no linkage.
 It is a default storage class if the variable is declared inside the block.

Syntax:
storageclasstype datatype var1,var2….varn;

Example:
#include<stdio.h>
{
auto int a=10;
printf(“a=%d”,a);
{
int b=20;
printf(“b=%d”,b);
}
printf(“Here b is not visible\n”);
printf(“a=%d”,a);
}
OUTPUT:
a=10
b=20
Here b is not visible
a=10

2. The register storage class


 Register variables can be accessed faster than others
 Variables are stored in CPU.
 Variables have automatic (local) lifetime.
 Register variables are not implicitly initialized.
 Register variables have no linkage.
 Register variables are used for loop counter to improve the performance of a
program.
Syntax:
storageclasstype datatype var1,var2….varn;
Example:
#include<stdio.h>
void main()
{
register int a=200;
printf(“a=%d”,a);
}
OUTPUT:
a=200
3. The static storage class
 Static variables have static (global) lifetime.
 Static variables are stored in the main memory.
 Static variables can be declared in local scope as well as in the global scope.
 Static variables are implicitly initialized.
 The value of static variables persists between the function calls. Last change
made in the value of static variable remains throughout the program execution.

 Static variables will have internal linkage.


Syntax:
storageclasstype datatype var1,var2….varn;
Example:
#include<stdio.h>
void fun(int);
void main()
{
int i=0;
for(i=0;i<5;i++)
{
fun(i);
}
}
void fun(int i)
{
static int a=10;
a++;
printf(“%d”,a);
}
OUTPUT:
11 12 13 14 15
4. The extern storage class
 Variables that are available to all functions are called external or global
variables.
 External variables are stored in main memory.
 External variables have static (global) lifetime.
 External variables have external linkage.
 External variables are implicitly initialized to 0.
Syntax:
storageclasstype datatype var1,var2….varn;
Example:
extern int v=10;
void call1()
void main()
{
call1();
printf(“In main v=%d”,v);
}
void call1()
{
printf(“In call1() v=%d”,v);
}
OUTPUT:
In main v=10
In call1( ) v=10
Since v is a external variable it is visible and accessed in all functions.
The typedef storage class typedef is used for
creating an alias or synonym for a known type.
Syntax:

typedef known type synonym name;

Summary of storage classes


S.No Storage Storage Initial Lifetime Linkage
class value

1 auto Memory Garbage Automatic NO


2 register CPU register Garbage Automatic NO
3 static Memory 0 Static Internal
4 extern Memory 0 Static External
1.4.2 Constants
A constant is an entity whose value cannot be changed during the execution of a
program.
Syntax: const datatype identifier=value;
Constants are classified as:
1. Literal constants
2. Qualified constants
3. Symbolic constants
1.Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating
point number, character or a string.
Literal constants are of the following types.
1. Integer Literal constant
2. Floating point Literal constant
3. Character Literal constant
4. String Literal constant
Integer Literal constant
Integer Literal constants are integer values like -1, 2, 8 etc.
Eg: const int M=95;
The rules for writing integer literal constant are:
• An Integer Literal constant must have at least one digit.
• It should not have any decimal point.
• It can be either positive or negative.
• No special characters and blank spaces are allowed.
Floating point Literal constant
Floating point Literal constants are values like -23.1, 12.8 etc.. It can be written in a
fractional form or in an exponential form.
Eg: const float distance=126.5;
The rules for writing Floating point Literal constants in a fractional form:
• A fractional floating point Literal constant must have at least one digit.
• It should have a decimal point.
• It can be either positive or negative.
• No special characters and blank spaces are allowed.
Character Literal constant
A Character Literal constant can have one or at most two characters enclosed within
single quotes.
Eg: const char c=’s’;
It is classified into:
 Printable character literal constant
 Non-Printable character literal constant.
Printable character literal constant
All characters except quotation mark, backslash and new line characters enclosed
within single quotes form a Printable character literal constant.
Non-Printable character literal
Non-Printable character literal constants are represented with the help of escape
sequences. An escape sequence consists of a backward slash (i.e. \) followed by a
character and both enclosed within single quotes.

String Literal constant


A String Literal constant consist of a sequence of characters enclosed within double
quotes. Each string literal constant is implicitly terminated by a null character.
E.g. const char c[10]=“Hello” ;
2. Qualified constants:
Qualified constants are created by using const qualifier.
E.g. const char a = “A”
The usage of const qualifier places a lock on the variable after placing the value in it.
So we cannot change the value of the variable a.
3. Symbolic constants
Symbolic constants are created with the help of the define preprocessor directive.
For ex: #define PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each
symbolic constant is replaced by its actual value during the pre-processing stage.
1.4.3 Enumeration constants:
• Enumeration is user defined data type, enum, used to assign names to
integral constants which makes a program easy to read and maintain.
• First object is initialized to 0 and automatically incremented by 1.
Syntax:
enum typename {list of objects};
Example:
#include<stdio.h>
main()
{
enum Day{Monday=1, Tuesday, Wednesday, Thursday};
printf(“%d\n”,Thursday);
}
OUTPUT:
4
1.4.4. Keywords
Keyword is a reserved word that has a particular meaning in the programming
language. The meaning of a keyword is predefined. It can‟t be used as an identifier.

1.5 Operators:
Operator
An operator is a symbol that is used to perform specific mathematical or logical
manipulations.
For e.g, a=2+3
Here = , + are the operators
Operands
An operand specifies an entity on which an operation is to be performed. It can be a
variable name, a constant, a function call.
Eg: a=2+3
Here a, 2, 3 are operands
Classification of Operators
The operators in C are classified on the basis of
1) The number of operands on which an operator operates
2) The role of an operator
Classification based on Number of Operands
Types:
1. Unary Operator: A unary operator operates on only one operand. Some of
the unary operators are,
Operator Meaning
- Minus
++ Increment
-- Decrement
& Address- of operator
sizeof sizeof operator

Unary Minus:
An operand is proceeded by a minus sign, the unary operator negates its value.
Ex:
int a,b=10;
a=-b;
printf(“%d”,a);
Output: -10
Increment operator and Decrement operator
++ and -- are increment and decrement operator.
Pre increment or Pre decrement: First the value is either incremented or
decremented before performing the operation.
Post increment or Post decrement: First do the operation then incremented or
decrement the value.
Operator Meaning Example A=5
++a Pre increment printf(“A=%d”,++a) A=6
--a Pre decrement printf(“A=%d”,--a) A=5
a++ Post increment printf(“A=%d”,a++) A=5
a-- Post decrement printf(“A=%d”,a--) A=6

2. Binary Operator: A binary operator operates on two operands. Some of the


binary operators are,
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
Division
&& Logical AND

3. Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is the ternary
operator.

Classification based on role of operands :


Types of operators:
1. Arithmetic Operators
2. Relational Operators
3. Equality operators
4. Logical Operators
5. Bitwise Operators
6. Assignment Operators
7. Miscellaneous Operators
1. Arithmetic Operators
They are used to perform arithmetic operations like addition, subtraction,
multiplication, division etc.
OPERATORS MEANING EXAMPLE A=9, B=5 Description
+ Addition c=a+b c=14 Adds two
operands
- Subtraction c=a-b c=4 Subtracts
second
operand from
the first
* Multiplication c=a*b c=45 Multiplies both
operands
/ Division c=a/b c=1 The division
operator is
used to find
the quotient.
% Modulo c=a%b c=4 Modulus
operator is
used to find
the remainder

Example: Arithmetic Operator


#include<stdio.h>
void main()
{
int a,b,c;
printf(“\nEnter the A&B Value:”);
scanf(“%d%d”,&a, &b);
c=a+b;
printf(“\nAddition=%d”, c);
}
OUTPUT:
Enter the A&B
Value: 9 5
Addition: 14

2) Relational operators:

 It is also called as comparison operator.


 Relational operators are used to compare two operands. There are 6 relational
operators in C, they are
Operator Meaning of Operator Example
== Equal to 5==3 returns false (0)
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)

 Relational operators return true or false value, depends on the relationship


between the two operands.
 The value of relational expression is either one or zero
 If the relation is true, it returns value 1 and if the relation is false, it
returns value 0.
 An expression that involves a relational operator is called as a
condition. For e.g a<b is a condition.
 Relational operators are used in decision making process
Example: //Program to find biggest of 2 numbers
#include<stdio.h>
#include conio.h>
void main()
{
int a,b;
printf("\n Enter the values of a & b:");
scanf("%d %d",&a,&b);
if(a>b)
printf("a is biggest number");
else
printf( "b is biggest number");
}
OUTPUT:
Enter the values of a &b:
5 3
a is biggest number
3.Equality operators
 Equality operators is used to compare their operands for equality or inequality.
 == and != operators.
Operators Meaning
== Returns if both operands are equal, 0
otherwise.
!= Returns 1 if operands do not have the
same value, 0 otherwise.

4.Logical operators:
 Logical operators are used to perform more than one condition at a time and
combine the results of two or more conditions.
 Logical operators are used to logically relate the sub-expressions. There are 3
logical operators in C, they are
 If the relation is true, it returns value 1 and if the relation is false, it returns value
0.
Operator Meaning of
Operator Example A=9,B=5,C=2 Description

&& Logial AND d=(a>b)&&(a>c) d=1 It returns true


when both
conditions are
true
|| Logical OR d=(a>b)||(a>c) d=1 It returns true
when at-least
one of the
condition is
true
! Logical NOT d=!(a>=b) d=0 It reverses the
state of the
operand

Truth tables of logical operations


condition 1 condition 2 NOT X X AND Y X OR Y

(e.g., X) (e.g., Y) (~X) ( X && Y ) ( X || Y )

False false true false false

False true true false true

true false false false true

true true false true true


5.Bitwise Operators
 C language provides 6 operators for bit manipulation.
 Bitwise operator operates on the individual bits of the operands. They are used
for bit manipulation.

Operators Meaning of operators


& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Truth tables
p Q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

E.g.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)

3 << 2 (Shift Left)


0011
1100=12

3 >> 1 (Shift Right)


0011
0001=1
6.Assignment Operators
To assign a value to the variable assignment operator is used.

Operators Example Explanation

Simple assignment operator = sum=10 10 is assigned to variable sum

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


operators
-= sum-=10 sum = sum-10
Or
*= sum*=10 sum = sum*10
Shorthand assignment operators
/+ sum/=10 sum = sum/10

%= sum = sum%10
sum%=10
&= sum = sum&10
sum&=10
^= sum^=10 sum = sum^10

Syntax: variable=expression(or)value;
E.g.
var=5 //5 is assigned to var
a=c; //value of c is assigned to a
7.Miscellaneous Operators
Other operators available in C are
a. Function Call Operator(i.e. ( ) )
b. Array subscript Operator(i.e [ ])
c. Member Select Operator
i. Direct member access operator (i.e. . dot operator)
ii. Indirect member access operator (i.e. -> arrow operator)
d. Conditional operator (?:)
e. Comma operator (,)
f. sizeof operator
g. Address-of operator (&)
a) Comma operator
 It is used to seperate the statement elements such as variables, constants or
expression etc.
E.g. int a=2,b=3,x=0;
b) sizeof Operator
 It is unary operator,that returns the size of its operand in bytes.
 It is a compile time operator.
 Example : sizeof(char) will give us 1.
sizeof(a), where a is integer, will return 2.
c) Conditional Operator
 It is the only ternary operator available in C.
 Conditional operator takes three operands and consists of two symbols ? and : .
 Conditional operators are used for decision making in C.
Syntax :
(Condition?true_value:false_value);
For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c
will be -10.
d) Address-of Operator
It is used to find the address of a data object.
Syntax : &operand
E.g. &a will give address of a.
1.6. Precedence and Associativity
Precedence of operators
 The precedence rule is used to determine the order of application of operators in
evaluating sub expressions.
 Each operator in C has a precedence associated with it.
 The operator with the highest precedence is operated first.
Associativity of operators
 The associativity rule is applied when two or more operators are having same
precedence in the sub expression.
 An operator can be left-to-right associative or right-to-left associative.
Category Operators Associativity Precedence

Unary +, -, !, ~, ++, - -, &, sizeof Right to left Level-1

Multiplicative *, /, % Left to right Level-2


Additive +, - Left to right Level-3

Shift << , >> Left to right Level-4


Relational <, <=, >, >= Left to right Level-5

Rules for evaluation of expression


• First parenthesized sub expressions are evaluated first.
• If parentheses are nested, the evaluation begins with the innermost sub expression.
• The precedence rule is applied to determine the order of application of operators in
evaluating sub expressions.
• The associativity rule is applied when two or more operators are having same
precedence in the sub expression.

1.7 Expressions in C
An expression is a combination of variables, constants and operators. Every
expression is evaluated to a value.
i.e., every expression results in some value of certain type that is assigned to a
variable.
Some examples of C expressions are given below.

Algebric Expression C Expression


axb-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
(ab/c) a*b/c
3x2+2x+1 3*x*x+2*x+1
(x/y)+c x/y+c

Expressions are evaluated using an assignment statement of the form


Variable=Expression;
Example of evaluation statements are
x=a*b-c
y=b/c*a
z=a-b/c+d;
1.8 Input/Output statements
Streams:
Streams provide communication channels between files and programs.
 The standard input is read data from the
keyboard.
 The standard output to print data on the screen.
 The standard error.
2 Types:
Text stream and Binary stream

Streams

Text stream Binary stream

Text stream: Sequence of characters is divided into lines with each line being
terminated with a new line character(\n).
Binary stream: Contains data values using their memory representation.
Input and Output streams in C:

Keyboard Input text stream Data

Keyboard Output text Data


stream

The I/O functions are classified into two types:


 Formatted Functions
 Unformatted functions

Input and Output functions

Formatted Functions Unformatted Functions

printf() getch()
getche()
getchar()
scanf()
gets()
putch()
putchar()
puts()

1.8.1 Formatted Functions:


Formatted Input/Output Statements:
C language supports 2 formatting functions scanf and printf.
1. scanf() function:
 scanf is used to convert the text stream from the keyboard to data values and
stores them in program variables.
 Used to read formatted data from the keyboard.
 scanf function takes a text stream from the keyboard, extracts and formats data
from the streams according to a format control string and then stores the data in
specified variable.
Syntax:
scanf(“control string”,&var1, &var2,……..&varn);
Example:
int n;
scanf(“”, &n); //reads integer data
Control string:
 Specifies the the type and format of the data obtained from the keyboard and
stored in the memory locations pointed by arguments ie., the addresses where
data are to be stored.
Format code Meaning
%c Single character
%d integer
%s Strings
%f Float values
%1d Long integers

Rules for writing scanf() function:


 The control string must be preceded with % sign and must be within quotations.
 If there is a more than one input data items, items must be separated by commas
and must be preceded with & sign except for string input.
 The control string and the variables should match with each other.
 It must be terminated with semicolon.
 An error would be generated if the format string is ended with a white space
character.
2. printf() function:
 printf is used to convert data stored in the program into a text stream for output
to the monitor.
 Used to display information required by the user and also prints the values of the
variables.
Syntax:
printf("control string", var1, var2,............var n);

Rules for writing printf() function:

The variable must be separated by commas, and need not be preceded with &
sign.
The control string and the variables must match in their order.
The control string must be in quotations.
Print special messages wherever required in output.
1.8.2 Unformatted Functions:
They are used when I/P & O/P is not required in a specific format.
C has 3 types I/O functions.
a) Character I/O
b) String I/O
c) File I/O
a) Character I/O:
1. getchar() This function reads a single character data from the standard input.
(E.g. Keyboard)
Syntax :
variable_name=getchar();
Eg:
char c;
c=getchar();
2. putchar() This function prints one character on the screen at a time.
Syntax :
putchar(variable name);
Eg.
char c=”C”;
putchar(c);
3. getch() and getche() : getch() accepts only a single character from keyboard. The
character entered through getch() is not displayed in the screen (monitor).
Syntax
variable_name = getch();
4. putch(): putch displays any alphanumeric characters to the standard output device.
It displays only one character at a time.
Syntax

putch(variable_name);

b) String I/O
1.gets() – This function is used for accepting any string through standard input
(keyboard) until enter key is pressed.
Syntax:
gets(variable_name);
2. puts() – This function prints the string or character array.
Syntax

puts(variable_name);

3. cgets()- This function reads string from the console.


Syntax
cgets(char *st);
It requires character pointer as an argument.
4. cputs()- This function displays string on the console.
Syntax
cputs(char *st);

1.9 ASSIGNMENT STATEMENTS

Statements can be defined as set of declaration or sequence of action


 It causes the computer to perform some action.
 Assignment operator used for assigning values to the variables.

Syntax: variable=expression:

Example:

int a=3; // value


a=a+2; // expression

1.10 CONTROL STATEMENTS OR CONTROL STRUCTURES

Programmers can take decisions in their program with the help of control statements.
The types of control statements are,

1. Sequence (or) Linear Structure


2. Decision making (or) selection (or) Branching Structure 3. Looping (or) Iteration
Structure
4. Unconditional Structure
S.No Structure Name Types
1. Sequence (or) linear Reading the statements one
structure by one is called sequence or
linear structure. It
represents the normal flow
of the program.
2. Decision making (or) 1. Simple if
selection (or) branching
2. If…….else
structure
3. Nested if…….else
4. If…….else ladder
5. Switch case
6. Nested switch case
3. Looping (or) Iteration 1. While
structure
2. do-while
3. For
4. Nested for
4. Unconditional Structure 1. break
2. continue
3. goto
4. return

1.11 Decision making statements


Decision making statements in a programming language help the programmer to
transfer the control from one part to other part of the program.

Flow of control: The order in which the program statements are executed is known as
flow of control. By default, statements in a c program are executed in a sequential
order
Branching statements
Branching statements are used to transfer program control from one point to another.
2 types
a) Conditional Branching:- Program control is transferred from one point to
another based on the result of some condition
Eg) if, if-else, switch
b) Unconditional Branching:- Program control is transferred from one point to
another without checking any condition
Eg) goto, break, continue, return

a) Conditional Branching : Selection statements


Statements available in c are
 The if statement
 The if-else statement
 The switch case statement
(i)The if statement
C uses the keyword if to execute a statement or set of statements when the logical
condition is true.
Syntax:

Test
if (test expression)
expres
Statement; F

Statement

• If test expression evaluates to true, the corresponding statement is


executed.
• If the test expression evaluates to false, control goes to next executable
statement.
• The statement can be single statement or a block of statements. Block
of statements must be enclosed in curly braces.

Example : //Eligibility to vote


#include<stdio.h>
void main()
{
int age;
printf(“Enter your age: ”);
scanf(“%d”, &age);
if(age>=18)
printf(“Eligible to vote ”);
}
Output:
Enter your age: 20
Eligible to vote

(ii)The if-else statement


It is two way decision making statement.

Syntax:

if (test expression)
Test
Statement T;
expres
else sion
Statement F;

Statement Statement
F

• If the test expression is true, statementT will be executed.


• If the test expression is false, statementF will be executed.
• Statement T and Statement F can be a single or block of statements.
Example Program 1: //Biggest of 2 Numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter the values of a,b : ”);
scanf(“%d%d”, &a,&b);
if(a>b)
printf(“a is biggest number ”);
else
printf(“a is biggest number ”);
getch();
}
Output:
Enter the values of a,b: 5 3
a is biggest number

iii) Nested if statement


if..else statement can be used inside another if..else statement. This is called nesting
in computer programming.

Syntax:
if(outer test condition)
{
if(inner test condition)
{
True statement 1;
}
else
{
False statement 2;
}
else
{
False statement (3);
}
}
FLOWCHART:

Test
expre1

Test
exp 2
Stmtblock1

Stmtblock2 Stmtblock3

Stmt Y

Example:
#include<stdio.h>
void main()
{
int a,b,c;
printf(“Enter 3 numbers…”);
scanf(“%d%d%d”, &a, &b, &c);
if(a>b)
{
if(a>c)
{
printf(“a is the greatest”);
}
else
{
printf(“c is the greatest”);
}
}
else
{
if(b>c)
{
printf(“b is the greatest”);
}
else
{
printf(“c is the greatest”);
}
}
}
Execution:
Input:
Enter 3 numbers…56,89,23
Output:
b is the greatest
v) Switch statement
• It is a multi way branch statement.
• It provides an easy & organized way to select among multiple operations
depending upon some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets
executed.
4. If no match occurs, then all the statements after the default statement get executed.
• Switch ,case, break and default are keywords
• Break statement is used to exit from the current case structure
Flowchart

case: statement break


constant 0

case :
constant 1 statement break

default statement break

switch(expression) End of switch

Syntax

switch(expression)
{ case value 1:

program statement;
program statement;
……
break;
case value 2:

program statement;
Program statement;
……
break;
… case value n:
program statement;
program statement;
……
break;
default: program statement;
program statement;

Example:
#include<stdio.h>
void main(){
int n;
printf(“Enter any number (1 to 7)”);
scanf(“%d”, &n);
switch(n)
{
case 1:
printf(“Today is Monday”);
break;
case 2:
printf(“Today is Tuesday”);
break;
case 3:
printf(“Today is Wednesday”);
break;
case 4:
printf(“Today is Thursday”);
break;
case 5:
printf(“Today is Friday”);
break;
case 6:
printf(“Today is Saturday”);
break;
case 7:
printf(“Today is Sunday”);
break;
default:
printf(“Wrong number entered”);
}}}
Execution:
Input:
Enter any number (1 to 7): 5
Output:
Today is Friday
b)Unconditional branching statements
i)The goto Statement
This statement does not require any condition. Here program control is transferred to
another part of the program without testing any condition.

Syntax:

goto label;

 label is the position where the control is to be transferred.


Example:
#include<stdio.h>
void main()
{
int i;
for(i=1; i<=10; i++)
{
printf(“hello\t”);
if(i==5)
goto L1;
}
printf(“\nYou came out of loop”);
L1:
printf(“\nThis is the Label statement”);
}
Execution:
Output:
hello hello hello hello hello
This is the Label statement
ii)break statement
• A break statement can appear only inside a body of , a switch or a loop
• A break statement terminates the execution of the nearest enclosing loop or
switch.
Syntax:
break;
Example:
#include<stdio.h>
void main()
{
int i;
for(i=1; i<=10; i++)
{
if(i==5)
break;
printf(“hello\t”);
}
printf(“\nYou came out of loop”);
}
Execution:
Output:
hello hello hello hello hello
You came out of loop
iii) continue statement:
• A continue statement can appear only inside a loop.
• A continue statement terminates the current iteration of the nearest
enclosing loop.
Syntax:

continue;
Example:
#include<stdio.h>
void main()
{
int i;
for(i=1; i<=10; i++)
{
printf(“hello\t”);
if(i==5)
continue;
}
printf(“\nYou came out of loop”);
}
Execution:
Output:
hello hello hello hello hello hello hello hello hello
You came out of loop
iv)return statement:
A return statement terminates the execution of a function and returns the control to
the calling function.

Syntax:
return; (or) return expression;
Difference between break and continue statement:
break continue
break statement takes the control to the continue statement takes the control to
outside of the loop. the beginning of the loop.
It is used in switch statements. It is used in loop statements.
Always associated with if condition in This is also associated with if condition.
loops.

1.12 Looping statements


Iteration is a process of repeating the same set of statements again and again until the
condition holds true.
Iteration or Looping statements in C are:
1.for
2.while
3.do while Loops are classified as
 Counter controlled loops
 Sentinel controlled loops
Counter controlled loops
• The number of iterations is known in advance. They use a control variable
called loop counter.
• Also called as definite repetitions loop.
• E.g: for
Sentinel controlled loops
• The number of iterations is not known in advance. The execution or
termination of the loop depends upon a special value called sentinel value.
• Also called as indefinite repetitions loop.
• E.g: while
1. for loop
It is the most popular looping statement.
Syntax:

for(initialization; condition test; increment/update or decrement)


{
Statements;
}

There are three sections in for loop.


a. Initialization section – gives initial value to the loop
counter.
b. Condition section – tests the value of loop counter to
decide whether to execute the loop or not.
c. Manipulation section - manipulates the value of loop
counter.
Example:
for(a=5; a<=10; a++)

Initialization

Condition

Increment(++) (or) Decrement(--)


Execution of for loop
1. Initialization section is executed only once.
2. Condition is evaluated
a. If it is true, loop body is executed.
b. If it is false, loop is terminated
3. After the execution of loop, the manipulation expression is evaluated.
4. Steps 2 & 3 are repeated until step 2 condition becomes false.
Example:
#include<stdio.h>
void main()
{
int i;
for(i=1; i<=3; i++)
{
printf(“%d\t”, i);
}
}
Execution:
Output:
1 2 3
2. while statement
 They are also known as Entry controlled loops because here the condition is
checked before the execution of loop body.
Syntax:
while (expression)
{
statements; }

Execution of while loop


a. Condition in while is evaluated
i. If it is true, body of the loop is executed.
ii. If it is false, loop is terminated
b. After executing the while body, program control returns back to while header.
c. Steps a & b are repeated until condition evaluates to false.
d. Always remember to initialize the loop counter before while and manipulate
loop counter inside the body of while.
Example:
#include<stdio.h>
void main()
{
int i=3;
while(i<10)
{
printf(“%d\t”, i);
i++
}
}
Execution:
Output:
3456789
3. do while statement
• They are also known as Exit controlled loops because here the condition is
checked after the execution of loop body.
Syntax:
do
{
statements;
}
while(expression);

Execution of do while loop


a. Body of do-while is executed.
b. After execution of do-while body, do-while condition is evaluated
i. If it is true, loop body is executed again and step b is repeated.
ii. If it is false, loop is terminated
• The body of do-while is executed once, even when the condition is initially
false.
Example:
#include<stdio.h>
void main()
{
int a=10;
do
{
printf(“%d\t”, a);
a=a+1;
}
while(a<15)
}
Execution:
Output:
10 11 12 13 14
Three main ingredients of counter-controlled
looping
1. Initialization of loop counter
2. Condition to decide whether to execute loop or not.
3. Expression that manipulates the value of loop.

4.Nested loops
• If the body of a loop contains another iteration statement, then we say that the
loops are nested.
• Loops within a loop are known as nested loop.
• In nested for loops two or more for statements are included in the body of the
loop.
• The numbers of iterations in this type of structure will be equal to the number
of iterations in the outer loop multiplied by the number of iterations in the
inner loop.
Syntax
for(condition)
{
for(condition)
{
Statements;
}
Statements;
}

Example:
#include<stdio.h>
void main()
{
int i,j;
for(i=1; i<=3; i++)
{
printf(“\n”);
for(j=1; j<=3; j++)
printf(“%d\t”, i);
}}
Execution:
Output:
1 2 3
1 2 3
1 2 3
Difference between while and do while loop
S.No while loop do while loop
1. while loop is an entry do while loop is an exit
controlled loop. controlled loop.
2. Since condition is Since condition is
checked first, the looping checked later, the looping
statements may or may statements will execute
not executed. atleast once.

1.13 Preprocessor Directives:

Preprocessor
Directives

File inclusion Macro Conditional Miscellaneous


substitution directive directive
directive
directive #if #pragma
#include
#define #elif #error
#else #line
Operators in preprocessor #endif
# #ifdef
## #ifndef
#undef
Before a C program is compiled in a compiler, source code is processed by a program
called pre-processor. This process is called pre-processing. Commands used in pre-
processor are called pre-processor directives and they begin with “#” symbol.
Macro:
Macro is a segment of code which is replaced by the value of macro.
This macro defines constant value and can be any of the basic data types.
Syntax: #define
Header file inclusion:
The source code of the file “file_name” is included in the major program at the
specified place.
Syntax: #include<file_name>
1.13.1 Conditional compilation:
Set of commands are included or excluded in source program before compilation
with respect to the condition.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Other directives:
#undef is used to undefine a defined macro variable.
#pragma is used to call a function before and after main function in a C program.
The program in C language involves different processes and are:

Program Filename in each steps Description


Process Flow
Sample.c Preprocessor replaces
Source code
#define (macro), #include
(files), conditional
compilation codes like
Preprocessor #ifdef, #ifndef by their
Respective values and
source codes in source
file.

Expand source code Sample.i


Compiler compiles
Compiler expanded source code to
assembly source code.

Assembly source
Sample.s It is a program that
code
converts assembly source
code to object code.
Assembler

Sample.o This is a program that


Object code
converts object code to
executable code and also
Linker combines all object codes
together.

Executable
Sample.exe Executable code is loaded
code
in CPU and executed by
loader program.
Loader

Execution

Example:
Simple C program to explain define and undefine statements.
#include<stdio.h>
#define PI 3.1415
void main()
{
printf(“%f”, PI);
}
Output: 3.141500
#include<stdio.h>
#define PI 3.1415
#undef PI
void main()
{
printf(“%f”, PI);
}
Output: error:’PI’ undeclared
1.14 Compilation Process: Compiling a C program is a multi-stage process. At an
overview level, the process can be split into four seperate stages: Preprocessing,
compilation, assembly, and linking.
Example:
#include<stdio.h>
int
main(void)
{
puts(“Hello , World!”);
return 0;
}
Preprocessing
 The first stage of compilation is called preprocessing.
 In this stage, lines starting with a # character are interpreted by the preprocessor
as preprocessor commands.
 These commands form a simple macro language with its own syntax and
sematics.
 This language is is used to reduce repetition in source code by providing
functionality to inline files, define macros and to conditionally omit code.
Compilation
 The second stage of compilation is confusingly enough called compilation. In
this stage, the preprocessed code is translated to assembly instructions specific to
the target processor architecture. These form an intermediate human readable
language.
 The existence of this step allows for Ccode to contain inline assembly
instructions and for different assemblers to be used.
 Some compilers also supports the use of an integrated assembler, in which the
compilation stage generates machine code directly, avoiding the overhead of
generating the intermediate assembly instructions and invoking the assembler.
Assembler
 During the assembly stage, an assembler is used to translate the assembly
instructions to machine code, or object code. The output consists of actual
instructions to be run by the target processor.
Linking
 The object code generated in the assembly stage is composed of machine
instructions that the processor understands but some pieces of the program are
out of order or missing.
 To produce an executable program, the existing pieces have to be rearranged and
the missing ones filled in. This process is called linking.

You might also like