Introduction To C Programming-Module 1
Introduction To C Programming-Module 1
Introduction to C
Comparison Parameter C Python
The Python programming
The C programming language
language was first worked upon
Developed / Founded by was developed by Dennis M.
by Guido van Rossum and was
Ritchie in 1972.
released in the year 1991.
C is a procedural programming Python is an object oriented
Programming model
language programming language.
C is a middle level language as it Python is a high-level language
binds the bridges between as the translation of Python
Type of language
machine level and high level code takes place into machine
languages. language, using an interpreter.
C is a compiled programming Python is an interpreted
language. Special programs programming language. Special
known as compilers check the C programs known as interpreters
Compilation and Interpretation code line by line and if any check the entire Python code
error is found on any line, the and all the errors in the entire
program compilation stops then Python code is reported at
and there. once.
Comparison Parameter C Python
In Python, variables are
In C, the type of the various untyped, that is, there is no need to
variables must be declared when they define the data type of a variable
Variable Declaration are created, and only values of those while declaring it. A given variable in
particular types must be assigned to Python can store values of different
them. data types in different parts of the
Python code.
Memory management is
Memory management needs to be
Memory Management automatically handled in Python by
done manually in C.
the Garbage Collector provided by it.
• Small size: C has only 32 keywords. This makes it relatively easy to learn
• Quick language: Since C programs make use of operators and data types,
of compilers which use C this way are BitC, Gambit, the Glasgow Haskell
• #include<stdio.h>
• Preprocessor directive : Contains
special instruction that indicate how
to prepare the program for
executable.
3. Definition Section
• All the symbolic
constants are written in
the definition section.
• Macros are known as
symbolic constants.
• #define PI 3.14
4. Global Declaration Section
Global declarations
main() /* execution of a C program begins at this function*/
{
Local declarations /* describe the data that will be used in the function, data is visible only within this function*/
Statements /* statements in a C function are written in a logical sequence to perform a specific task*/
}
Function 1()
{
Local declarations
Statements
}
Function N()
{
Local declarations
Statements
}
int main()
int is the return value of the main function. After all the statements in the program
have been written, the last statement of the program will return an integer value to
the operating system.
For example: \n is used for newlines. The backslash ( \ )causes "escape" (or deviation)
from the normal way the characters are interpreted by the compiler. So instead of the
character ‘n’, the meaning of \n is a newline.
Files Used in C Program
1. Source File
It contains the source code of the program. The file extension of C source
code file is “.c”.
This file contains C source code that defines the main function and maybe
other functions.
The main() is the starting point of execution when you successfully compile
and run the program.
2. Header File
When working with large projects, it is often desirable to make sub-routines and
store them in a different file known as header file.
The advantage of header files can be realized when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those changes
be reflected in all other programs.
Conventionally, header files names ends with a “.h”extension and its name can use
only letters, digits, dashes, and underscores.
Although some standard header files are available in C, but the programmer may
also create his own user defined header files
• It contains a set of predefined functions
• Subroutines: A set of instructions designed to perform a frequently used operation
within a program
3. Object File
Object files are generated by the compiler as a result of processing the source code file.
Linker uses this object file to produce an executable file (.exe file) by combining the of
object files together. Object files have a “.o” extension, although some operating systems
including Windows and MS-DOS have a “.obj” extension for the object file.
4. Binary Executable File
The binary executable file is generated by the linker. The linker links the
various object files to produce a binary file that can be directly executed.
There is different compiler for every individual language; the same linker is used for object file
regardless of the original language in which the new program was written
USING COMMENTS
It helps the reader to understand the code clearly. Comments are just a way of
explaining what a program does. The compiler ignores the comments when forming
the object file. This means that the comments are non-executable statements.
C supports two types of commenting.
// is used to comment a single statement. This is known as a line comment. A line
comment can be placed anywhere on the line and it does not require to be specifically
ended as the end of the line automatically ends the line.
/* is used to comment multiple statements. A /* is ended with */ and all statements
that lie within these characters are commented.
Keywords There are 32 keyword in ANSI C:
• Keywords are the reserved
words in C whose meanings are
fixed by the language.
Keywords cannot be used as variable names. ( E.g. int char = 10; is not allowed in C since char is
keyword)
Identifiers
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
5. Identifiers must not contain white spaces. ( student name is is not valid identifier
whereas student_name is valid)
Student name Student_name
student123
student_ _name Student_123
23_student
%marks
Basic.pay
-HRA
(DA) FIRST
First
&dept_code first
Int
Data Types
Every data used in a C program must have a type associated with it. That is referred to as data type.
Since data is normally stored in variables, we specify the data type of a variable when we declare the variable
name (i.e creating a variable). Hence language has defined a set of DATA TYPES that can be used to declare
variables.
Numeric variables can be used to store either integer values or floating point values.
While an integer value is a whole numbers without a fraction part or decimal point, a
floating point number, can have a decimal point in them. Numeric values may also be
associated with modifiers like short, long, signed and unsigned. By default, C
automatically a numeric variable signed.
Character variables can include any letter from the alphabet or from the ASCII chart and
numbers 0 – 9 that are put between single quotes
Declaring a Variable
Declaring Variable
To declare a variable specify data type of the variable followed by its name.
The data type indicates the kind of data that the variable will store. Variable names
should always be meaningful and must reflect the purpose of their usage in the
program.
Variable declaration always ends with a semicolon.
data_type variable_name;
Example,
int emp_num; float salary; char grade;
double balance_amount;
Initializing a variable
While declaring the variable, we can also initialize them with
some value,
For example,
Application: In Unix/Linux systems, file permissions are often represented using octal notation.
• 0755 (Octal) → 493 (Decimal)
• 7 (Owner: Read, Write, Execute) Convert (345)₈ (Octal) to Decimal:
• 5 (Group: Read, Execute) (3X82) + (4X81 ) + (5X80 )
(345)₈ = (229)₁₀ in decimal.
• 5 (Others: Read, Execute)
c.) Hexadecimal constant (base 16): It is preceded with 0x or oX. It contains
digits from 0-9 and alphabets A through F,
• Each hex digit represents 4 bits ,making it easier to work with binary data.
• Example:
• Binary: 11011010 (Difficult to read)
• Hexadecimal: **DA** (Easier!)
2. Floating point constant
Integers are inadequate to represent quantities such as distance, heights,
temperature, price and so on. These quantities are represented by a number
containing fractional parts like 12.32, 7.34 etc. Such numbers are called floating
point constants.
c = getchar();
printf("Character %c is entered",c);
return 0;
}
Unformatted I/O
2. Writing a character
Function: putchar(variable_name);
#include<stdio.h>
int main()
{
Output:
char c; Enter a character:A
printf("Enter a character:"); Character entered is:A
c = getchar();
printf("Character entered is:");
putchar(c);
return 0;
}
When to Use Unformatted I/O in C Programming
Unformatted I/O functions in C are used when dealing with raw data
without any formatting. These functions read and write data directly as
stored in memory. They are generally used for fast and efficient
input/output operations, particularly when handling characters, strings, or
binary data.
Eg: %.2f
General Syntax:
printf(“Control string", arg1,arg2,arg3,…,argn);
E.g.:
int a = 10,b=5,sum;
sum = a+b; Output:
printf("The sum of %d and %d is %d",a,b,sum); The sum of 10 and 5 is 15
printf("hello world"); ==> hello world
printf(“ "); ==>prints a blank space
printf("\n"); ==>prints a new line
printf("hello\nworld"); ==>hello
world
printf("a=%d \t b=%d",10,5); ==>
a=10 b=5(tab inserted)
Outputting Integers:
General format specification: %wd
w==> Specify minimum field width for the output.
That many(w) spaces is reserved on screen for the data displayed.
"%ld" ==> For long int
"%hd" ==> For short int
Output of Real Numbers
General format specifier
%w.pf or %w.pe (e.g 1.234e3)
w ==> width specification
p ==> precision specification
Default precision is 6.
printf("%f",2.3) ==>2.300000
printf("%.3f",2.3) ==> 2.300
Output of single character
Output of strings
%d reads an integer and stores it in age.
return 0;
}
Area of triangle
#include <stdio.h> •Height h is a variable.
•&h means "address of height".
int main() { •scanf("%f", &h); tells scanf() to
float b, h, area;
store the user's input in the
memory location of height.
printf("Enter the height of the triangle: ");
scanf("%f", &h);
area = (b * h) / 2;
return 0;
}
Square of a Number
#include<stdio.h>
int main()
{
int num, square;
printf("Please Enter any integer Value : ");
scanf("%d", &num);
square = num * num;
printf("Square of %d is = %d", num, square);
return 0;
}
Simple Interest #include <stdio.h>
int main() {
int principal, rate, time, interest;
printf("Enter the principal: ");
scanf("%d", &principal);
printf("Enter the rate: ");
scanf("%d", &rate);
printf("Enter the time: ");
scanf("%d", &time);
interest = (principal * rate * time) / 100;
printf("The Simple Interest is %d\n", interest);
return 0;
}
Compound Interest #include <stdio.h>
#include <math.h>
int main() {
float principal, rate, time, CI;
int main() {
int n;
return 0;
}
Square root of a number
int main() {
int num;
double root;
root = sqrt(num);
• The style of writing programs and the set of capabilities and limitations that a
particular programming language has depends on the programming paradigm it
supports.
These paradigms, in sequence of their
application, can be classified as follows:
# Example Usage
library = Library()
library.register_user("Alice")
library.borrow_book("Alice", "Python Basics")
library.return_book("Alice", "Python Basics")
# Monolithic Library Management System
class Library:
def __init__(self):
self.books = {"Python Basics": 3, "Data
Science": 2, "AI for Beginners": 4}
self.users = {}
3.Top-Down Execution
•The program executes in a sequential manner
Structured programming:
• Structured programming employs a top-down approach in
which the overall program structure is broken down into
separate modules.
def get_numbers():
"""Gets a list of numbers from the user.""" def main():
numbers = list(map(int, input("Enter numbers separated by """Main function to execute the program."""
space: ").split())) numbers = get_numbers()
return numbers print(f"Sum: {calculate_sum(numbers)}")
print(f"Maximum: {find_maximum(numbers)}")
def calculate_sum(numbers): print(f"Minimum: {find_minimum(numbers)}")
"""Calculates the sum of numbers."""
return sum(numbers) # Run the program
if __name__ == "__main__":
def find_maximum(numbers): main()
"""Finds the maximum number."""
return max(numbers)
def find_minimum(numbers):
"""Finds the minimum number."""
return min(numbers)
Why is This Considered Structured Programming?
1.Modularization:
•Functions (get_numbers(), calculate_sum(), find_maximum(), find_minimum()) separate
different tasks.
2.Sequential Execution:
•The main() function calls each function in a structured manner.
3.Decision and Looping Constructs:
•Uses functions, which help maintain clean control flow instead of using goto statements.
Advantages of Structured Programming
Improves code readability and maintainability
Reduces code duplication using functions
Easier debugging and testing
Suitable for both small and large projects
3. Functions that operate on data are tied together with the data.
5. New data and functions can be easily added as and when required
• While constructing the code, the development team checks whether the
software is compatible with the available hardware and other software
components that were mentioned in the Requirements Specification
Document created in the first phase.
4. Testing:
• All the modules are tested together to ensure that the overall system works
well as a whole product.
• Software is tested using a large number of varied inputs also known as test
data to ensure that the software is working as expected by the users’
requirements that were identified in the requirements analysis phase.
5. Software Deployment, Training and Support:
• After testing, the software is deployed in the production environment.
• Software Training and Support is a crucial phase which makes the end users
familiar with how to use the software.
• Moreover, people are often resistant to change and avoid venturing into an
unfamiliar area, so as a part of the deployment phase, it has become very
crucial to have training classes for the users of the software.
6. Maintenance:
• Maintenance and enhancements are ongoing activities which are done to
cope with newly discovered problems or new requirements.
• Such activities may take a long time to complete as the requirement may call
for addition of new code that does not fit the original design or an extra piece
of code required to fix an unforeseen problem.
• As a general rule, if the cost of the maintenance phase exceeds 25% of the
prior-phases cost then it clearly indicates that the overall quality of at least
one prior phase is poor.
• In such cases, it is better to re-build the software (or some modules) before
maintenance cost is out of control.
Algorithms
• An algorithm provides a blueprint to writing a program to solve a particular
problem.
• Be precise
• Be unambiguous
Sequence: Sequence means that each step of the algorithm is executed in the specified order.
Decision: Decision statements are used when the outcome of the process depends on
someconditon. For example, if x=y, then print “EQUAL”. Hence, the general form of the if
construct can be given as if condition then process.
Repetition: Repetition, which involves executing one or more steps for a number of times,
can be implemented using constructs such as while, do-while, and for loops. These loops execute
one or more steps until some condition is true.
Pseudocode:
• Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language.
• It is basically meant for human reading rather than machine reading, so it omits the details that
are not essential for humans. Such details include variable declarations, system-specific code,
and sub-routines.
• Pseudocodes are an outline of a program that can be easily converted into programming
statements.
Pseudocode:
• It is basically meant for human reading rather than machine reading, so it omits
the details that are not essential for humans. Such details include variable
declarations, system-specific code, and sub-routines.
Pseudocode:
• They consist of short English phrases that explain specific tasks within a
program’s algorithm. They should not include keywords in any specific computer
language. The sole purpose of pseudocodes is to enhance human
understandability of the solution.
START
Declare three variables: num1, num2, num3
Print "Enter three numbers" Step-by-Step Algorithm:
Read num1, num2, num3 1.Start
2.Declare three variables: num1, num2, num3
IF num1 > num2 AND num1 > num3 THEN 3.Print "Enter three numbers"
Print "num1 is the largest" 4.Read the values of num1, num2, and num3
ELSE IF num2 > num1 AND num2 > num3 THEN 5.If num1 > num2 AND num1 > num3, then
Print "num2 is the largest"
•Print "num1 is the largest"
ELSE
Print "num3 is the largest"
6.Else if num2 > num1 AND num2 > num3, then
ENDIF •Print "num2 is the largest"
7.Else
STOP •Print "num3 is the largest"
8.Stop
Flowchart:
• Flowchart is a graphical or symbolic representation of a process.
• It is basically used to design and document virtually complex processes to help the viewers to
visualize the logic of the process, so that they can gain a better understanding of the process and
find flaws, bottlenecks, and other less obvious features within it.
• When designing a flowchart, each step in the process is depicted by a different symbol and is
associated with a short description. The symbols in the flowchart are linked together with arrows
• These errors if not removed will either give erroneous output or will not let the compiler to compile
the program.
1. Run-time errors:
• Run-time Errors occur when the program is being run executed.
• Such errors occur when the program performs some illegal operation like
• Run-time errors may terminate program execution, so the code must be written in such a way
that it handles all sorts of unexpected errors rather terminating it unexpectedly.
• This ability to continue operation of a program despite of run-time errors is called robustness.
2. Compile time errors:
• Compile-time Errors occur at the time of compilation of the program.
Syntax Errors: Syntax error is generated when rules of C programming language are
violated. For example, if we write int a: then a syntax error will occur since the correct
statement should be int a;
Semantic Errors: Semantic errors are those errors which may comply with rules of the
programming language but are not meaningful to the compiler. For example, if we write,
a * b = c; it does not seem correct. Rather, if written like c=a*b would have been more
meaningful.
3. Logical errors:
• Logical Errors are errors in the program code that result in unexpected and
undesirable output which is obviously not correct.
• Such errors are not detected by the compiler, and programmers must check
their code line by line or use a debugger to locate and rectify the errors.
• Logical errors occur due to incorrect statements. For example, if you meant to
perform c= a + b; and by mistake you typed c = a * b; then though this
statement is syntactically correct it is logically wrong.
4. Linker errors:
• Linker Errors occur when the linker is not able to find the function definition
for a given prototype.
• For example, if you write clrscr(); but do not include conio.h then a linker
error will be shown.
Testing Approaches
Testing is an activity that is performed to verify correct behavior of a program.
Unit testing is applied only on a single unit or module to ensure whether it exhibits the expected
behavior.
Integration Tests are a logical extension of unit tests. In this test, two units that have already been
tested are combined into a component and the interface between them is tested. This process is
repeated until all the modules are tested together. The main focus of integration testing is to
identify errors that occur when the units are combined.
Testing Approaches
System testing checks the entire system. For example, if our program code
consists of three modules then each of the module is tested individually using
unit tests and then system test is applied to test this entire system as one system.
Debugging Approaches
• Debugging is an activity that includes execution testing and code
correction.
• Once located, errors are then isolated and fixed to produce an error-
free code.
It is the least efficient way of debugging a program and is generally done when
all the other methods fail.
Backtracking Method works by locating the first symptom of error and then trace
backward across the entire source code until the real cause of error is detected.
However, the main drawback of this approach is that with increase in number of
source code lines, the possible backward paths become too large to manage.
If some tests indicate that a particular cause maybe responsible for an error then
the data are refined to isolate the error.