Unit 1 Introduction

You might also like

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

Chapter 1.

Introduction

FE - C Programming

Prof. Sneha Tapre


Assistant Professor
Dept. of Artificial Intelligence Machine Learning
SIES Graduate School of Technology
Course Code:FEC205
Course Name
C Programming

Objectives: To provide exposure to problem-solving by developing an


algorithm, flowchart and implement the logic using C programming
language.

Outcomes: Learner will be able to…


1.Formulate simple algorithms for arithmetic, logical problems and
translate them to programs in C language
2. Implement, test and execute programs comprising of control
structures.
3. Decompose a problem into functions and synthesize a complete
program.
4. Demonstrate the use of arrays, strings and structures in C
language.
5. Understand the concept of pointers
Syllabus
C Language Introduction

○ C is a procedural oriented and general-


purpose programming language created by
Dennis Ritchie at the Bell Laboratories in
1972.C was invented to write an operating
system called UNIX.
A procedural-oriented programming language
contains a small bunch of code blocks called
procedures to solve a problem.

Why Learn C?
•It is one of the most popular programming
language in the world
•If you know C, you will have no problem
learning other popular programming
languages such as Java, Python, C++, C#, etc,
as the syntax is similar
•C is very fast, compared to other
programming languages, like Java and Python
● Features of the C language

1.Simple

C is a simple language provides a structured


approach (to break the problem into parts), the rich
set of library functions, data types, etc.

2. Machine Independent or Portable


Programs can be executed on different machines with
some machine specific changes. Therefore, C is a machine
independent

3.Memory Management
It supports the feature of dynamic memory allocation.

4. Speed
compilation and execution time of C language is fast

5. Pointer
C provides the feature of pointers. We can directly interact
with the memory by using the pointers. We can use
pointers for memory, structures, functions, array, etc.

6. Recursion
In C, we can call the function within the function. It
provides code reusability for every function.
Unit 1: Introduction
Introduction to components of a Computer
System

● WHAT IS A COMPUTER?
• Computer is a device that transforms data
into meaningful information.
• Data can be anything like marks obtained
by you in various subjects.
• It can also be name, age, sex, weight,
height, etc. of all the students in a class.
• Computer can also be defined in terms
of functions it can perform.
• A computer can
i)accept data,
ii)store data,
iii)process data as desired, and
iv)retrieve the stored data as and when
required and
v)print the result in desired format.
The major characteristics of a computer are
high speed, accuracy, and storage.
● Computer Organisation
1.
● The computer performs basically five major operations
These are
1)it accepts data or instruction by way of input,
2)it stores data,
3)it can process data as required by the user,
4)it gives results in the form of output, and
5)it controls all operations inside a computer.

1.Input: this is the process of entering data and programs into the
computer system.
2.Control Unit (CU): The process of input, output, processing and storage is
performed under the supervision of a unit called 'Control Unit'. It decides when
to start receiving data, when to stop it, where to store data, etc. It takes care of
step -by-step processing of all operations in side the computer.
3.Memory Unit: Computer is used to store data and instructions.
4.Arithmetic Logic Unit (ALU): The major operations performed by the
ALU are addition, subtraction, multiplication, division, logic and comparison.

5.Output: This is the process of producing results from the data for getting
useful information.
The ALU and the CU of a computer system are jointly known as the central
processing unit (CPU). handling everything from basic input/output
operations to complex operations,
● SOFTWARE

As you are aware, computer cannot do anything on its


own. It is the user who instructs computer; what to do,
how to do and when to do. In order to perform any task,
you have to give a set of instructions in a particular
sequence to the computer. These sets of instructions are
called Programs.

Software is a set of instructions, data or programs used to


operate computers and execute specific tasks.

Software can be classified mainly into following


categories and
sub-categories are shown in Figure
◻System Software
• When you switch on the computer the programs stored in ROM
are executed which activates different units of your computer and
makes it ready for you to work on it. This set of programs can be
called system software. System software are sets of programs,
responsible for running the computer, controlling various
operations of computer systems and management of computer
resources. Operating System (OS) falls under this category.
• An operating system is a system software An Operating
System can be defined as an interface between user and
hardware. It is responsible for the execution of all the
processes, Resource Allocation, CPU management, File
Management and many other tasks.
• Some popular Operating systems are UNIX, Windows
and Linux.
//CPU (Central Processing Unit) also called a central
processor or main processor is the brain of a computer,
responsible for executing instructions and performing
calculations. It is composed of the main memory, control unit,
and arithmetic-logic unit
◻Application Software

• Application software is a set of programs, which are written to


perform specific tasks, for example: An application package for
managing library known as library information system is used to
manage information of library such as: keeping book details,
account holder details, book issue details, book return details etc.
Another application package for managing student details is called
student’s information system, manages student’s roll no, name,
parents name, address, class, section, processing of examination
results etc.
●Introduction to Algorithms and Flowchart
➔A step by step procedure for solving a particular
problem is an Algorithm.
➔To be an algorithm, a set of rules must be
unambiguous and have a clear stopping point.
➔Algorithms can be expressed in any language, from
natural languages like English or French to
programming languages like FORTRAN, C

❖Qualities of a good algorithm

‾ Inputs and outputs should be defined precisely.


‾ Each step in algorithm should be clear.
‾ Algorithm should be most effective among many
different ways to solve a problem.

‾ Write an algorithm to add two numbers
entered by user.

Step 1: Start
Step 2: Declare variables num1,
num2 and sum.
Step 3: Read values num1 and
num2.
Step 4: Add num1 and num2 and assign the
result to sum. sum=num1+num2
Step 5: Display sum
Step 6: Stop

variable is the name of a memory location


that we use for storing data
• Flow Chart
Flowcharts are nothing but the graphical
representation of the data or the algorithm for a
better understanding of the code visually.

. Flowchart is very helpful in writing program and


explaining program to others

❖Principles of Flowchart

1.Simplicity: -
-Easy to put on paper
-Easy to draw
-Readable and meaningful
2.Organization:
-putting ideas together and organizing those
ideas in a logical way.

3.Communication: A flowchart is a
better way of communicating the logic of a
program.
Symbols Used In Flowchart

A box represents arithmetic instructions. All arithmetic


processes such as adding, subtracting, multiplication and
division are indicated by action or process symbol

Program instructions that take input from input devices


and display output on output devices

Connectors: Whenever flowchart becomes complex or it


spreads over more than one page, it is useful to use
connectors to avoid any confusions. It is represented by a
circle.
Algorithm & Flowchart to find the sum of two
numbers

Algorithm
Step-1 Start
Step-2 Input first numbers say A
Step-3 Input second number say B
Step-4. SUM = A + B
Step-5 Display SUM
Step-6 Stop
2. Flowchart to find largest
number of two numbers
C Program can be divided into header, main() function, variable
declaration, body, and return type of the program.
C is a structured programming language because it divides the
programs into small modules called functions which makes the
execution easier.

Program in C

C Basic commands Explanation

This is a preprocessor command that includes standard input output header file(stdio.h)
from the C library before compiling a C program
#include <stdio.h>

A header file is a file with extension .h The stdio.h header file


allows us to perform input and output operations in C. The
functions like printf() and scanf() are used to display output and
take input from a user, respectively. .

. It has the information related to input/output functions.


The reason why we use stdio.h in C is that this header file
imports different variables, and functions to perform input
and output operations

If we want to use printf or scanf function in our program, we


should include the stdio.h header file in our source code.

int main() defines the entry or the starting point of the

main():serves as the entry point of the program where the


execution begins.

int main(): An int data type used with the main() function that
indicates the function should return an integer value.
Conio.h is a header file stand for console input-
output.It is a header file with several built-in
functions that are commonly used to execute
input/output on the console, ie: it is used to take
input from the keyboard given by the user and
display output on the screen.

Some functions of conio.h such as getch()


getch(): hold the output screen for some time
until the user passes a key from the keyboard to
exit the console screen.

clrscr()
This function is used to clear the output on the
screen.
return 0 in the main function means that the program
executed successfully. return 1 in the main function means
that the program does not execute successfully

Since the main function (int main()) returns a numeric number,


we are return 0.When a function returns a result, the word
“return” is used.

This is the main function from where


int main()
execution of any C program begins.

This indicates the beginning of the main


{
function.

whatever is given inside the command “/*

/*_some_comments_*/ */” in any C program, won’t be considered for

compilation and execution.

printf command prints the output onto the


printf(“Hello_World! “);
screen.

This command waits for any character


getch();
input from keyboard.

This command terminates C program (main


return 0;
function) and returns 0.

} This indicates the end of the main function.


Format Specifiers in C

• The format specifier in C is used to tell the compiler


about the type of data to be printed or scanned in input
and output operations. They always start with
a % symbol and are used in the formatted string in
functions like printf(), scanf,

• format specifiers are represented by modulus/ percent


symbol (%), followed by a character indicating the data
type. For example, %d represents a decimal integer, %f
represents a floating-point number, and %c represents a
character.
// C Program to illustrate the %c format specifier.
#include <stdio.h>

int main()
{

char c;
// using %c for character input
scanf("Enter some character: %c", &c);

// using %c for character output


printf("The entered character: %c", &c);
return 0;
}
❖ Fundamentals of C Programming

1. Keywords (eg: int, while),


2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Variables (eg: 30, 40)
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)

KEYWORDS IN C LANGUAGE:

A keyword predefined reserved


word, cannot use it as a variable
name, constant name, etc. There
are only 32 reserved words
(keywords) in the C language.
●Identifiers are the building blocks
of a program. Identifiers are
unique names that are assigned to
variables, functions, and other
entitie
●An identifier can be composed of
letters such as uppercase,
lowercase letters, underscore,
digits, but the starting letter should
be either an alphabet or an
underscore.
●eg. x is a name given to an integer
Rules For Naming Identifiers in C
variable.
3. C – Constant

• C Constants are also like normal variables. But, the only


difference is, their values can not be modified by the program
once they are defined.
• Constants refer to fixed values. They are also called as literals
• Constants may be belong to any of the data type.

A constant is a value or variable that can't be changed in the


program, for example: 10, 20, 'a', 3.4, "c programming", etc.

The const keyword is used to define constant in C


programming.
Syntax:
const data_type variable_name;

Example :
const int height = 100;
4. C – Variable

● C variable is a named location in a memory where a


program can manipulate the data. This location is used to
hold the value of the variable.
● The value of the C variable may change in the program.
● C variable might be belonging to any of the data types like int,
float, char etc.

RULES FOR NAMING C VARIABLE:

1.Variable name must begin with a letter or underscore.


2.Variables are case sensitive // case sentitive-two
words that appear or sound identical, but are
using different letter cases(letter , Letter), are
not considered equal.
3.No special symbols are allowed other than
underscore.
4.sum, height, _value are some examples for variable
name
DECLARING & INITIALIZING C VARIABLE:

1. Variables should be declared in the C program before to use.


2. Variable initialization means assigning a value to the variable.

Type Syntax
data_type variable_name;
Variable declaration
Example: int x, y, z;
data_type variable_name = value;
Variable initialization
Example: int x = 50, y = 30;
Operators and Expressions

●The symbols which are used to perform logical and


mathematical operations in a C program are called
C operators.
●Operators, functions, constants and variables are
combined together to form expressions.

●Consider the expression A + B * 5 is anexpression


where, +, * are operators, A, B are variables, 5 is
constant .
TYPES OF OPERATORS:

• Arithmetic operators
• Assignment operators
• Relational operators
• Logical operators
• Bit wise operators
• Conditional operators (ternary
operators) Increment/decrement
operators
• Special operators
Arithmetic Operator is used to
performing mathematical operations such
as addition, subtraction, multiplication,
division, modulus, etc., on the given
operands.
// C program to demonstrate syntax of binary arithmetic
operators
#include <stdio.h>
int main()
{
int a = 10, b = 4, res;

// printing a and b
printf("a is %d and b is %d\n", a, b);

res = a + b; // addition
printf("a + b is %d\n", res);

res = a - b; // subtraction
printf("a - b is %d\n", res);

res = a * b; // multiplication
printf("a * b is %d\n", res);

res = a / b; // division
printf("a / b is %d\n", res);

res = a % b; // modulus
printf("a %% b is %d\n", res);

return 0;
}
Relational Operators

• The relational operators in C are used


for the comparison of the two
operands.
• All these operators are binary
operators that return true or false
values as the result of comparison.
• In case the relation happens to be
true, then it returns to 1. But in case
this relation turns out to be false, then
it returns to the value 0
• Binary operators operate on two
operands. Some of the binary
operators in C are: Arithmetic
operators ( +, -, *, /, % ).
• These are a total of 6 relational
operators in C:
Relational Operators

Assume variable A holds 10 and variable B holds


20 then −
// C program to illustrate the relational operators

#include <stdio.h>

int main()
{
int a = 25, b = 5;

// using operators and printing results


printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);

return 0;
}
Logical Operators
Logical operators in C are used to combine
multiple conditions/constraints. Logical
Operators returns either 0 or 1, it depends on
whether the expression result is true or false.

Reverse the
result, returns
0 if the result
is 1
Logical Operators

Assume variable A holds 1 and


variable B holds 0 then −
#include <stdio.h>
int main()
{
int x = 5;
int y = 3;
// Returns 1 (true) because 5 is greater than 3
AND 5 is less than 10
printf("%d", x > 3 && x < 10);
return 0;
}
Output: 1
#include <stdio.h>

int main()
{
int x = 5;
int y = 3;

// Returns 1 (true) because one of the


conditions are true (5 is greater than 3, but 5 is
not less than 4)
printf("%d", x > 3 || x < 4);
return 0;
}
Output : 1
#include <stdio.h>

int main() {
int x = 5;
int y = 3;

// Returns false (0) because !


(not) is used to reverse the result
printf("%d", !(x > 3 && x < 10));
return 0;
}

Output: 0
Logical AND Operator
The "&&" operator tests whether two
conditions are true simultaneously. It returns
true if both conditions are true, and false
otherwise.

Logical OR Operator
The "||" operator tests whether at least one of two
conditions is true. It returns true if either of the conditions
is true, and false if both are false.

Logical NOT Operator


The "!" operator, also known as the logical NOT
operator, reverses the truth value of a condition. It
returns true if the condition is false, and false if the
condition is true.
#include <stdio.h>
int main()
{
int x = 22, y = 33;

if (x > 0 && y > 0)


{
printf("Both values are greater than 0\n")
;
}
else
{
printf("Both values are less than 0\n");
}
return 0;
}

Output
Both values are greater than 0
Bitwise Operator in C
• The bitwise operators are the operators used
to perform the operations on the data at the
bit-level.
• It consists of two digits, either 0 or 1.
• It is mainly used in numerical computations
to make the calculations faster.
Bitwise AND operator
Two integer operands are written on both
sides of the (&) operator. If the corresponding
bits of both the operands are 1, then the
output of the bitwise AND operation is 1;
otherwise, the output would be 0.

Ex:
1.We have two variables a and b.
2.a =6;
3.b=4;
4.The binary representation of the above two variables
are given below:
5. a = 0110
6. b = 0100
7.When we apply the bitwise AND operation in the abo
ve two variables, i.e., a&b, the output would be:
8.Result = 0100

In the example bits of both the variables are


compared one by one. If the bit of both the
variables is 1 then the output would be 1,
otherwise 0.
#include <stdio.h>
int main()
{
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b i
s %d",a&b);
return 0;
}

n the above code, we have created two variables, i.e., 'a' and 'b'. The
values of 'a' and 'b' are 6 and 14 respectively. The binary value of 'a'
and 'b' are 0110 and 1110, respectively. When we apply the AND
operator between these two variables,
a AND b = 0110 && 1110 = 0110

Bitwise OR operator

The bitwise OR operator is represented by a


single vertical sign (|). Two integer operands
are written on both sides of the (|) symbol. If
the bit value of any of the operand is 1, then
the output would be 1, otherwise 0.
For example,
We consider two variables,
a = 23;
b = 10;
The binary representation of the above two variables wo
uld be:
a = 0001 0111
b = 0000 1010
When we apply the bitwise OR operator in the above tw
o variables, i.e., a|b , then the output would be:
Result = 0001 1111
As we can observe from the above result that the bits of
both the operands are compared one by one; if the
value of either bit is 1, then the output would be 1
otherwise 0.
#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is
%d",a|b);
return 0;
}
Bitwise exclusive OR operator
Bitwise exclusive OR operator is denoted by (^)
symbol. Two operands are written on both sides of the
exclusive OR operator. If the corresponding bit of any
of the operand is 1 then the output would be 1,
otherwise 0. two variables a and b,
We consider
a = 12;
b = 10;
The binary representation of the above two variables
would be:
a = 0000 1100
b = 0000 1010
When we apply the bitwise exclusive OR operator in t
he above two variables (a^b), then the result would be
:
Result = 0000 1110
As we can observe from the above result that the bits
of both the operands are compared one by one; if the
corresponding bit value of any of the operand is 1,
then the output would be 1#include <stdio.h>
otherwise 0.
int main()
{
int a=12,b=10; // variable decl
arations
printf("The output of the Bitwise
exclusive OR operator a^b is %d
",a^b);
return 0;
}
Bitwise complement operator
The bitwise complement operator is also
known as one's complement operator. It is
represented by the symbol tilde (~). It takes
only one operand or variable and performs
complement operation on an operand. When
we apply the complement operation on any
bits, then 0 becomes 1 and 1 becomes 0.
For example,
If we have a variable named 'a',
a = 8;
The binary representation of the above varia
ble is given below:
a = 1000
When we apply the bitwise complement ope
rator to the operand, then the output would b
e:
Result = 0111
Bitwise shift operators
Two types of bitwise shift operators exist in C
programming. The bitwise shift operators will shift the
bits either on the left-side or right-side. Therefore, we
can say that the bitwise shift operator is divided into
two categories:
Left-shift operator
It is an operator that shifts the number of bits to the
left-side.
Syntax
Operand << n
Where,
Operand is an integer expression on which we apply the
left-shift operation.
n is the number of bits to be shifted.
In the case of Left-shift operator, 'n' bits will be shifted on the
left-side. The 'n' bits on the left side will be popped out, and 'n'
bits on the right-side are filled with 0.
For example,
Suppose we have a statement:
int a = 5;
The binary representation of 'a' is given below:
a = 0101
If we want to left-
shift the above representation by 2, then the statement would
be:
a << 2;
0101<<2 = 00010100
#include <stdio.h>
int main()
{
int a=5; // variable initialization
printf("The value of a<<2 is : %d ", a<<2);
return 0;
}

Right-shift operator
It is an operator that shifts the number of bits
to the right side.
Syntax of the right-shift operator is given
below:
1.Operand >> n;
Where,
Operand is an integer expression on which
we apply the right-shift operation.
N is the number of bits to be shifted.
In the case of the right-shift operator, 'n' bits will be
shifted on the right-side. The 'n' bits on the right-side
will be popped out, and 'n' bits on the left-side are
filled with 0.
For example,
1.Suppose we have a statement,
2.int a = 7;
3.The binary representation of the above variable wo
uld be:
4.a = 0111
5.If we want to right-
shift the above representation by 2, then the stateme
nt would be:
6.a>>2;
7.0000 0111 >> 2 = 0000 0001

#include <stdio.h>
int main()
{
int a=7; // variable initialization
printf("The value of a>>2 is : %d ", a>>2);
return 0;
}
// C Program to demonstrate use of bitwise operators

#include <stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
unsigned char a = 5, b = 9;

// The result is 00000001


printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a & b);

// The result is 00001101


printf("a|b = %d\n", a | b);

// The result is 00001100


printf("a^b = %d\n", a ^ b);

// The result is 11111010


printf("~a = %d\n", a = ~a);

// The result is 00010010


printf("b<<1 = %d\n", b << 1);

// The result is 00000100


printf("b>>1 = %d\n", b >> 1);

return 0;
}
Assignment Operators

Assignment operators are used for assigning


value to a variable

Increment/decrement operators
These operators are used to either increase or
decrease the value of the variable by one.
Assignment Operators

There are 2
categories of
assignment
operators in C
language. They
are,
1.Simple
assignment
operator (
Example: = )
2.Compound
// C program to demonstrate working of Assignment operators

#include <stdio.h>

int main()
{

// Assigning value 10 to a using "=" operator


int a = 10;
printf("Value of a is %d\n", a);

// Assigning value by adding 10 to a using "+=" operator


a += 10;
printf("Value of a is %d\n", a);

// Assigning value by subtracting 10 from a using "-="


operator
a -= 10;
printf("Value of a is %d\n", a);

// Assigning value by multiplying 10 to a using "*=" operator


a *= 10;
printf("Value of a is %d\n", a);

// Assigning value by dividing 10 from a using "/=" operator


a /= 10;
printf("Value of a is %d\n", a);

return 0;
}
Modulus of a, b is : 0
PROGRAM FOR ASSIGNMENT OPERATORS:

}
// for loop is used to repeat a block of code until the specified
condition is met
Loops in C is used to execute the block of code
several times according to the condition given in
the loop.

Why do we use loop in C?


1) It provides code reusability. 2) Using loops,
we do not need to write the same code again
and again.

for loop
When you know exactly how many times you
want to loop through a block of code, use the for
loop.
for loop is used to repeat/iterate a block of
code(statement) until specified condition is met

Syntax
for (expression 1; expression 2; expression 3)
{ }

// code block to be executed


}
expression 1 is executed (one time)
before the execution of the code block.
expression 2 defines the condition for
executing the code block.
expression 3 is executed (every time)
after the code block has been executed.
for loop flowchart

}
//A list is a collection of different kinds of
values or items. An element of the list can be
any data

}
Example
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 5; i++)
{
printf("%d\n", i);
}
return 0;
}
Example explained
expression 1 sets a variable before the loop
starts (int i = 0).
expression 2 defines the condition for the
loop to run (i must be less than 5). If the
condition is true, the loop will start over again,
if it is false, the loop will end.
expression 3 increases a value (i++) each
}

time the code block in the loop has been


executed.
Relational Operators
EXAMPLE PROGRAM FOR RELATIONAL
OPERATORS
Increment/decrement Operators

Increment operators are used to increase


the value of the variable by one and
Decrement operators are used to
decrease the value of the variable by
one in● C

●Syntax:
Increment operator: var_name++;
Decrement operator: var_name –
-;
●Example:
Increment operator : i ++
; Decrement operator : i –
–;
Conditional Operator in C

●The conditional operator is also known


as a ternary operator.
●The conditional statements are the
decision-making statements which
depends upon the output of the
expression. It is represented by two
symbols, i.e '?' and ‘:’
●Syntax

Expression1? expression2: expressio


n3;
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for a
ge variable
(age>=18)? (printf("eligible for voting")) :
(printf("not eligible for voting"));
// conditional operator

return 0;
}
• In the above code, we are taking
input as the 'age' of the user.
• After taking input, we have applied
the condition by using a
conditional operator.
• In this condition, we are checking
the age of the user. If the age of
the user is greater than or equal to
18, then the statement1 will
execute, i.e., (printf("eligible for
voting")) otherwise, statement2 will
execute, i.e., (printf("not eligible
for voting"))
Data Types
●Each variable in C has an associated data
type.
●It specifies the type of data that the variable
can store like integer, character, floating,
double, etc.
●Each data type requires different amounts of
memory and has some specific operations
which can be performed over it..
●data type specifies the size and type of
information the variable will store
●data type defines the type of data we are
going to store in variable and how much
memory we require to store that data
Data Types
- float - typedef
-void - enum
-double

int main()
{
int a = 4000; // positive integer data
char c = 'Z'; // char data type
long d = 41657; // long positive integer data
short g = 130; // short +ve integer data type
short h = -130; // short -ve integer data type
double i = 4.1234567890; // double float data
Int: Short and long
Short and long are the size modifier

Range of integer depends on the machine wheather


it is 16-bit,32,bit or 64 bit machine.

In 16 bit machine range of inetegr is -32768 to 32767


Signed and unsigned and are datatype modifier that can be used
with some primitive data types to change the size or length of
the datatype. You can alter the data storage of a data type by using
them You can alter the data storage of a data type by using them

Unsigned integer range is 0 to 65536. The numbers we can


take in this range only for 16 bit machine

Range of 32 bit machine is -214483648 to 214783647

To find size : printf(“%lu”, size of (int))

long int predefined function


•signed - allows for storage of both positive and negative numbers
•unsigned - allows for storage of only positive numbers
List of Format Specifiers in C

Format Specifier Description


%c character
%d Signed int

%f For float type.

%u Unsigned int

%lf Double

%ld long int

%d Short int or signed short int

%Lf Long double


Integer datatype in C is used to store the
integer numbers(any number including
positive, negative and zero without decimal
part).
•Range: -2,147,483,648 to 2,147,483,647
•Size: 4 bytes
•Format Specifier: %d
•Syntax:

Character data type allows its variable to


store only a single character. The size of the
character is 1 byte. Format Specifier is %c

Syntax:
char var_name;
#include <stdio.h>
void main()
{
char c = 'b';
printf("The character value is: %c \n", c);
}

float data type Float in C is used to store decimal


and exponential values. •Size: 4 bytes
#include <stdio.h> •Format Specifier: %f
void main()
{
float f = 7.2357;
printf("The float value is: %f \n", f);
}

#include <stdio.h>
void main()
{
float f = 7.2357;
printf("The float value is: %f
\n", f);
}
double
Stores fractional numbers. Double has 8
bytes, which is equal to 64 bits in size
Syntax: double data1;
format specifier "%lf" is used to
display a floating point number with one
digit after the decimal point.

#include <stdio.h>
void main()
{
double d = 71.2357455;
printf("The double value is: %lf \n", d);
}

The size of each data type is defined in


bits or bytes (8 bits). :
//Program 1:Integer data type
#include <stdio.h>
void main()
{
int i = 5;
printf("The integer value is: %d \n", i);
}

//Program 2:character data type

#include <stdio.h>
void main()
{
char c = 'b';
printf("The character value is: %c \n",
c);
}
//Program 3: float data type
#include <stdio.h>
void main()
{
float f = 7.2357;
printf("The float value is: %f \n", f);
}

//Program 4:double data type

#include <stdio.h>
void main()
{
double d = 71.2357455;
printf("The double value is: %lf \n",
d);
}
Data Type Modifiers
in C
In C, data type modifiers are used to modify
the length or size of data that various data
types hold such as int, char, and double as per
the requirements. By using these data type
modifiers we can precisely utilize the
computer memory.
Types of Modifiers
In C, we have 4 data type modifiers that are used to
modify data types.

1.short
2.long
3.signed
4.unsigned

1. ‘short’ Type Modifier

short modifier works with integer data type. It


decreases the size of the int to 2 bytes along with the
range that decreases to -32,768 to 32,767.
// C program to illustrate difference between
short int and int

#include <stdio.h>

int main()
{
int a;

// Modify the int using short


short int b;

// Print the size of a.


printf("Size of a: %d", sizeof(a));

// Print the size of b.


printf("\nSize of b: %hd", sizeof(b));

return 0;
}

Output
Size of a: 4
Size of b: 2
With scanf, the "h" modifier indicates that it's reading a
short integer.So the "%hd" is necessary to write only
two bytes (on most machines) instead of the 4 bytes
that "%d" writes.
‘long’ Type Modifier in C
long data type modifier is used to increase the size
of a int or double data type by two times that also
increases the range of these data types. For example,
if int take 4 bytes of space it will take 8 bytes of
space after using long with int

‘signed’ Type Modifier in C


It is default modifier of int and char data type if no
modifier is specified. It indicates that we can store
both negative and positive values.
// CProgram to illustrate int and signed int
#include <stdio.h>
int main()
{
int num1 = 248;
signed int num2 = 23124;

printf("size of num1: %d", sizeof(num1));


printf("\nsize of num2: %d", sizeof(num2));

return 0; Outputs:
} Size of num1: 4
size of num2: 4
unsigned’ Type Modifier in C
• unsigned int can store positive values.
• if the range of int is “-2,147,483,648 to
2,147,483,647” then after using unsigned with int
the range became “0 to 4,294,967,295”
Data Types with Unsigned
•unsigned int
•unsigned short int
•unsigned long int

// C Program to illustrate difference between int and


unsigned int
#include <stdio.h>
int main()
{
int num1 = 4294967295;
unsigned int num2 = 4294967295;

printf("num1: %d", num1);


printf("\nnum2: %u", num2);

return 0;
}
Output
num1: -1
num2: 4294967295

num1 value is -1 because num1 is of int type


and cannot hold larger values, and on the
other hand num2 is of ‘unsigned int’ type and
can hold large value up to 429496295.
tyepdef
User defined data type
enum
Array
Input Output

• Input refers to feeding data into the


program, and Output refers to getting data
out of the program.
• The following are the functions used for
standard input and output:
• printf() - Show Output. This function is
defined in the stdio.h header file and is
used to show output on the console
(standard output).
In the code example below, we have used
the printf() function to print values of
a float and double type variable.
For float value we use the %f format
specifier and for double value we use
the %lf format specifier.
2.scanf() function - Take Input
Blank Spaces, New
Line
getchar is used for input, while putchar is used for
output.
getchar( ) function is used to read one character at
a time from the key board.

Syntax:
ch = getchar( ); //where ch is a char Var.

#include <stdio.h>
void main( )
{
int c;
printf("Enter a character: ");
/*
Take a character as
input and store it in
variable c
*/
c = getchar();
putchar(c);
}
getchar() & putchar() functions
getchar is used for input, while putchar is used for output.
getchar()function reads a character from the terminal and returns it as an integer
function reads only a single character at a time. This method in a loop in case
want to read more than one character. +
putchar() function displays the character passed to it
on the screen and returns the same character. This function too displays
only a single character at a time. In case you want to display more than
one character, use method in a loop.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
/*
Take a character as input and
store it in variable c
*/
c = getchar();
/*
display the character stored
in variable c
*/
putchar(c)
;
}
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered.

● gets() & puts() functions


putchar( ) function is used to display one
character at a time on the monitor.
Syntax: putchar (ch);
The Computer display the value char of variable ‘ch’ i.e
G on the Screen.
#include <stdio.h>
int main()
{
// Get the character to be written
char ch = 'G’;
putchar(ch);
return (0);
}

gets() is a pre-defined function in C which is used to


read a string or a text line. And store the input in a well-
defined string variable. The function terminates its
reading session as soon as it encounters a newline
character.
Syntax:
gets( variable name );
#include<stdio.h>
int main()
{
char string[10];
printf("Enter the String: ");
gets(string);
printf("\n%s",string);
return 0;
}
➢ Operator Precedence and Associativity in C
Operator precedence determines which operator is
performed first in an expression with more than one operator

with different precedence.


For example:

10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30
Operators Associativity is used when two operators of the same
precedence appear in an
expression. Associativity can be either Left to Right or Right to Left.

For example: ‘*’ and ‘/’ have same precedence and their

associativity is Left to Right, so the expression “100 / 10 * 10” is

treated as “(100 / 10) * 10”.

Operators Precedence and Associativity are two characteristics of


operators that determine the
evaluation order of sub-expressions in absence of
brackets
For example:

100 + 200 / 10 - 3 * 10
1)Associativity is only used when there are two or more operators
of same precedence.
2)All operators with the same precedence have same
associativity For example + and – have the same
associativity.
() Parentheses (function call) (see Note 1)

[] Brackets (array subscript)

. Member selection via object name left-to-right

-> Member selection via pointer

++ — Postfix increment/decrement (see Note 2)

++ — Prefix increment/decrement

+– Unary plus/minus

!~ Logical negation/bitwise complement

(type) Cast (convert value to temporary value of type) right-to-left

* Dereference

& Address (of operand)

sizeof Determine size in bytes on this implementation

* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to

left-to-right
> >= Relational greater than/greater than or equal to

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left


In-built function

• In C programming language, a built-in


function (also called a library function)
that is already included in the C
Standard Library.
• scanf(), printf(), gets(), puts(), ceil(),
floor() etc.
Some examples of built-in functions in C
include:

•printf(): used to display output on the


console
•scanf(): used to take input from the user
•strlen(): used to find the length of a string
•strcpy(): used to copy one string to
another
•sqrt(): used to find the square root of a
number
•rand(): used to generate a random number
Header Description
file
This is standard input/output header
stdio.h file in which
Input/Output functions are declared
conio.h This is console input/output header file

string.h All string related functions are defined


in this header file
math.h All maths related functions are defined
in this header file

<ctype.h> header file has several built-in


functions that are useful for testing and mapping
characters.

//ctype (character type)


List of C ctype.h Library Functions

1) isalnum()
.
This function checks whether character is
alphanumeric or not.
Alphanumeric characters are made up of the
26 letters of the alphabet (A through Z) and the
digits 0 through 9
2) isalpha()
This function checks whether character is
alphabet or not
3) isdigit()
This function checks whether character is
digit or not
)
4 isupper()
This function checks whether character is an
uppercase character or not.
5) islower()
This function checks whether character is a
lowercase character or not.
6)isprint()
This function checks whether character is
printable or not.
/* C example program of isalpha().*/

#include <stdio.h>
#include <ctype.h>

int main()
{
char ch;

printf("Enter a character: ");


scanf("%c", &ch);

if (isalpha(ch))
printf("%c is an alphabet.\n", ch);
else
printf("%c is not an alphabet.\n", ch);

return 0;
}
• floor( ) is a library function in C defined in the
<math.h> header file.

• This function returns the nearest integer value, which


is less than or equal to the floating point number (float
or double) passed to it as an argument. (ie: rounds
downs the nearest integer).
• For example, if we pass a floating point number
5.6677 to the floor() function, the return value will be 5
(an integer).
Syntax: floor(float or a double value)
// Using floor() function
#include <stdio.h>
#include <math.h>
int main()
{
float num = 3.14; // initializing a float value
int result = floor(num); // returning the floor value of a float
value
printf("Floor integer of %.2f = %d", num, result); // printing
the floor value
}
return 0;
.%2f format specifier is used to format the
floating-point value with two decimal places
• Ceil function is a predefined function of math.h header
file.
• It returns the nearest integer number, which is greater
than the number passed as an argument in it. he ceil()
function accepts a single argument and returns an integer
value.
• For example, we pass the float number 3.4, and the ceil()
function returns greatest number 4.
• Syntax: double ceil ( double x);
x is an argument of the ceil function.
#include <stdio.h>
#include <math.h>
int main ()
{
double num = 9.37; // declare variables
int result;
// use ceil () function to round up the nearest
value.
result =
ceil(num);
printf ( " \n The ceiling integer of %.2f = %d
", num, result);
return 0;
}
Output
The ceiling integer of 9.37 = 10
sqrt() function in C returns the square root
of the number. It is defined in
the math.h header file.
Syntax: double sqrt(double x);
The sqrt() function takes a single number(in
double) as the input. sqrt() function returns a
double number value as the output.

#include<stdio.h>
#include<math.h>

int main()
{
double a = 45.98;
printf("The square root of %lf: %lf\n", a, sqrt(a));

return 0;
}

The square root of 45.980000: 6.780855


pow ( ) :This is used to find the power of the
given number. Defined in math.h header file
Syntax :
double pow(double x, double y)
•base is the number to be raised.
•exponent is the power to which the base
number is raised.

#include <stdio.h>
#include <math.h>

int main()
{
double num = 4.0;
double result = pow(num, 2.0);
printf("The square of %.2f is: %.2f\n",
num, result);
return 0;
}

Output
The square of 4.00 is: 16.00
tanh ( ) This function is used to
calculate hyperbolic tangent.
sinh ( ) This function is used to
calculate hyperbolic sine.

log ( ) This function is used to


calculates natural logarithm.
log10 ( )
This function is used to
calculates base 10 logarithm.
C – stdio.h library functions

Description
Function
This function is used to print the character,
printf() string, float, integer, octal and hexadecimal
values onto the output screen
This function is used to read a character,
scanf() string, numeric data from keyboard.
gets() It reads line from keyboard

getchar() It reads character from keyboard

puts() It writes line to o/p screen

putchar() It writes a character to screen

C – conio.h library functions

Functions Description

clrscr() This function is used to clear the output


screen.
getch() Holds the output screen
C – string.h library functions
Write a program to find the greatest of 3
numbers.
// C program to find the maximum number out of the
three
given numbers using if-else statement
#include <stdio.h>
int main()
{
int A, B, C;
printf("Enter the numbers A, B and C: ");
scanf("%d %d %d", &A, &B, &C);
if (A >= B && A >= C)
printf("%d is the largest number.", A);
else if (B >= A && B >= C)
printf("%d is the largest number.", B);
else
printf("%d is the largest number.", C);
return 0;
}
• List and explain different components of Computer
System.
• Explain conditional operators used in C language with
proper examples.
• Explain bitwise operators available in c.
Explain data type modifiers available in c language.
• Explain what is flowchart? Explain different symbols
used in flowchart.
• Explain following library functions with proper
examples. A) gets( ) b)pow() c) ceil() d) floor( ) e) sqrt( )
• Explain with example left and right shift bitwise
operators.
• Define Flowchart and Draw flowchart to find sum of
digits of an acceptednumber.
• Write a program to find square root of a accepted perfect
square integer number without using standard sqrt( )
function.
Programs for practice

1. Write a program to calculate simple and compound


interest.
2. Write a program to swap values of two variables with and
without using third variable.
3. Write a program to display the size of every data type
using “sizeof” function.
5. Write a program to input two numbers and display the
maximum number.
6. Write a program to find the largest of three numbers
using ternary operators.
7. Write a program to find the roots of quadratic equation.
8. Write a program to input name, marks of 5 subjects of a
student and display the name of the student, the total marks
scored, percentage scored and the class of result.

You might also like