Problem Solving Using C Unit-1
Problem Solving Using C Unit-1
• CO1: Understand basic terminology of computers, problem solving, programming Languages and their evolution (Understand)
• CO2: Create specification from problem requirements by asking questions to disambiguate the requirement statement. (Create)
• CO3: Design the solution from specification of a problem and write pseudo code of the algorithm using basic building blocks or
structured programming constructs (Sequence, Selection and Repetition statement). (Create)
• Basics of programming: Approaches to problem solving, Use of high level programming language for systematic development of
programs, Concept of algorithm and flowchart, Concept and role of structured programming.
UNIT-II
• Conditional Program Execution: if, if-else, and nested if-else statements, Switch statements, Use of break and default with switch,
Comparison of switch and if-else.
• Loops and Iteration: for, while and do-while loops, Multiple loop variables, Nested loops, break and continue statement.
• Functions: Introduction, Types, Declaration of a Function, Function calls, Defining functions, Function Prototypes, Passing arguments to
a function Return values and their types, Writing multifunction program, Calling function by value, Recursive functions.
UNIT-III
• Arrays: Array notation and representation, Declaring one-dimensional array, Initializing arrays, Accessing array elements, Manipulating
array elements, Arrays of unknown or varying size, Two-dimensional arrays, Multidimensional arrays.
• Pointers: Introduction, Characteristics, * and & operators, Pointer type declaration and assignment, Pointer arithmetic, Call by reference,
Passing pointers to functions, arrayof pointers, Pointers to functions, Pointer to pointer, Array of pointers.
• Strings: Introduction, Initializing strings, Accessing string elements, Array of strings, Passing strings to functions, String functions.
Syllabus
UNIT-IV
• Structure: Introduction, Initializing, defining and declaring structure, Accessing members, Operations on individual members,
Operations on structures, Structure within structure, Array of structure, Pointers to structure.
• Union: Introduction, Declaring union, Usage of unions, Operations on union. Enumerated data types.
• Dynamic Memory Allocation: Introduction, Library functions – malloc, calloc, realloc and free.
• File Handling: Basics, File types, File operations, File pointer, File opening modes, File handling functions.
Unit-1
Problem Solving is a scientific technique to discover and implement the answer to a problem. The computer is the symbol manipulating device that
follows the set of commands known as program.
Program:
Program is the set of instructions which is run by the computer to perform specific task. The task of developing program is called programming.
Sometimes it is not sufficient just to cope with problems. We have to solve that problems. Most people are involving to solve the problem. These
problem are occur while performing small task or making small decision. So, Here are the some basic steps to solve the problems
Step 1: Identify and Define Problem
Explain you problem clearly as possible as you can.
List out all the solution that you find. Don’t focus on the quality of the solution
Generate the maximum number of solution as you can without considering the quality of the solution
After filtering all the solution, you have the best solution only. Then choose on of the best solution and make a decision to make it as a perfect solution.
After getting the best solution, Implement that solution to solve a problem.
After implementing a best solution, Evaluate how much you solution solve the problem. If your solution will not solve the problem then you can again
start with Step 2.
Algorithm:
Algorithm is the set of rules that define how particular problem can be solved in finite number of steps. Any good algorithm must have following
characteristics
Advantages of Algorithms:
Disadvantage of Algorithms:
1. It is time consuming
2. Difficult to show branching and looping statement
3. Large problems are difficult to implement
Flowchart:
The solution of any problem in picture form is called flowchart. It is the one of the most important technique to depict an algorithm.
Advantage of Flowchart:
1. Easier to understand
2. Helps to understand logic of problem
3. Easy to draw flowchart in any software like MS-Word
4. Complex problem can be represent using less symbols
5. It is the way to documenting any problem
6. Helps in debugging process
Disadvantage of Flowchart:
Solution:
Algorithm:
Step 1: Start
Step 2: Declare a variable x
Step 3: Take a input from user and store in x
Step 4: IF x % 2 == 0 THEN
PRINT Even
ELSE
PRINT Odd
Step 5: End
Flowchart:
What is a Programming Language?
A programming language is a way for people to give instructions to a computer. It uses special words and rules to create programs that tell the
computer what to do. These instructions can make the computer perform tasks like solving problems, playing games, or running apps. Examples of
programming languages are Python, Java, and C++.
There are Two Types of Programming languages:
High-Level Language
Low-Level Language
High-Level Language
A high-level language (HLL) is a human-readable programming language that simplifies coding by hiding complex hardware details, letting
developers focus on logic and functionality.
Designed to make writing code simpler and faster.
Allow developers to build large programs more easily.
Easier to find and fix mistakes.
Can work on different computers with minimal adjustments.
Usually slower in performance compared to machine-oriented languages.
Provide many ready-made features to speed up coding.
Good for beginners and widely used for everyday software.
Examples include JavaScript, Ruby, Swift, and PHP.
Low-Level Language
A low-level language is a machine-oriented programming language that provides minimal abstraction from hardware, offering direct control over
memory and system resources for maximum performance and efficiency.
Provide direct access to the computer’s hardware.
Require detailed knowledge of how a computer works.
Less user-friendly, making programming more challenging.
Harder to find and solve errors in code.
Not easily adapted for use on different hardware.
Used mostly for specific tasks needing high performance or precise control.
Often faster and use fewer system resources.
Examples include Binary code and Assembly languages like MIPS or ARM.
High-Level Language Vs Low-Level Language
The table below shows the key differences between high-level and low-level languages.
Parameters High-Level Language Low-Level Language
Abstraction Level High abstraction, closer to human language Low abstraction, closer to machine code
Ease of Use Easier to learn and use More complex and harder to learn
Portability Highly portable across different systems Less portable, often system-specific
Error Handling Built-in error handling features Limited error handling, requires manual checks
Use Cases Application development, scripting, web development System programming, embedded systems, device drivers
History of C:-
C is a general-purpose high level language that was originally developed at Bell laboratories in 1972, by Dennis M. Ritchie for the Unix operating
system. It was first implemented on the Digital Equipment Corporation PDP-11 computer in 1972.
C programming language features were derived from an earlier language called “B” (Basic Combined Programming Language – BCPL) .
C language was invented for implementing UNIX operating system.
In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming Language” and is commonly known as K&R C.
In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The
resulting definition, the ANSI standard, or “ANSI C”, was completed late 1988.
Many of C’s ideas & principles were derived from the earlier language B, thereby naming this new language “C”.
Features of C Language
The following are the standard features of C Language as follows.
[Link]: Programs written in C language can be run on any compiler with little or no modifications of a program.
#include <stdio.h> int main() { printf("Hello,
World!"); return 0;
}
This simple program will run on Windows, Linux, Mac, or any C compiler.
2. Flexibility: C has 32 keywords and many operators, allowing programmers to control program flow and structure.
#include <stdio.h> int main() { int age = 20; if
(age >= 18) { printf("Eligible to Vote");
} else { printf("Not Eligible");
} return 0;
}
Here if and else (keywords) give us flexibility in decision-making.
• 3. Modularity
Large programs can be broken into smaller modules (functions) → makes code easier to read, debug, and reuse.
#include <stdio.h> void add(int a, int b) { printf("Sum =
%d\n", a + b);
} int main() { add(5, 10); // Calling module (function) return 0;
}
4. Robustness
C has a rich set of built-in functions & operators → helps in writing complex programs reliably.
#include <stdio.h> #include
<math.h> int main() {
double num = 25.0;
printf("Square Root = %.2f", sqrt(num)); // Built-in function return 0;
}
• 5. Extensibility
New features or modules can be added anytime without affecting the existing program. #include <stdio.h> int main() {
printf("Welcome to C!\n");
Structure of a C Program:
1. Documentation Section
2. Link Section
3. Definition Section
- Variable Declaration
- Body of main()
6. Subprogram Section
- User-defined functions
1. Documentation Section
Used to write comments about the program (what it does, author name, date).
/* Program to add two numbers Date: 15 Sept 2025 */
2. Link Section
Used to link header files (library files) for built-in functions.
#include <stdio.h> // For printf, scanf
#include <math.h> // For mathematical functions
3. Definition Section
Used to define constants and macros before the program starts.
#define PI 3.14
#define MAX 100
4. Global Declaration Section
Variables and functions declared here can be used anywhere in the program.
int total; // Global variable
4. { (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two - for every open brace there must be a matching close one.
5. printf("Hello C Language"); printf() is a function defined in
stdio.h.
It is used to print/display text on the screen.
"Hello C Language" is a string constant written inside double quotes.
6. Scanf
The standard input/output library contains a number of functions for formatted data transfer; the two we are going to use are scanf (scan formatted) and
printf (print formatted)
6. return 0;
This ends the main() function and returns 0 to the operating system.
0 usually means the program executed successfully.
If we return some other value, it may indicate an error code.
C Programming Development Cycle
C Programming Development Cycle
1. Write/Edit Source Code
You write the program in C language (e.g., program.c).
You can use an editor like Notepad, VS Code, Code::Blocks, or Turbo C.
Example code: #include <stdio.h> int
main() { printf("Hello, World!"); return 0;
}
• The C compiler (like GCC) converts the human-readable code into machine language.
• It checks for syntax errors (missing semicolon, wrong spelling of keywords, etc.).
• If there are errors, you must correct them before moving on.
3. Syntax Error?
If errors exist → Go back to edit source code and fix them.
If no errors → The compiler produces an object file (e.g., program.o).
4. Linker & Loader
• Linker: Combines your object file with required library functions (like printf, scanf from stdio.h).
• Result → Executable file ([Link] on Windows, [Link] on Linux).ors → The compiler produces an object file (e.g., program.o).
• Example: If program asks for two numbers, you enter them during execution.
6. Logic/Data Errors?
• Sometimes program runs but output is wrong due to mistakes in logic. Example: Writing a - b instead of a + b.
• Sometimes user enters wrong input data (like entering text instead of a number).
• If error found → Go back and fix the source code.
• If no error → Continue.
7. See Output
• The correct result of your program is displayed.
Example:
Hello, World!
1. Every program starts with main()
int main() { //
code return 0;
}
3. Case-sensitive language
Uppercase and lowercase letters are treated differently.
int number = 10; int Number = 20; // Different
variable
6. Comments in C
Used to explain code, ignored by compiler.
// Single-line comment
/* Multi-linecomment */
7. Identifiers (names)
Rules for naming variables, functions, etc.
Must start with a letter or _
Can contain letters, digits, _
❌ No spaces, special characters
int age; float total_marks;
8. Keywords
Reserved words in C (cannot be used as variable names).
Examples: int, float, if, while, return
9. White Spaces
Spaces, tabs, and newlines are ignored by the compiler but used for readability.
int x = 5; // valid int y=10; //
also valid
• Lowercase letters: a to z
• Example:
int Age; // uses uppercase 'A' float rate; // uses
lowercase ‘r’
[Link]
• Numbers 0 to 9
3. Special Characters
These are symbols that have special meaning in C.
Some examples:
+ - * / = < > % & # ^ ! | ~ ? : ; , . _ ( ) { } [ ] " " ' ' \ printf("Hello, World!\n"); // uses " , , ; ,
( ) , \n
4. White Spaces
• Blank space, tab, newline.
Examples:
\n → new line
\t → tab space
\\ → backslash
\" → double quote printf("Hello\nWorld"); // prints Hello in one line, World in next line
C TOKENS
C programs contain many elements which are identified by the compiler, are known as tokens. Just like English sentences are made of words, a C
program is made of tokens. Example:
int age = 20;
Here:
int → keyword age →
identifier = → operator
20 → constant
; → special symbol
All of these are tokens.
1) Keywords
2) Identifiers
3) Variables
4) Constants
5) Special symbols
6) Operators
Tokens can be categorized as,
1. Keywords
A keyword is a reserved word. All keywords have fixed meaning that means we cannot change. C keywords are the words that convey a special
meaning to the c compiler. The keywords cannot be used as variable names, constant name.
A list of 32 keywords in c language is given below:
2. IDENTIFIERS
In C language identifiers are the names, which are given to variables, user-defined functions and arrays.
Syntax Rules:
1. An identifier should only have alphanumeric characters (a-z, A-Z, 0-9) and underscore (_) symbol.
2. The first character of an identifier should only have alphabets (a-z, A-Z) or underscore (_) symbol.
3. Identifiers are case sensitive in C language. For example, “name” and “Name”are two different identifiers in C language.
5. Special characters (Ex: ;, ., white spaces, slash etc.,) are not permitted to use as identifiers.
Example:
int age; // "age" is an identifier float salary; //
"salary" is an identifier
3. Variables
A variable is a name that is used to store a value. Variable are simply names used to refer some locations in memory i.e. a location that holds a
value Variable declaration:
Declaration of variable must be done before they are used in the program. It dones three things:
• It tells the compiler what the variable name it is.
1. All variables must be declared before they can be appeared in executable statements.
5. Variable names can consists of alphabets, digits and only permitted special symbol underscore (_).
4. Constants
C Constants are like normal variables. But, only difference is their values cannot be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals.
Constants may be belonging to any of the data type.
1. Numeric Constant Integer constants:
Integer constants are whole numbers (without a decimal point). They can be positive, negative, or zero.
They can be written in three number systems:
• Hexadecimal (Base 16): Begins with 0x or 0X, digits 0–9 and letters A–F Examples: int a = 10; // Decimal constant
int b = -9; // Decimal constant int c = 021; // Octal constant (17 in decimal) int d = 0x7F; // Hexadecimal constant
(127 in decimal)
Real Constants (Floating-point):
Numbers that have a fractional (decimal) part or are written in exponential notation.
6. Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
There are following assignment operators supported by C language:
Operators
7. INCREMENT AND DECREMENT OPERATOR
These operators are used to increment or decrement by 1 in an expression.
#include<stdio.h> void main()
{
int i = 1; printf("%d %d %d", i, ++i, i++);
}
Output : 3 3 1
Postfix and Prefix Expression in Same Statement
#include<stdio.h>
#include<conio.h>
void main() {
int i = 0, j = 0;
j = i++ + ++i;
printf("%d\n", i);
printf("%d\n", j);
}
Output :
2
2
Derived Data Types: The data types which derived from fundamental or primitive data types is known as derived data
types. For example, arrays, functions, structures and unions etc.
Void Data Type: void data type means “no values” (or) “empty” i.e. it take or returns empty value. The void data type usually
used with functions to specify its return type or with parameters list.
Enumerated Data Type:
Enumerated data type consists of named integer constants as a list.
It starts with zero by default and increments by one for the sequential identities in the list.
Syntax: enum identifier{enumerators_list};
Example: enum month{ jan, feb, march};
Variable:-
A variable is a name of memory location. It is used to store data. Variables are changeable,
we can change value of a variable during execution of a program. . It can be reused many times.
Note: Variable are nothing but identifiers.
Rules to write variable names:
2. A variable name includes alphabets and numbers, but it must startwith an alphabet.
1. Local Variables
A local variable is declared inside a function or block (like inside { }).
It is created when the function is called and destroyed when the function ends.
Scope → only inside that function/block.
Lifetime → exists only while the function is running.
Default value → garbage (random value) until initialized.
1. Local Variables #include <stdio.h>
void test() {
int a = 10; // local variable printf("Local variable a = %d\n", a);
} int main() {
test();
// printf("%d", a); // ❌ Error: 'a' not available here return 0;
}
2. Global Variables
A global variable is declared outside all functions.
It can be accessed by any function in the program.
Scope → available throughout the program.
Lifetime → exists as long as the program runs.
Default value → 0 if not initialized.
ALGORITHM
An algorithm is a description of a procedure which terminates with a result. Algorithm is a step-by-step method of solving a problem.
Properties of an Algorithm:
5) Effectiveness: - It consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in
a finite amount of time.
ALGORITHM
Example
Q. Write a algorithem to find out number is odd or even?
step 1 : start step 2 : inputnumber step 3 : rem=number mod 2 step 4 : if
rem=0then print "number even" else print "number odd" endif step 5 :stop
FLOWCHART
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing program and explaining program to others. Symbols
Used In Flowchart Different symbols are used for different states in flowchart,
Draw a flowchart to add two numbers entered by user.
Input-Output in C
Output Functions
Types of Expressions in C
There are four types of Expressions in C programming:
1. Arithmetic Expression
2. Relational Expression
3. Logical Expression
4. Conditional Expression
1. Arithmetic Expression in C
An arithmetic expression consists of operands and arithmetic operators. It performs computations on the int, float, or double type values.
Arithmetic operations can be performed in a single line of code or multiple lines combined with arithmetic operations such
as addition, subtraction, multiplication, and division.
The following types of arithmetic expressions are there:
integer expression - an expression containing only integral operands,
real expression - an expression containing only real operands
mixed mode expression - an expression containing both integral and real operands
The arithmetic expression makes it easier to calculate computationally intensive tasks by programming each operation step-by-step.
The precedence and associativity of operators decide the order of the evaluation of individual operations.
Type of results after evaluation of an arithmetic expression:
When both the operands are of integer type, the result of the operation would be an integer value. The fractional part of the result is
ignored.
When both the operands are of float data type, the result of the operation would be a real value.
If one operand is of type integer and another of type real, the first operand is converted into a real operand, and then the operation is
performed, producing a real value as the result.
Example
Evaluation of expression Description of each operation
2. Relational Expression in C
Relational expressions use comparison operators such as '>' (greater than) and '<' (less than) to compare two operands. The result of the
comparison is a boolean value i.e. 0(false) or non-zero (true).
It is a condition that decides whether the action should be taken or not. Relational expressions are used in decision-making
statements and looping statements in the C language.
Relational
Description
Expression
The given condition checks whether the x is an even number or not. This relational
x%2 = = 0
expression shows the result as the value 1 if x is an even number otherwise as the value 0
This relational expression is used to check if a is not equal to b and it results in 1 if a is not
a!=b
equal to b otherwise 0.
a+b = = x+y It is used to check if this particular expression "a+b" is equal to the expression "x+y"
Example
#include <stdio.h>
int main()
{
int x = 5, y = 10;
if (x == y) {
printf("x is equal to y\n");
} else {
printf("x is not equal to y\n");
}
return 0;
}
Run Code >>
The above code in C Compiler checks if x is equal to y or not
Output
x is not equal to y
3. Logical Expression in C
Logical expressions in C are a powerful tool for controlling the logic of the flow of the program. They are made by combining as many relational
expressions as the programmer wants. It then determines if certain statements or groups of statements should be executed or not.
Logical
Description
Expressions
( x > 4 ) && ( x < This logical expression is used as a test condition to check if the x is greater than 4 and the
6) x is less than 6. The result of the condition is true only when both conditions are true.
This logical expression is used as a test condition to check if x is greater than 10 or y is less
x > 10 || y <11
than 11. The result of the test condition is true if either of the conditions holds true value.
! ( x > 10 ) && ( y This logical expression is used as a test condition to check if x is not greater than 10 and y is
==2) equal to 2. The result of the condition is true if both the conditions are true
Example
#include <stdio.h>
int main()
{
int x = 10;
int y = 2;
if ( (x >10) || (y<5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Run Code >>
OUTPUT
Condition is true
4. Conditional Expression in C
The conditional expression consists of three operands. It returns 1 if the condition is true otherwise 0. We had seen the conditional operator in
the section, Operators in C. We will look at ternary operators in detail in the section Ternary Operator in C.
Example
#include <stdio.h>
#include <string.h>
int main()
{
int age = 29;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0; }
Run Code >>
Output
Married