0% found this document useful (0 votes)
137 views27 pages

Unit 1

Uploaded by

harirathan2008
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)
137 views27 pages

Unit 1

Uploaded by

harirathan2008
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/ 27

VCET 2025 CS25C01 Problem Solving Using C Programming

UNIT 1- INTRODUCTION
SYLLABUS
Evolution of Programming Languages - Programming Paradigms : Structured
programming - Object Oriented programming - Functional programming -Algorithms - Pseudo
code and Flowchart - Structure of C Program -Compilation Process -Preprocessor Directives - C
Tokens.

Evolution of Programming Languages

Programming languages have evolved from procedure-oriented programming to object-oriented


programming.

• First Generation (Machine Language):


This is the most fundamental level, consisting of binary code (0s and 1s) directly understood
by the computer's CPU. Programming at this level is extremely tedious and error-prone,
requiring deep knowledge of the specific machine's architecture.
• Second Generation (Assembly Language):
Introduced in the late 1940s, assembly languages use mnemonic codes (like ADD, MOV) to
represent machine instructions. While still low-level and machine-specific, they offer a
significant improvement in readability and ease of writing compared to raw machine code.
• Third Generation (High-Level Procedural Languages):
Beginning in the mid-1950s with languages like FORTRAN (1957) and COBOL (1959), these
languages introduced abstractions, allowing programmers to write code using more human-
readable syntax and concepts like variables, loops, and functions. This marked a major shift
towards problem-oriented programming, independent of specific hardware. Other notable
languages include ALGOL, BASIC, and C.
• Fourth Generation (Problem-Oriented Languages):
Emerging from the 1970s onwards, these languages focus on specific problem domains, often
with built-in functionalities for tasks like database management (SQL), report generation, or
rapid application development. They aim to reduce programming effort and increase efficiency
for specialized tasks.

• Fifth Generation (Natural Languages & Beyond):


VCET 2025 CS25C01 Problem Solving Using C Programming

While the concept of "fifth-generation languages" often refers to languages aiming for natural
language processing and artificial intelligence (like Prolog), the evolution continues with
paradigms like:
o Object-Oriented Programming (OOP): Languages like Smalltalk, C++, Java, and
Python introduced concepts of objects, classes, inheritance, and polymorphism,
promoting modularity and reusability.
o Functional Programming: Emphasizing immutability and functions as first-class
citizens (e.g., LISP, Haskell), this paradigm focuses on computation as the evaluation
of mathematical functions.
o Concurrent and Parallel Programming: Addressing the need for efficient use of
multi-core processors and distributed systems (e.g., Go, Erlang).
o Modern Languages for Specific Domains: Languages like Python for data science
and AI, JavaScript for web development, Swift and Kotlin for mobile platforms, and
Rust for systems programming focusing on safety and performance.

Introduction to programming paradigms

A programming paradigm is the classification, style or way of programming. It is an approach


to solve problems by using programming languages. Depending on the language, the difficulty of
using a paradigm differs. The programming language „C‟ was developed in the early 1970s by
Dennis Ritchie at Bell Laboratories. Although C was initially developed for writing system
software, today it has become such a popular language that a variety of software programs are
written using this language. The greatest advantage of using C for programming is that it can be
easily used on different types of computers. Many other programming languages such as C++ and
Java are also based on C which means that you will be able to learn them easily in the future.
Today, C is widely used with the UNIX operating system.

Programming Languages

The purpose of using computers is to solve problems, which are difficult to solve
manually. So the computer user must concentrate on the development of good algorithms for
solving problems. After preparing the algorithms, the programmer or user has to concentrate the
programming language which is understandable by the computer.
Computer programming languages are developed with the primary objectives of facilitating a
large number of people to use computer without the need to know the details of internal structure
of the computer.
Structured programming
VCET 2025 CS25C01 Problem Solving Using C Programming

Structured programming in C emphasizes the use of control structures like sequences,


selections (if/else, switch), and iterations (loops) to create clear, maintainable, and efficient
code. It also promotes the decomposition of larger programs into smaller, manageable functions
or modules.
Key aspects of structured programming in C include:
• Modularization:
Breaking down a program into smaller, self-contained functions or modules, each responsible
for a specific task. This improves code organization, reusability, and makes debugging easier.
• Top-down design:
Designing the program from a high-level overview down to the specific details, gradually
refining the solution.
• Use of control structures:
Employing if-else statements for decision-making, switch statements for multi-way branching,
and for, while, and do-while loops for repetitive tasks.
• Avoidance of goto statements:
Structured programming discourages the use of goto statements, as they can lead to spaghetti
code and make program flow difficult to follow.
• Emphasis on readability and maintainability:
Writing code that is easy to understand, modify, and debug by using clear variable names,
comments, and consistent formatting.

Object Oriented Programming


C is primarily a procedural programming language and does not inherently support object-
oriented programming (OOP) features like classes, inheritance, and polymorphism in the same
way languages like C++ or Java do. However, it is possible to simulate or implement aspects of
OOP in C using its existing features.
Simulating OOP in C:
• Encapsulation:
o Structs: C structs can be used to group related data members, representing the
attributes of an object.
o Function Pointers: Member functions can be simulated by using function pointers
within the struct or by passing the struct instance as an argument to functions that
operate on its data. This provides a way to associate behavior with the data.
• Abstraction:
VCET 2025 CS25C01 Problem Solving Using C Programming

o Header Files: Public interfaces can be defined in header files (.h), exposing only the
necessary functions and data structures while hiding the internal implementation details
in source files (.c).
• Polymorphism:
o Function Pointers: Polymorphism can be achieved through function pointers, where
different functions can be assigned to the same function pointer based on the "object's"
type, allowing for different behaviors based on the data.
o Void Pointers and Type Casting: Generic void pointers can be used to handle
different "object" types, with explicit type casting to access specific data or call
appropriate functions.
• Inheritance:
o Struct Composition: Inheritance can be simulated by embedding one struct within
another, allowing the "child" struct to inherit the "parent's" members. This creates a
"has-a" relationship rather than a direct "is-a" relationship like in true OOP languages.

Functional programming
Functional programming paradigms can be applied in C, although C is primarily an
imperative language. This involves adopting certain principles and techniques to write code that
mimics functional characteristics.
Key Concepts
• Immutability:
o Minimize the use of mutable data. Declare variables as const whenever possible to
prevent modification after initialization.
o Instead of modifying existing data structures, create new ones with the updated values.
• Pure Functions:
o Design functions to be "pure," meaning they always produce the same output for the
same input and have no side effects (e.g., modifying global variables, performing I/O).
o This enhances testability and predictability.
• First-Class Functions (Simulated):
o While C doesn't have true first-class functions like functional languages, you can
achieve a similar effect using function pointers.
o Function pointers allow you to pass functions as arguments to other functions, store
them in data structures, and return them from functions.
• Higher-Order Functions (Simulated):
VCET 2025 CS25C01 Problem Solving Using C Programming

o Using function pointers, you can implement higher-order functions in C, which are
functions that take other functions as arguments or return functions. Examples
include map, filter, or reduce operations on data.
• Recursion:
o Embrace recursion as an alternative to loops for iterative processes, especially when
working with data structures like linked lists or trees.
o Be mindful of stack overflow for deep recursion and consider tail recursion
optimization if your compiler supports it.
Algorithm
It is defined as a sequence of instructions that describe a method for solving a problem.
In other words it is a step by step procedure for solving a problem
· Should be written in simple English
· Each and every instruction should be precise and unambiguous.
· Instructions in an algorithm should not be repeated infinitely.
· Algorithm should conclude after a finite number of steps.
· Should have an end point
· Derived results should be obtained only after the algorithm terminates.
Qualities of a good algorithm
The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser
is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem,
some of these may provide more accurate results than others, and such algorithms may be
suitable.
Building Blocks of Algorithm
As algorithm is a part of the blue-print or plan for the computer program. An algorithm is
constructed using following blocks.
· Statements
· States
· Control flow
· Function
Statements
Statements are simple sentences written in algorithm for specific purpose. Statements may
consists of assignment statements, input/output statements, comment statements
Example:
· Read the value of ‘a’ //This is input statement
· Calculate c=a+b //This is assignment statement
VCET 2025 CS25C01 Problem Solving Using C Programming

· Print the value of c // This is output statement


Comment statements are given after // symbol, which is used to tell the purpose of the line.
States
An algorithm is deterministic automation for accomplishing a goal which, given an initial
state, will terminate in a defined end-state.
An algorithm will definitely have start state and end state.
Control Flow
Control flow which is also stated as flow of control, determines what section of code is to
run in program at a given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow
Function
Function is a block of organized, reusable code that is used to perform a single related action.
Function is also named as methods, sub-routines.
Elements of functions:
1. Name for declaration of function
2. Body consisting local declaration and statements
3. Formal parameter
4. Optional result type
Notations of an algorithm
Algorithm can be expressed in many different notations, including Natural Language,Pseudo code,
flowcharts and programming languages.
Natural language tends to be verboseand ambiguous. Pseudocode and flowcharts are represented
through structured human language.
A notation is a system of characters, expressions, graphics or symbols designs used among each others
in problem solving to represent technical facts, created to facilitate the best result for a program
Pseudocode
Pseudocode is an informal high-level description of the operating principle of a
computer program or algorithm. It uses the basic structure of a normal programming language, but is
intended for human reading rather than machine reading. It is text based detail design tool. Pseudo
means false and code refers to instructions written in programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules. The
pseudocode is written in normal English language which cannot be understood by the computer.
Example:
Pseudocode: To find sum of two numbers
READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
VCET 2025 CS25C01 Problem Solving Using C Programming

1. Only one statement per line.


Statements represents single action is written on same line. For example to read the input, all the
inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF, ELSE,ENDIF,
WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
READ name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department, mark1, mark2, mark3
Advantages of Pseudocode
· Can be done easily on a word processor
· Easily modified
· Implements structured concepts well
· It can be written easily
· It can be read and understood easily
· Converting pseudocode to programming language is easy as compared with
flowchart

Disadvantages of Pseudocode
· It is not visual
· There is no standardized style or format
Flowchart
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes,
diamonds, and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Some of the symbols used for flowchart and Example is shown below:
VCET 2025 CS25C01 Problem Solving Using C Programming
VCET 2025 CS25C01 Problem Solving Using C Programming

Rules for drawing flowchart


1. In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
2. The flow chart should be clear, neat and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
3. The usual directions of the flow of a procedure or system is from left to right or top to
bottom.
Only one flow line should come out from a process symbol.
4. Only one flow line should enter a decision symbol, but two or three flow lines, one for
VCET 2025 CS25C01 Problem Solving Using C Programming

each possible answer, cap leave the decision symbol.


5. Only one flow line is used in conjunction with terminal symbol.
6. If flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines.
7. Ensure that flowchart has logical start and stop.
Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for various purposes.
Efficient Coding
The flowcharts act as a guide or blue print during the system analysis and program development
phase.
Systematic Testing and Debugging
The flowchart helps in testing and debugging the program
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part.
Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart
becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require redrawing
completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes problematic.

Structure of a C program

In general, a C program is composed of the following sections:


Section 1: Pre-processor directives
Section 2: Global declarations
Section 3: Functions
Section 1 and 2 are optional, Section 3 is compulsory.
VCET 2025 CS25C01 Problem Solving Using C Programming

Documentation Section
Pre-processor directives
Definition Section and Global declarations
void main()
{
Declaration part
Executable part
}
Sub Program Section
{
Body of the Sub
}
VCET 2025 CS25C01 Problem Solving Using C Programming

Comments:
Comments are used to convey a message and used to increase the readability of a program.
They are not processed by the compiler.

There are two types of comments:


1. Single line comment
2. Multi line comment
VCET 2025 CS25C01 Problem Solving Using C Programming

Single line comment


A single line comment starts with two forward slashes (//) and is automatically terminated with the end
of the line.
E.g. //First C program
Multi-line comment
A multi-line comment starts with /* and terminates with */.A multi-line comment is used when multiple
lines of text are to be commented.
E.g. /* This program is used to find
Area of the Circle */
Section 1.Preprocessor Directive section
 The pre-processor directive section is optional.
 The pre-processor statement begins with # symbol and is also called the pre-processor directive.

 These statements instruct the compiler to include C pre-processors such as header files and symbolic
constants before compiling the C program.
 The pre-processor directive is terminated with a new line character and not with a semicolon.
 They are executed before the compiler compiles the source code.
Some of the pre-processor statements are listed below:
(i)Header files
#include<stdio.h> - to be included to use standard I/O functions : prinf(),scanf()
#include<math.h> -to be included to use mathematical functions :eg)sqrt()
(ii)Symbolic constants
#define PI 3.1412
#define TRUE 1
Section 2: Global declaration Section
This section is used to declare a global variable. These variables are declared before the main() function
as well as user defined functions.
Global variables are variables that are used in more than one function.
Section 3: Function Section
This section is compulsory. This section can have one or more functions. Every program written in C
language must contain main () function. The execution of every C program always begins with the
function main ().
Every function consists of 2 parts
1. Header of the function
2. Body of the function
VCET 2025 CS25C01 Problem Solving Using C Programming

1. Header of the function


The general form of the header of the function is
[return_type] function_name([argument_list])
2. Body of the function
The body of the function consists of a set of statements enclosed within curly brackets commonly
known as braces. The statements are of two types.
1. Non executable statements:

These are declaration statements, which declares the entire variables used. Variable initialization is also
coming under these statements.
2. Executable statements :

Other statements following the declaration statements are used to perform various tasks. For example
printf function call statement.
Non-executable statements are written first and then executable statements are written
E.g. C Program
Line 1: // First C program
Line2: #include<stdio.h>
Line3: main()
Line4: {
Line5 Printf(“Hello”);
Line6 }
Line1 is a comment; Line 2 is a preprocessor directive. Line3 is a header of the function main. Line 4, 5,
6 form the body of main function.
Example Program:
/*Addition of two numbers*/ Documentation Section
#include<stdio.h> Pre-processor directives
#define A 10 Definition Section
int c; Global declarations
int sum(int,int);
main() Main() functions
{
int b;
printf(“Enter the value for B:”);
scanf(“%d”,&b); Execution Part
c=sum(b);
printf(“\n Answer=%d”,c);
getch();
}
int sum(int y)
VCET 2025 CS25C01 Problem Solving Using C Programming

{
c=A+Y; Sub Program
return(c);
}

Compiling a C Program
A sequence of binary instructions consisting of 1 and 0 bits is called as machine code. High-
level programming languages such as C, C++, Java, etc. consist of keywords that are closer to human
languages such as English. Hence, a program written in C (or any other high-level language) needs to be
converted to its equivalent machine code. This process is called compilation.

Note that the machine code is specific to the hardware architecture and the operating system. In
other words, the machine code of a certain C program compiled on a computer with Windows OS will
not be compatible with another computer using Linux OS. Hence, we must use the compiler suitable for
the target OS.
VCET 2025 CS25C01 Problem Solving Using C Programming

C Compilation Process Steps


The compilation process has four different steps −

Preprocessing
Compiling
Assembling

Linking

The following diagram illustrates the compilation process.


VCET 2025 CS25C01 Problem Solving Using C Programming
VCET 2025 CS25C01 Problem Solving Using C Programming

#include <stdio.h>
int main()

{
/* my first program in C */

printf("Hello World! \n");


return 0;

}
Output

Hello World !
The ".c" is a file extension that usually means the file is written in C. The first line is the
preprocessor directive #include that tells the compiler to include the stdio.h header file. The text
inside /* and */ are comments and these are useful for documentation purpose.

The entry point of the program is the main() function. It means the program will start by
executing the statements that are inside this functions block. Here, in the given program code, there are
only two statements: one that will print the sentence "Hello World" on the terminal, and another
statement that tells the program to "return 0" if it exited or ended correctly. So, once we compiled it, if
we run this program we will only see the phrase "Hello World" appearing.
Step 1: Preprocessing

The preprocessor performs the following actions −


It removes all the comments in the source file(s).
It includes the code of the header file(s), which is a file with extension .h which contains C
function declarations and macro definitions.
It replaces all of the macros (fragments of code which have been given a name) by their values.

The output of this step will be stored in a file with a ".i" extension, so here it will be in "main.i".

Compiling

The C compiler checks for valid syntax in C language. If any wrong syntax is found, the compiler
reports that error. After the expanded code has been syntactically verified, the compiler converts it into
assembly code.
VCET 2025 CS25C01 Problem Solving Using C Programming

Output file: hello.s

Assembling

In this stage, the assembler converts assembly code into pure binary code or machine code known as the
object code.

Output file: hello.o

Linking
The linker creates the final executable, in binary. It links object codes of all the source files
together. The linker knows where to look for the function definitions in the static libraries or
the dynamic libraries.
Static libraries are the result of the linker making a copy of all the used library functions to the
executable file. The code in dynamic libraries is not copied entirely, only the name of the library is
placed in the binary file.

The linker merges all the object code from multiple modules and libraries into a single file and produces
the final executable file.

Output file: hello.exe


VCET 2025 CS25C01 Problem Solving Using C Programming

Preprocessors Directives
 Preprocessor is a Macro processor program, that processes the code before it passes through
the compiler. It operates under the control of preprocessor command lines and directives.
 It is not part of the compiler, but is a separate step in the compilation process.
 In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler
to do required pre-processing before actual compilation.
VCET 2025 CS25C01 Problem Solving Using C Programming

 All preprocessor commands begin with a pound symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in first column

Directive Description
#define Substitutes a preprocessor macro
#include Inserts a particular header from
another file
#undef Undefines a preprocessor macro
#ifdef Returns true if this macro is
defined
#ifndef Returns true if this macro is not
defined
#if Tests if a compile time condition
is true
#else The alternative for #if
#elif #else an #if in one statement
#endif Ends preprocessor conditional
#error Prints error message on stderr
#pragma Issues special commands to the
compiler, using a standardized
method

Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use
#definefor constants to increase readability.
These directives tell the CPP to get stdio.h from System Libraries and add the text to the
current source file. The next line tells CPP to get myheader.h from the local directory and add the
content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42 //tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
C Tokens

In C programming, tokens are the smallest units in a program that have meaningful representations.
Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid
expressions and statements. Tokens can be classified into various categories, each with specific roles in
the program.
VCET 2025 CS25C01 Problem Solving Using C Programming

Types of Tokens in C

1. Punctuators
The following special symbols are used in C having some special meaning and thus, cannot be used for
some other purpose. Some of these are listed below:
Brackets[]: Opening and closing brackets are used as array element references. 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.
Comma (, ): It is used to separate more than one statement like for separating parameters in function
calls.
Colon(:): It is an operator that essentially invokes something called an initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That's
why each individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
Assignment operator(=): It is used to assign values and for logical operation validation.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler to
transform your program before actual compilation.
Dot (.): Used to access members of a structure or union.
Tilde(~): Bitwise One's Complement Operator.
VCET 2025 CS25C01 Problem Solving Using C Programming

Example:
#include <stdio.h>

int main() {

// '\n' is a special symbol that


// represents a newline
printf("Hello, \n World!");
return 0;
}
Output
Hello,
World!
2. Keywords
Keywords are reserved words that have predefined meanings in C. These cannot be used as identifiers
(variable names, function names, etc.). Keywords define the structure and behavior of the
program C language supports 32 keywords such as int, for, if, ... etc.
Example:
#include <stdio.h>

int main() {

// 'int' is a keyword used to define


// variable type
int x = 5;
printf("%d", x);

// 'return' is a keyword used to exit


VCET 2025 CS25C01 Problem Solving Using C Programming

// main function
return 0;
}
Output
5
3. 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 and C++.
Examples:

#include <stdio.h>

int main() {

// "Hello, World!" is a string literal


char str[] = "Hello, World!";
printf("%s", str);
return 0;
}
Output
Hello, World!

4. Operators
Operators are symbols that trigger an action when applied to C variables and other objects. The data
items on which operators act are called operands.
Example:
#include <stdio.h>
int main()
VCET 2025 CS25C01 Problem Solving Using C Programming

{
int a = 10, b = 5;

// '+' is an arithmetic operator used


// for addition
int sum = a + b;
printf("%d", sum);
return 0;
}
Output
15
5. Identifiers
Identifiers are names given to variables, functions, arrays, and other user-defined items. They must
begin with a letter (a-z, A-Z) or an underscore (_) and can be followed by letters, digits (0-9), and
underscores.
Example:
#include <stdio.h>

int main() {

// 'num' is an identifier used to name


// a variable
int num = 10;
printf("%d", num);
return 0;
}
Output
10
6. Constants
VCET 2025 CS25C01 Problem Solving Using C Programming

Constants are fixed values used in a C program. These values do not change during the execution of the
program. Constants can be integers, floating-point numbers, characters, or strings.
Example:

#include <stdio.h>

int main() {

// 'MAX_VALUE' is a constant that holds


// a fixed value
const int MAX_VALUE = 100;
printf("%d", MAX_VALUE);
return 0;
}
Output
100
VCET 2025 CS25C01 Problem Solving Using C Programming

You might also like