0% found this document useful (0 votes)
13 views164 pages

Introduction To C Programming-Module 1

The document provides a comprehensive overview of the C programming language, including its history, characteristics, and structure. It compares C with Python across various parameters such as programming model, memory management, and variable declaration. Additionally, it outlines the compilation process, data types, and conventions in C programming, emphasizing its applications in system programming and software development.

Uploaded by

lsdslipp
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)
13 views164 pages

Introduction To C Programming-Module 1

The document provides a comprehensive overview of the C programming language, including its history, characteristics, and structure. It compares C with Python across various parameters such as programming model, memory management, and variable declaration. Additionally, it outlines the compilation process, data types, and conventions in C programming, emphasizing its applications in system programming and software development.

Uploaded by

lsdslipp
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/ 164

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.

Pointers C has support for pointers. Python has no support pointers.

In Python, mostly the functional


In C, mostly the functional units are
units are objects as it is an
Functional Units functions as it is a procedural
object oriented programming
programming language.
language.
Comparison Parameter C Python
The C programming language is
Python is a general purpose
Applications mostly used for the development of
programming language
hardware applications.

The number of built-in functions in There are a lot of built-in functions


Built-in functions
C are very limited. in Python.

To use various data structures like It is easier to use Data Structures in


Usage of Data Structures stacks, queues, etc. in C, we need to Python as it provides built in libraries
implement them on our own. for the same.
Python does not allow inline
C allows inline assignment. For
In line assignment. assignment. For instance, a = 5;
instance: int a = 5; runs well in C.
throws an error in python.

Python codes are stored with .py


Type of file C codes are stored with .c extension.
extension.
Introduction to C

• C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories.


• C was initially developed for writing system software
• Today, C has become a popular language and various software programs are
written using this language.
• Many other commonly used programming languages such as C++ and Java
are also based on C.
Characteristics of C
• C is a high level programming language which enables the programmer to
concentrate on the problem and not to worry about the machine code

• Small size: C has only 32 keywords. This makes it relatively easy to learn

• C makes extensive use of function calls


• C is well suited for structured programming. In this
programming approach, where it allows the user to think a
problem in terms of modules where collection of all these
modules make up a complete program.

• Unlike PASCAL it supports loose typing (as a character can


be treated as an integer and vice versa
• Stable language.

• Quick language: Since C programs make use of operators and data types,

they are fast and efficient.

• Facilitates low level (bitwise) programming

• Supports pointers to refer computer memory, array, structures and functions.


Uses of C

• C language is primarily used for system programming. The portability,


efficiency, the ability to access specific hardware addresses and low runtime
demand on system resources makes it a good choice for implementing
operating systems and embedded system applications.

• C has been so widely accepted by professionals that compilers, libraries, and


interpreters of other programming languages are often implemented in C.
• For portability and convenience reasons, C is sometimes used as an
intermediate language by implementations of other languages. Example

of compilers which use C this way are BitC, Gambit, the Glasgow Haskell

Compiler, Squeak, and Vala.

• C is widely used to implement end-user applications


Structure of a C programming
1. Documentation Section
• This section consists of comment lines
which include
➢ The name of the program, the
author and other details like
time and date of writing the
program.
• The Documentation section helps
anyone to get an overview of the
program.
• //
• /*……………….
……………………
……………………. */
2. Link Section
• The link section consists of the
header files of the functions that are
used in the program.
• It provides instructions to the
compiler to link functions from the
system library.

• #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

• The global variables that can be


used anywhere in the program are
declared in the global declaration
section.

• This section also declares the user


defined functions.
5. main() Function Section
• It is necessary to have one main() function
section in every C program.
• This section contains two parts,
1. declaration part (Local declaration)
2. executable part.
• The declaration part declares all the variables
that are used in the executable part.
• These two parts must be written in between the
opening and closing braces { }.
• Each statement in the declaration and executable
part must end with a semicolon (;).
• The execution of program starts at opening
braces and ends at closing braces.
6. Subprogram Section
• The subprogram section contains
all the user defined functions
that are used to perform a
specific task.

• These user defined functions are


called from the main() function
directly or indirectly.
Preprocessor directives /*how to prepare the program for compilation, e.g include, which tells the compiler to execute the program,
some information is needed for the specified header file*/

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.

Printf(“\nWelcome to the world of C”);


The printf function is defined in the stdio.h file and is used to print text on the screen.
The message that has to be displayed on the screen is enclosed within double quotes
and put inside brackets.
The ‘\n’ is an escape sequence and represents a newline character. It is used to print
the message on a new line on the screen.
return 0;
This is a return command that is used to return the value 0 to the operating
system to give an indication that there were no errors during the execution of the
program.
Escape Sequences (Backslash character constants)

Sometimes, it is necessary to use characters which cannot be typed or have special


meaning in C programming. For example: newline (enter), tab etc. In order to use
these characters, escape sequences are used.

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.

Object files contain compact binary code of the function definitions.

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.

On Windows operating system, the executable files have “.exe” extension.


Compiling and Executing a C program
C is compiled language. So once the C program is written, you must run it through a C
compiler.
The source file (human-readable) is first processed with special program called a
Compiler that translate the source code into an object code.
The object code contains the machine instructions for the CPU. However, even the
object file is not an executable file.
Therefore, in the next step the object file is processed with another special program
called a linker. That translates the object file into executable file (machine-readable).
The output of the linker is an executable or runnable file.
Compiling and Executing a C program

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 are case sensitive. i.e.


while and While are not the
same.

• In C, All keywords are of


lowercase.

Keywords cannot be used as variable names. ( E.g. int char = 10; is not allowed in C since char is
keyword)
Identifiers

Names defined by programmers in a program are called Identifiers.


These names can be variable names, function names etc.
E.g.: x, y, sum, add() etc.
Rules for writing an identifier

1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.

2. The first letter of an identifier should be either a letter or an underscore. However,


it is discouraged to start an identifier name with an underscore.

3. There is no rule on the length of an identifier. However, the first 31 characters of


identifiers are discriminated by the compiler.(Depends on the compiler)

4. Cannot use a keyword as an identifier.

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.

E.g: 25 is Integer data type. 2.53 is floating point type etc.

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.

The data type categories supported by ANSI C are:


1. Primary(Fundamental) data types

2. Derived Data types


3. User-defined data types
Primary Data Types

The 5 Primary Data Types are following


The difference between signed and unsigned numeric variable is that signed variables can be
either negative or positive but unsigned variable can be only positive
Variables
A variable is defined as a meaningful name given to the data storage location in computer
memory. When using a variable, we actually refer to address of the memory where the data
is stored. C language supports two basic kinds of 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,

int emp_num = 7; float salary = 5000; char grde =’A’;


Constants
• Constants are fixed values that do not
change during execution of the program.
E.g: 5, 100, “hello”, 14.52, ‘A’, ‘b’

• Constants are used to define fixed values


like PI or the charge on an electron so that
their value does not get changed in the
program even by mistake.
1. Integer Constant
An integer constant is a numeric constant (associated with number) without any
fractional or exponential part.

There are three types of integer constants in C programming:

a) Decimal constant (base 10): It consist of a set of digits, 0 through 9, preceded


by an optional – or + sign.

Eg: 0, -9, 22 etc


b.) Octal constant (base 8): An Integer constant preceded by a zero (0) is an
octal number. It consists of a set of digits, 0 through 7.

Eg: 021, 077, 033 etc.

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,

Eg: 0x7f, 0x2a, 0x521 etc

Compact Representation of Binary Numbers

• 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.

Eg: 0.0000234 // Fractional form

-0.22E-5 // Exponent form: mantissa E exponent Note: E-5 is same as 10-5


3. Character constant
A character constant consists of a single character enclosed in single quotes‘a’, ‘I’
• ‘9’, ‘8’
• ‘@’
• ‘\n’
• Some numeric value associated with each upper and lower case alphabets and decimal
integers are as:
• A------------ Z ASCII value (65-90)
• a-------------z ASCII value (97-122)
• 0-------------9 ASCII value (48-59)
• ; ASCII value (59)
4. String Constant
Set of characters are called string and when sequence of
characters are enclosed within a double quote.
String constant has zero, one or more than one character and
at the end of the string null character(\0) is automatically placed by compiler.
"good" //string constant
"" //null string constant
" " //string constant of six white spaces
"x" //string constant having a single character.
"Earth is round\n" //prints string with newline
Declaring a Constant
To declare a constant, precede the normal variable declaration with
const keyword and assign it a value.
For Eg:
const float pi = 3.14;
The const keyword specifies that the value of pi cannot change.
Another way to designate a constant is to use the pre-processor
command define.
#define PI 3.14159
Rules that need to be applied to a #define statement
Rule 1: Constant names are usually written in capital letter
Rule 2: No blank space are permitted in between # and define
Rule 3: Blank space must be used between #define and constant name
and between constant name and constant value.
Rule 4: #define is a pre-processor compiler directive and not a
statement. Therefore it does not end with semi – colon.
Input and Output(I/O)
Input/Output (I/O) Functions
I/O functions in C are categorized as:

1. Unformatted I/O functions


E.g. getchar(), putchar()

2. Formatted I/O Functions


E.g. scanf(), printf()
Unformatted I/O
1. Reading a character
This means taking character input from the user.
General Syntax:
variable_name = getchar();
E.g.
char c;
c = getchar();
Program: Reading a character
#include<stdio.h>
int main()
{
char c;
Output:
printf("Enter a character:"); Enter a character:A
// getchar function waits for user to type a Character Character A is entered

c = getchar();
printf("Character %c is entered",c);
return 0;
}
Unformatted I/O
2. Writing a character

Outputting a character on to standard output device

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.

When NOT to Use Unformatted I/O


•When formatting output is required (use printf() instead).
•When user input needs validation (use scanf() for formatted input).
•When reading/writing structured text files (e.g., CSV files).
Formatted Input
• Function used for formatted Input: scanf
General format:
scanf("format_specifier", &variable);
Format specifier: Defines the type of data to read.
Address-of operator (&): Required for non-string variables.
• Control string(format string): specifies order in which data to be entered and
the type of the data expected.

E.g: scanf("%d %c %f", &num,&ch,&fno);


int main() {
int age;
float salary;
char name;
printf("Enter your name, age, and salary: ");
scanf("%s %d %f", name, &age, &salary);
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);
return 0;
}
Inputting Integers
• General format of control string: %wd

w ==> Specifies width of the data to read


d ==> Indicated we want to read an integer.

❖E.g. scanf("%5d", &num1)


Reads five digits of user entered number

❖E.g: scanf("%d", &num1)


Read maximum possible digits(value) from the number entered.
int main()
{
int a;
printf("Enter 6 digit number:"); Output:
Enter 6 digit number:678123
scanf("%5d", &a);
The number is: 67812
printf("The number is: %d",a);
return 0;
}
Inputting real number: float and double
types
float a,b,c;
scanf("%f %f %f",&a,&b,&c);

Eg: %.2f

For double data type, control string is "%lf"


Formatted Input: Strings
General format: %ws
E.g: %s , %5s
char str[10];
scanf("%s",str); // Read till first space or \n found
scanf("%5s",str); // Read first 5 characters
Reading Mixed Data Types
int a;
char b;
float c;
scanf("%d %c %f",&a, &b,&c);
Formatted Output
Most used output function: printf()

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.

%f reads a floating-point number and


stores it in height.

The & operator is used to pass the


address of variables to scanf.
Write a c program to print the size of a char, long int, float, long, short,
double and long double
int main() {
printf("size of char: %lu\n", sizeof(char));
printf("size of int: %lu\n", sizeof(int));
printf("size of float: %lu\n", sizeof(float));
printf("size of long: %lu\n", sizeof(long));
printf("size of short: %lu\n", sizeof(short));
printf("size of double: %lu\n", sizeof(double));
printf("size of long double: %lu\n", sizeof(long double));
return 0;
} •The sizeof() operator returns the size of a variable or data type in bytes.
•%lu (unsigned long) is used to display the size returned by sizeof(), ensuring no warning
messages.
•Sizes may vary depending on the compiler and system architecture (32-bit vs 64-bit).
Write a program to explore the printf for all datatypes and print the below output
to monitor (where, c = 'A', bool b = true, f = 3.14, octal = 010, hex = 0x10,
signedint = -10;):
#include <stdio.h>
#include <stdbool.h> // For boolean data type
int main() {
char c = 'A';
bool b = true; // Boolean value (true is 1, false is 0)
float f = 3.14;
int octal = 010; // Octal value (base 8)
int hex = 0x10; // Hexadecimal value (base 16)
int signedInt = -10;
unsigned int unsignedInt = 10;
// Printing values
printf("The c variable contains = %c\n", c);
printf("The b variable contains = %d\n", b); // Boolean prints as integer (1 for true, 0 for false)
printf("The f variable contains = %f\n", f);
printf("The octal variable contains = %o (octal), %d (decimal)\n", octal, octal);
printf("The hex variable contains = %x (hex), %d (decimal)\n", hex, hex);
printf("The signedInt variable contains = %d\n", signedInt);
printf("The unsignedInt variable contains = %u\n", unsignedInt);
return 0;
}
Write a program to print the floating-point numbers
#include <stdio.h>
int main() {
float value1 = 3.14159;
float value2 = 0.000123456789;
float value3 = 123456789.0;
// Printing values with different formats
printf("The float value1 with trailing zeros: %.2f\n", value1);
printf("The float value1 in exponential form (lowercase): %e\n", value1);
printf("The float value1 in exponential form (uppercase): %E\n", value1);
printf("The float value2 with trailing zeros: %.9f\n", value2);
printf("The float value2 in exponential form (lowercase): %e\n", value2);
printf("The float value2 in exponential form (uppercase): %E\n", value2);
printf("The float value3 with trailing zeros: %.9f\n", value3);
printf("The float value3 in exponential form (lowercase): %e\n", value3);
printf("The float value3 in exponential form (uppercase): %E\n", value3);
return 0;
}
Output
The float value1 with trailing zeros: 3.14
The float value1 in exponential form (lowercase): 3.141590e+00
The float value1 in exponential form (uppercase): 3.141590E+00
The float value2 with trailing zeros: 0.000123457
The float value2 in exponential form (lowercase): 1.234568e-04
The float value2 in exponential form (uppercase): 1.234568E-04
The float value3 with trailing zeros: 123456792.000000000
The float value3 in exponential form (lowercase): 1.234568e+08
The float value3 in exponential form (uppercase): 1.234568E+08
Write a program to explore the scanf for all datatypes and print the
below output to monitor (Assume variable c is charater, b is bool, f is
float, octal is octal, hex is hexadecimal number, signedInt is a signed
interger and unsignedInt is unsigned integer):
// Taking input from user
#include <stdio.h> printf("Enter a character: ");
#include <stdbool.h> // For boolean type scanf(" %c", &c); // Space before %c to ignore any newline character
int main() { printf("Enter a boolean (0 for false, any other non-zero value for true): ");
char c; scanf("%d", &b); // Boolean is stored as an integer (0 = false, 1 = true)
bool b; printf("Enter a floating-point number: ");
float f; scanf("%f", &f);
int octal, hex, signedInt; printf("Enter an octal number: ");
unsigned int unsignedInt; scanf("%o", &octal); // Reads octal number
printf("Enter a hex number: ");
scanf("%x", &hex); // Reads hexadecimal number
printf("Enter a signed integer: ");
scanf("%d", &signedInt);

printf("Enter an unsigned integer: ");


scanf("%u", &unsignedInt);
// Printing results
printf("The c variable contains = %c\n", c);
printf("The b variable contains = %d\n", b);
printf("The f variable contains = %f\n", f);
printf("The octal variable contains = %o (octal), %d (decimal)\n", octal, octal);
printf("The hex variable contains = %x (hex), %d (decimal)\n", hex, hex);
printf("The signedInt variable contains = %d\n", signedInt);
printf("The unsignedInt variable contains = %u\n", unsignedInt);

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);

printf("Enter the breadth of the triangle: ");


scanf("%f", &b);

area = (b * h) / 2;

printf("Area of Triangle is: %f", area);

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;

printf("Enter principal: ");


scanf("%f", &principal);

printf("Enter time: ");


scanf("%f", &time);

printf("Enter rate: ");


scanf("%f", &rate);

CI = principal * pow((1 + rate / 100), time);

printf("Compound Interest = %.2f\n", CI);


return 0;
}
Cube of number #include <stdio.h>

int main() {
int n;

printf("Enter a number: ");


scanf("%d", &n);

printf("Cube of %d = %d\n", n, (n * n * n));

return 0;
}
Square root of a number
int main() {
int num;
double root;

printf("Enter any number to find square root: ");


scanf("%d", &num);

root = sqrt(num);

printf("Square root of %d = %.2lf\n", num, root);


return 0;
}
Program: Check the type of character entered

Include header file: #include<ctype.h>


Use functions: isalpha() and isdigit()
#include<stdio.h>
#include<ctype.h>
int main()
{
char c; Output:
printf("Enter a character:"); Enter a character: A
c = getchar(); Entered character is a letter.
if(isalpha(c)!=0) Enter a character:9
printf("Entered character is a letter.\n"); Entered character is a digit.
else if(isdigit(c)!=0) Enter a character:#
printf("Entered character is a digit.\n"); Entered character is not alpha-numeric
else
printf("Entered character is not alpha-numeric\n");
return 0;
}
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.

• 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:

1. Monolithic programming — emphasizes on finding a solution

2. Procedural programming—lays stress on algorithms

3. Structured programming—focuses on modules

4. Object-oriented programming—emphasizes on classes and objects


Monolithic programming:
• Monolithic programming is a style of software
development where an entire application is written as a
single, self-contained unit. In this approach, all
functionalities, such as user interface, business logic, and data
processing, are tightly coupled in a single codebase.
Characteristics of Monolithic Programming:
•A single large codebase
•Functions and components are tightly integrated
•Difficult to scale and maintain as the application grows
•Code changes can affect the entire application
•Typically used for small projects or in early development
stages
def borrow_book(self, name, book):
if name not in self.users:
print("User not registered.")
return def return_book(self, name, book):
if book in self.books and self.books[book] > 0: if name in self.users and book in self.users[name]:
self.books[book] -= 1 self.books[book] += 1
self.users[name].append(book) self.users[name].remove(book)
print(f"{name} borrowed {book}.") print(f"{name} returned {book}.")
else: else:
print("Book not available.") print("Invalid return request.")

# 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 = {}

def register_user(self, name):


if name not in self.users:
self.users[name] = []
print(f"User {name} registered
successfully.")
else:
print("User already registered.")
Why is This Considered Monolithic?
1.Single Codebase: All functionalities (user registration, borrowing,
returning books) are in one class.

2.Tightly Coupled: The library functions are dependent on the users


and books data structures.

3.Difficult to Scale: If we need to add a database or an online interface,


the whole code must be modified.
Monolithic programming:

• Programs written using monolithic


programming languages consist of global
data and sequential code.

• The global data can be accessed and


modified from any part of the program.
Examples are Assembly Language and
BASIC
Procedural programming:
• In procedural languages, a program is divided into subroutines
that can access global data.

• To avoid repetition of code, each subroutine performs a well-


defined task.

• A subroutine that needs the service provided by another


subroutine can call that subroutine.

• Therefore, with ‘jump’,‘ goto’, and ‘call’ instructions, the


sequence of execution of instructions can be altered.

• FORTRAN and COBOL are two popular procedural


programming languages.
Procedural programming is a programming paradigm based on the
concept of procedures (also known as functions or routines). In this
approach, a program is structured as a sequence of step-by-step
instructions, where each procedure performs a specific task.

Key Features of Procedural Programming:


•Uses functions to structure code into reusable blocks
•Follows a top-down approach (executed sequentially)
•Uses local and global variables
•Focuses on procedures rather than objects
# Procedural Student Grade Management System
def find_student(name):
"""Finds and displays a student's grade."""
students = {} # Dictionary to store student names and grades
if name in students:
print(f"{name}'s grade: {students[name]}")
def add_student(name, grade):
else:
"""Adds a student with their grade."""
print(f"Student {name} not found.")
students[name] = grade
print(f"Student {name} added with grade {grade}.")

def display_students(): # Example usage


"""Displays all students and their grades.""" add_student("Alice", 85)
if not students: add_student("Bob", 90)
print("No students found.") display_students()
else: find_student("Alice")
print("\nStudent Grades:") find_student("Charlie") # Student not in list
for name, grade in students.items():
print(f"{name}: {grade}")
Why is This Considered Procedural Programming?
1.Functions Handle Tasks Separately
•add_student(): Adds a student to the dictionary
•display_students(): Prints all students and their grades
•find_student(): Searches for a student's grade

2.No Object-Oriented Concepts


•No classes or objects
•Focuses on functions and data rather than entities

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.

• This allows the code to be loaded into memory more


efficiently and also be reused in other programs.

• Modules are coded separately and once a module is written


and tested individually, it is then integrated with other modules
to form the overall program.

• Structured programming is based on modularization which


groups related statements together into modules
Structured programming is a programming paradigm that emphasizes clear, logical program
structure using control flow constructs like sequence, selection (if-else), and iteration
(loops). It avoids the use of GOTO statements, which were common in earlier unstructured
programming approaches.
Key Principles of Structured Programming:
1.Sequence: Code executes line by line in a structured order.
2.Selection: Uses if-else or switch-case for decision-making.
3.Iteration: Uses loops (for, while) for repetitive tasks.
4.Modularization: Encourages breaking code into functions for reusability.
# Structured Number Analysis Program

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

Disadvantages of Structured Programming


Can become complex for very large applications
Lacks object-oriented features like inheritance and encapsulation
Object-oriented programming (oop)

The object-oriented paradigm is task-based and data-


based. In this paradigm, all the relevant data and tasks are
grouped together in entities known as objects. It treats
data as a critical element in the program development and
restricts its flow freely around the system.
Object-Oriented Programming (OOP) is a programming paradigm based on the
concept of objects. Objects are instances of classes, which encapsulate data
(attributes) and behavior (methods) together. OOP promotes modularity,
reusability, and scalability in software development.
Key Concepts of OOP
1.Class – A blueprint for creating objects.
2.Object – An instance of a class with actual values.
3.Encapsulation – Restricting direct access to object data and modifying it through
methods.
4.Abstraction – Hiding implementation details and exposing only essential features.
5.Inheritance – A class can inherit properties and methods from another class.
6.Polymorphism – A single method can have multiple behaviors based on context.
def withdraw(self, amount):
# Object-Oriented Bank Account System
"""Withdraws money if sufficient balance is available"""
if 0 < amount <= self.__balance:
class BankAccount:
self.__balance -= amount
def __init__(self, account_holder, balance=0):
print(f"Withdrew ${amount}. New balance:
"""Constructor to initialize account holder and balance"""
${self.__balance}")
self.account_holder = account_holder
else:
self.__balance = balance # Private attribute
print("Insufficient funds or invalid amount.")
def deposit(self, amount):
def get_balance(self):
"""Deposits money into the account"""
"""Returns the account balance"""
if amount > 0:
return self.__balance
self.__balance += amount
print(f"Deposited ${amount}. New balance:
# Example usage
${self.__balance}")
account1 = BankAccount("Alice", 500)
else:
account1.deposit(200)
print("Deposit amount must be positive.")
account1.withdraw(100)
print(f"{account1.account_holder}'s balance:
${account1.get_balance()}")
Why is This Considered OOP?

Encapsulation: The __balance attribute is private, ensuring data security.


Class and Object Usage: BankAccount class creates objects like account1.
Methods for Behavior: Functions (deposit(), withdraw(), get_balance()) define
object behavior.
Data Abstraction: The user interacts with account balance through methods
instead of directly modifying attributes.
The striking features of OOP include the following:

1. Programs are data centered.

2. Programs are divided in terms of objects and not procedures.

3. Functions that operate on data are tied together with the data.

4. Data is hidden and not accessible by external functions.

5. New data and functions can be easily added as and when required

6. Follows a bottom-up approach for problem solving


Advantages of OOP
Promotes code reusability through inheritance
Improves scalability for large applications
Enhances data security using encapsulation
Easier to maintain and debug
Disadvantages of OOP
More complex than procedural programming
May have higher memory usage due to object overhead
Design and Implementation of Efficient Programs.

• The design and development of correct, efficient and maintainable


programs depend on the approach adopted by the programmer to perform
various activities that need to be performed during the development
process.

• The entire programs and software development process is divided into a


number of phases.

• This phase is the Software Development Life cycle.


1. Requirement analysis:
• In this phase, user expectations are gathered to know why
the software/program has to be built.

• Then all the gathered requirements are analyzed to frame an


objective.

• The last activity in this phase is to document all the


requirements to avoid any further doubts.

• The functionality, capability, performance, and availability


of hardware and software components are analyzed in this
phase.
2. Design:

• In this phase, a plan of actions is made before the actual


development process could start.

• This plan will be followed throughout the development process.

• The core structure of the software/program is broken down into


modules.

• The solution of the program is then specified for each module in


the form of algorithms, flowcharts, or pseudo codes.
3. Implementation:
• Designed algorithms are converted into program code using any of the
high level languages.

• The choice of language depends on the type of program like whether it is


a system or an application program.

• Program codes are tested by the programmer to ensure their correctness.

• 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.

• Although individual pieces of codes are already tested by the programmers


in the implementation phase, there is always a chance for bugs to creep in
the program when the individual modules are integrated to form the overall
program structure.

• 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.

• It is considered to be an effective procedure for solving a problem in a finite


number of steps.

• A well-defined algorithm always provides an answer, and is guaranteed to


terminate.

• Algorithms are mainly used to achieve software re-use.


Algorithms
• A good algorithm must have the following characteristics

• Be precise

• Be unambiguous

• Not even a single instruction must be repeated infinitely

• After the algorithm gets terminated, the desired result must be


obtained
Control Structures used in Algorithms

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:

• 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.
Pseudocode:

• Pseudocodes are an outline of a program that can be easily converted into


programming statements.

• 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

to show the flow of logic in the process.


TYPES OF ERRORS

• While writing programs, very often we get errors in our program.

• 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

1. Dividing a number by zero

2. Opening a file that already exists

3. Lack of free memory space

4. Finding square or logarithm of negative numbers

• 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.

Such errors can be further classified as follows:

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.

It is specifically carried out with an intent to find errors.

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.

• It is done to locate errors in the program code.

• Once located, errors are then isolated and fixed to produce an error-
free code.

• Different approaches applied for debugging a code includes:


Brute-Force Method: In this technique, a printout of CPU registers and relevant
memory locations is taken, studied, and documented.

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.

Because Elimination lists all possible causes of an error is developed. Then


relevant tests are carried out to eliminate each of them.

If some tests indicate that a particular cause maybe responsible for an error then
the data are refined to isolate the error.

You might also like