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

Established as per the Section 2(f) of the UGC Act,

1956
Approved by AICTE, COA and BCI, New Delhi

B22CI0104
Programming with C

SCHOOL OF COMPUTER SCIENCE AND ENGG.


COURSE OBJECTIVE
➢ Explain algorithms, flowcharts and different programming constructs of C to

be used for development of applications.

➢ Illustrate the use of iterative statements and conditional Statements for solving

the real world problems.

➢ Demonstrate the use of pointers and functions with parameter passing

mechanisms for solving the real world problems.

➢ Discuss the use of structures, unions, and file operations for solving the real

world problems.
HISTORY OF C

• C is a programming language developed at AT & T’s Bell Laboratories of


USA in 1972.
• It was designed and written by Dennis Ritchie.
WHY THE NAME C?

• There was language by the name B designed by Ken Thomson at Bell


Labs.
• Dennis Ritchie has used most of the features of B and removed some
complicated parts of B.
• To convey the message that it is extension of B, Dennis Ritchie coined
his new programming language as C. (In alphabetical order C comes
after B)
UNIT - I

Algorithm and Flowchart


Algorithm
✓ The word Algorithm means ” A set of rules to be followed in calculations
or other problem-solving operations ”
Or
An algorithm is defined as finite sequence of unambiguous instructions
followed to accomplish a given task.
Or
Unambiguous step by step procedure (instructions) to solve a given problem in
a finite number of steps by accepting set of inputs and producing the desired
output

C_Pgm_Unit_I 6
Purpose of writing an algorithm
• It is written using English language so that it is easily understandable even by non-

programmers.

• Basically an algorithm is a finite steps that must be followed to solve any problem.

• Sometimes algorithms are written using “pseudocodes”.

C_Pgm_Unit_I 7
Rules for writing an algorithm
✓ It should terminate after a finite time.

✓ It should produce at least one output.

✓ It should take zero or more input.

✓ It should be deterministic means giving the same output for the same input case.

✓ Every step in the algorithm must be effective i.e. every step should do some work.

C_Pgm_Unit_I 8
Add two numbers entered by the user

Step 1: Start

Step 2: Read values num1 and num2.

Step 3: Add num1 and num2 and assign the result to sum.

sum←num1+num2

Step 4: Display sum

Step 5: Stop

C_Pgm_Unit_I 9
Algorithm to calculate simple interest

Step 1: Start

Step 2: Read values for p, t and r

Step 3: calculate simple interest and assign value to si

si←p × t × r / 100

Step 4: Display si

Step 5: Stop

C_Pgm_Unit_I 10
Algorithm to calculate area of triangle

Step 1: Start

Step 2: Read values for b and h

Step 3: calculate area of triangle and assign value to area

area←0.5 × b × h

Step 4: Display area

Step 5: Stop

C_Pgm_Unit_I 11
Algorithm to calculate area of circle

Step 1: Start

Step 2: Read value for r

Step 3: calculate area of circle and assign value to area

area←3.1412 × r × r

Step 4: Display area

Step 5: Stop

C_Pgm_Unit_I 12
Find the largest number among three numbers
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If (a > b && a > c )
Display a is the largest number.
else if ( b > a && b>c)
Display b is the largest number.
else
Display c is the largest number.

Step 5: Stop

C_Pgm_Unit_I 13
Flow chart

✓ A flowchart is a diagram that depicts a process, system or computer algorithm.

✓ They are widely used in multiple fields to document, study, plan, improve and
communicate often complex processes in clear, easy-to-understand diagrams.

C_Pgm_Unit_I 14
Notations used to write a flow chart

C_Pgm_Unit_I 15
Add two numbers

C_Pgm_Unit_I 16
Calculate profit and loss

C_Pgm_Unit_I 17
Largest among three different numbers

C_Pgm_Unit_I 18
Advantage of writing algorithm
✓ It is easy to understand.

✓ An algorithm is a step-wise representation of a solution to a given problem.

✓ No programming language required

✓ In Algorithm the problem is broken down into smaller pieces or steps hence, it is

easier for the programmer to convert it into an actual program.

✓ It is easy to debug as every step is got its own logical sequence.

C_Pgm_Unit_I 19
Advantages of using flowcharts
✓ Communication: Flowcharts are better way of communicating the logic of a system

to all concerned or involved.

✓ Effective analysis: With the help of flowchart, problem can be analysed in more

effective way therefore reducing cost and wastage of time.

✓ Proper documentation: Program flowcharts serve as a good program

documentation, which is needed for various purposes, making things more efficient.

✓ Efficient Coding: The flowcharts act as a guide or blueprint during the systems

analysis and program development phase.

✓ Proper Debugging: The flowchart helps in debugging process.


C_Pgm_Unit_I 20
Disadvantages of using flowcharts
✓ Complex logic: Sometimes, the program logic is quite complicated. In that case,

flowchart becomes complex and clumsy. This will become a pain for the user,

resulting in a waste of time and money trying to correct the problem

✓ Alterations and Modifications: If alterations are required the flowchart may require re-

drawing completely. This will usually waste valuable time.

✓ Time consuming

C_Pgm_Unit_I 21
Difference between Flow Chart & Algorithm

C_Pgm_Unit_I 22
Structure of C program
comments function 1 definition
preprocessor directives
Global variables Declaration
{
int main ()
{ }
Local variables Declaration function 2 definition
program statements
call function 1
{
call function 2
} }
1. DOCUMENTATION / COMMENTS
• 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.

• It is represented as follows

1.Single line comment:

// description, program name, programmer name, date, time etc.

Or

2.Multi-line comment:

/* description, name of the program, programmer name,

date, time etc.*/


2. PREPROCESSOR SECTION
• All the header files of the program will be declared in the preprocessor section of the
program.
• Header files help us to access various pre-defined functions code into our program,
before the process of compilation.
• Preprocessor directives start with the ‘#’ symbol.
• The #define preprocessor is used to create a constant throughout the program.
• Example:
• #include<stdio.h>
• #include<conio.h>
• #include<math.h>
• #define PI 3.1412 // symbolic constants
3. GLOBAL VARIABLE 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 program.
• The lifetime of the global variable exists till the program executes.

• Example: int num = 18;


4. MAIN() FUNCTION
• Every C program must have a single main function. The actual code / program is
written in this section.

• Operations like declaration and execution are performed inside the open and close
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() or main()


5. LOCAL VARIABLE DECLARATION
• Variables that are declared within or inside a function block are known as
Local variables.
• These variables can only be accessed within the function in which they are
declared.
• The lifetime of the local variable is within its function only, which means
the variable exists till the function executes.

• Example: int num = 18;


6. FUNCTIONS
• User-defined functions are called from the main function of the
program.

• The control of the program is shifted to the called function


whenever they are called from the main() function.

Example:
int add(int p, int q)
{
int r;
r = p + q;
return r;
}
//Program: To find addtion of 2 int add (int p, int q)
numbers {
//Author: Dennis Ritchie int r;
//Date: 09/03/2024 r = p + q;
# include <stdio.h> return r;
int a, b, c; }
int main ()
{
int a, b, c;
int add (int, int);
a = 10;
b = 20;
c = add (a, b);
printf ("%d", c);
return 0;
}
C TOKENS

✓ We can define the token as the smallest individual element in C.


• Classification of tokens in C
– Keywords
– Identifiers
– Variables
– Constants
– Strings
– Special Symbols
– Operators
KEYWORDS
✓ Keywords are pre-defined or reserved words in a programming language.
✓ Each keyword is meant to perform a specific function in a program.
✓ Rules to be followed while using keywords are:
1. They should not be used as variable names, identifiers (function names, array
names etc).
2. The meaning of keywords cannot be changed by the user.
3. All keywords are written in lower case letters.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
IDENTIFIERS
✓ Identifiers are the names that are given to various program elements such
as variables, symbolic constants, arrays and functions.
✓ Rules to frame an identifier:
1. An Identifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and
underscore( _ ).
2. It must begin with a letter or underscore.
3. Identifiers are case sensitive.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, dot, whitespaces, slash or
comma are permitted to be used in or as Identifier.
Valid Identifiers Invalid Identifiers
Add 123Add
add Add$
add_123 Add-123
_add int
_123_abc Add 123

C_Pgm_Unit_I 34
CONSTANTS:
An entity whose value does not change during the execution of program. The
classification of constants in C is shown below:
CONSTANTS:
• Integer Constant: Integer constants are whole numbers without any fractional
part. Ex: 10, -5, 24, 0

• Floating Point Constant: A number with decimal point is called floating point
constant.
Ex: 10.5, -5.6, 12.3
Note: 2.3*10^67 can be written as 2.3e67 or 2.3E67

• Character Constant: A character constant is a single letter/ any symbol, enclosed


in single quotation mark.
Ex: ‘a’, ‘6’, ‘$’

• String Constant: String is “Sequence of one or more Characters”. String


Constant is written in Pair of Double Quotes.
Ex: “REVA”, “Hello”, “123”, “abc_123”
STRINGS:
✓ Strings are nothing but an array of characters ended with a null character (‘\0’).
✓ This null character indicates the end of the string. Strings are always enclosed in
double-quotes.
✓ Whereas, a character is enclosed in single quotes in C.

Declarations for String:


✓ char string[5] = {‘R’,’E’,’V’,’A’, ‘\0’};
✓ char string[5] = “REVA”;
✓ char string [] = “REVA”;
SPECIAL SYMBOLS:
• The following special symbols are used in C having some special meaning and
thus, cannot be used for some other purpose.[] () {}, ; * = #

• Brackets []: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
• Parentheses (): These special symbols are used to indicate function calls and
function parameters.
• Braces {}: These opening and ending curly braces mark the start and end of a
block of code containing more than one executable statement.
• Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
p, t, r and si are variables

12.5000 23.40000
# include <stdio.h> P t
00 0
int main ()
{ 32.500 95.06250 si
float p, t, r, si; r 000 0
datatype
printf ("Enter values for p, t and r \n");
scanf ("%f%f%f", &p, &t, &r);
si = p * t * r / 100; Enter values for p, t and r
printf ("Simple interest = %f\n", si); 12.5
return 0; 23.4
} 32.5
Simple interest = 95.062500
100 is a constant
Variables
• Variable is a name given to memory location, its value can change during
the execution of the program. In the above program p, t, r and si are
variable names
Rules for constructing variable names:
1. Variable name can be constructed using alphabets, digits and underscore
2. First character should be alphabet or underscore
3. Keywords cannot be used as variable names in the program
4. No white spaces allowed within variable name
Note: C is a case sensitive language
REVA and Reva both are different according to C language
si int

2si $abc

_si simple

p sb_acc
t
abc_123

abc-123
Difference b/w variable declaration and definition / Variable initialization :

✓ Variable declaration refers to the part where a variable is first declared or


introduced before its first use. Ex: int a;

✓ A variable definition / Variable Initialization:

If we assign some value to a variable at the time of declaration, then it is


called initialization

o Eg: int a=5;


Types of variables
1. Local / automatic variable
2. Register variable
3. Static variable
4. Global variable
TYPES OF VARIABLES IN C CONT..
1. Local Variable / Automatic Variable
o A variable that is declared and used inside the function or block is called a
local variable.

o It is scope is limited to function or block.

o It cannot be used outside the block.

o We can explicitly declare an automatic variable using the auto keyword.

Note: {

} Block
TYPES OF VARIABLES IN C CONT..
2. Register variable
o A variable that is declared and used inside the function or block with the
keyword register is called register variable.

o It is scope is limited to function or block.

o It cannot be used outside the block.

o If we declare a variable with the keyword register, if register is available,


then the value will be stored in CPU register otherwise it will be stored in
RAM (Primary Memory)

o Register access is always fast compared to memory access.


TYPES OF VARIABLES IN C CONT..
3. Static Variable:

o A variable that retains its value between multiple function calls is known as a
static variable.

o It is declared with the static keyword.


TYPES OF VARIABLES IN C CONT..
4. Global Variable:

o A variable that is declared outside the function or block is called a global


variable.

o Declared before main function.

o It is available for all functions.


DATA TYPES IN C
✓ 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.
.
Primary/ Basic/ simple/ Primitive / fundamental data types: integer (int), floating
(float), character (char), double and void.

Derived / Non Primitive data types: arrays, functions, structures and pointers.
1. Void Data types

A void is an empty data type. No value is associated with void. so, no


memory will be allocated to void.
2. Integer types
✓ The integer data type in C is used to store the whole numbers without decimal
point. Octal values, hexadecimal values, and decimal values can be stored in int
data type in C.
o Size: 2 bytes or 4 bytes
o Format Specifier: %d
✓ Note: The size of an integer data type is compiler-dependent, when processors are
16-bit systems, then it shows the output of int as 2 bytes. And when processors are
32-bit then it shows 4 bytes.
2. Integer types
The sizes of the integer variables
3. Character types
✓ It is the basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.

✓ A char keyword is used to define a single character.


o Range: (-128 to 127) or (0 to 255 for unsigned)
o Size: 1 byte
o Format Specifier: %c
4. Floating-Point Types

✓ In C programming float data type is used to store floating-point values (decimal


and exponential values).
✓ floating point numbers have 6 decimal digits precision after decimal point i.e. it
will show only 6 digits after decimal point.
o Size: 4 bytes or 8 bytes
o Format Specifier: %f
5. Double types
✓ A Double data type in C is used to store decimal numbers (numbers with floating
point values) with double precision.
✓ Since double has more precision as compared to float, so it occupies twice the
memory as occupied by the floating-point type.
✓ double have 12 decimal digits precision after decimal point i.e. it will show 12
digits after decimal point.
o Size: 8 bytes or 16 bytes
o Format Specifier: %lf
Input and Output Functions
Types of input output functions:
1. Formatted I/O Functions.
2. Unformatted I/O Functions.
Input and Output Functions cont..
Formatted Input Function: scanf()

✓ It is the library function defined in stdio.h header file. This function takes all
types of values (numeric, character, string) as input.

✓ The scanf() can be written as:


scanf(“Format / type specifier”,address1,address2....);

✓ Parameters: First is format specifier, which contains conversion specification


characters and should be written in double quote. Ex: %d, %f, %c etc.
✓ The second parameter is called as address list, where variable name should be
written with & sign as prefix. →address operator.

✓ The number of format specifier and number of variables in address list


must be same.
Input and Output Functions cont..
Formatted Input Function: scanf()

Format / type specifier

• %d → int
• %f → float
• %lf → double
• %c → char
• %s → string
Input and Output Functions cont..
Formatted Input Function: scanf()
Input and Output Functions cont..
Formatted Output Function: printf()

• It is a library function defined in stdio.h header file which will take data stored at
given location and prints it on monitor.

• This function prints all types of values (numeric, character, string) as input.

• printf(“Format / type specifier”, variable1,variable2,.....); or

• printf(“write the message to be printed”);

• First is Format / type specifier, which contains conversion specification


characters and should be written in double quote.

• Second parameter is called as variable list.


Input and Output Functions
Formatted Output Function: printf()
✓ The number of format specifier and number of variables in address list must
be same.
Unformatted Input/Out put functions
✓ Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype.

✓ The following unformatted I/O functions are:

o getch(), getche() and putch()

o getchar() and putchar()

o gets() and puts()


Unformatted Input/Out put functions
1. getchar() and putchar() :

• getchar(): It reads a character from the keyboard and store this into a memory
location. We have to press ENTER key after typing the character.

• Whenever we want to display a character stored in memory on the screen


putchar() function is used. These functions are defined in stdio.h header file.
Unformatted Input/Out put functions
2. getch(), getche() and putch():

• getch(): It reads a character from the keyboard without echo. Whenever


we want to read a character from the keyboard with echo we use getche()
function.
• Whenever we want to display a character stored in memory location we
use putch() function.
Unformatted Input/Out put functions
3. gets() and puts():
• Whenever we want to read a sequence of characters from the keyboard
with spaces in between, we use gets() function.

• Whenever we want to display a sequence of characters stored in memory


location, we use puts() function.
Formatted I/O vs Unformatted I/O
S No. Formatted I/O functions Unformatted I/O functions

These functions allow us to take input or These functions do not allow to take input
1 display output in the user’s desired format. or display output in user desired format.

These functions do not support format


2 These functions support format specifiers. specifiers.

These are used for storing data more user


3 friendly These functions are not more user-friendly.

Here, we can use only character and string


4 Here, we can use all data types. data types.

printf(), scanf() are examples of these getch(), getche(), gets() and puts(), are
5 functions. some examples of these functions.
SAMPLE PROGRAM FOR INT DATATYPE
#include<stdio.h> Output
int main() Integer value with positive data: 9
Integer value with negative data: -9
{
Integer value with an unsigned int data: 89
int a = 9; Integer value with an long int data: 99998
int b = -9;
int c = 89U;
long int d = 99998L;
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n", c);
printf("Integer value with an long int data: %ld", d);
return 0;
}
C Program for arithmetic operation
#include <stdio.h>
#include<conio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
getch();
}
C_Pgm_Unit_I 67
C Program for arithmetic operation
#include<stdio.h>
#include<conio.h>
int main()
{
int a = 12, b = 3;
int addition, subtraction, multiplication, division, modulus;

addition = a + b; //addition of 3 and 12


subtraction = a - b; //subtract 3 from 12
multiplication = a * b; //Multiplying both
division = a / b; //dividing 12 by 3 (number of times)
modulus = a % b; //calculation the remainder

printf("Addition of two numbers a, b is : %d\n", addition);


printf("Subtraction of two numbers a, b is : %d\n", subtraction);
printf("Multiplication of two numbers a, b is : %d\n", multiplication);
printf("Division of two numbers a, b is : %d\n", division);
printf("Modulus of two numbers a, b is : %d\n", modulus);
C_Pgm_Unit_I 68
}
C Program for arithmetic operation by getting values
#include <stdio.h>
#include<conio.h>
int main()
{
int a,b, c,d,e,f,g;
Printf(“Enter Two Numbers:\n”);
scanf(“%d%d”, &a, &b);
c = a+b;
printf("a+b = %d \n",c);
d = a-b;
printf("a-b = %d \n",d);
e = a*b;
printf("a*b = %d \n",e);
f = a/b;
printf("a/b = %d \n",f);
g = a%b;
printf("Remainder when a divided by b = %d \n",g);
return 0;
getch(); C_Pgm_Unit_I 69
}
FEATURES OF C PROGRAMMING LANGUAGE
1. Procedural Language:
✓ C program may contain more than one function to perform a particular task.
2. Fast and Efficient:
✓ Languages like java, python offer more features than c programming language
but due to additional processing in these languages, their performance rate gets
down effectively.
✓ C programming language support the programmers to access and manipulate
computer hardware directly, but other higher-level languages do not allow this.
✓ It’s fast because statically typed languages are faster than dynamically typed
languages.
3. Modularity:
✓ The concept of storing C programming language code in the form of libraries
for further future uses are known as modularity.
4. Statically Type:
✓ C programming language is a statically typed language.
✓ Meaning the type of variable is checked at the time of compilation but not at
run time.
✓ This means each time a programmer type a program they have to mention the
type of variables used at the beginning of the program.
5. General Purpose Language:
✓ From system programming to photo editing software, the C programming
language is used in various applications.
✓ Some of the common applications where it’s used are as follows:
✓ Operating systems: Windows, Linux, iOS, Android, etc..
✓ Databases: PostgreSQL, Oracle, MySQL, MS SQL Server etc..
6. Rich set of built-in Operators: It is a diversified language with a rich set of built-
in operators which are used in writing complex or simplified C programs.

7. Libraries with rich Functions: Robust libraries and functions in C help even a
beginner coder to code with ease.

8. Middle-Level Language: As it is a middle-level language so it has the combined


form of both capabilities of assembly language and features of the high-level language.

9. Portability: C language is lavishly portable as programs that are written in C


language can run and compile on any system with either none or small changes.

10. Easy to Extend: Programs written in C language can be extended means when a
program is already written in it then some more features and operations can be added to
it.
Introduction to
GitHub

C_Pgm_Unit_I 74
THANK YOU

C_Pgm_Unit_I 75

You might also like