Unit 1 (Notes)
Unit 1 (Notes)
What is a Program?
A program is a set of instructions that are executed by the computer to perform a particular
task.
Programs are written using programming languages such as C, C++, JAVA, PYTHON
and are executed by the computer.
What is a Programming?
The process of writing, testing and maintaining those instructions.
2. Information Gathering:
To solve many problems, we need to gather or collect relevant data, information, facts
and resources about the problem so that it can help in understanding the problem better.
3. Creative Thinking:
Solving problems often require creative thinking to come up with new and innovative
solutions.
4. Decision Making:
When there are multiple solutions to a given problem, we need to find the pros
(advantages) and cons (disadvantages) of all solutions and then make a decision to pick
the best solution. Selecting the most effective and practical solution from the options
available.
5. Algorithm Design:
Develop a clear and efficient algorithm to solve the problem.
6. Test Cases:
A test case is set of actions that can be done on different inputs given to the
problem and test how the output is generated, works correctly or not for the given
input.
Test cases are specific conditions or sets of inputs used to test whether a software
application or system behaves as expected.
Phases of Problem Solving:
1. Problem Definition:
Before solving any problem, first we need to know the exact nature of the problem or
understand what the problem is?
We need to extract the problem statement (identifying and clearly defining the exact
problem). If the problem statement isn’t specified correctly, then we don’t know where
to begin from? to resolve the problem, which will result in wrong solution.
5. Implementation:
This phase involves coding (writing programs using a programming language like C).
6. Testing:
We should test whether our solution to a problem is correct or not by providing
different inputs and getting the outputs or results correctly.
Problem solving Strategies:
Number of strategies can be applied in computer science field to solve the problem and
measure how efficiently the solution is working. Probably the most and widely used
strategy is top-down approach (Divide and Conquer).
Bottom-Up approach:
This is the exact opposite of the Divide and Conquer approach (top-down approach).
In this approach, we begin by solving smaller or sub-problems first and then we
integrate or combine these small sub-problems to find the solution to the large problem
or the original problem.
Top-Down Approach:
Top-Down approach of solving a problem can be implemented by using the following
steps:
3. Construction of loops:
→ A looping construct is a programming structure that allows tasks to be repeated a
specific number of times or until a certain condition is met.
→ Many problems that need to solved requires loops in programming, so we have to
use or construct loop to solve the problem.
→ For example, to create a sequence of numbers such as 1, 2, 3, 4, 5 ........or to generate
even numbers like 2, 4, 6, 8, 10..... , we need to use the idea of loops to solve these
types of problems.
Algorithm Designing:
When designing an algorithm, it is important to be very careful and consider the following
factors.
Flowchart:
A flowchart is a graphical / diagrammatic used to represent an algorithm, that visually
explains about the process or workflow using standardized symbols and definitions.
Flowchart symbols:
Terminal (Oval):
An oval in a flowchart represents the terminal. It is used to represent the start or end of
a process / sequence. It is used to show the beginning or the termination point of the
flowchart.
Input/Output (Parallelogram):
The parallelogram represents data input to or output from the process. It is used to show
the way it takes input (e.g., user input, data entry) or give output (e.g., displaying results,
printing).
Process (Rectangle):
The rectangle represents a process or action step in the flowchart. It is used to show any
step in the process, such as calculations, data processing, or other tasks.
Decision Making (Rhombus/Diamond):
The diamond represents a decision point or a conditional branch. It is used to indicate
that a choice must be made between different paths based on certain conditions or
criteria.
Flowline (Arrow):
The arrow represents the direction of flow from one step to the next step. Connects
symbols to show the sequence of steps.
Flowchart:
start
stop
2. Write an algorithm and flowchart to perform the addition of two numbers.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare num1, num2 and add.
Step3: input/read num1 and num2. // Input
Step4: add = num1 + num2 // Process
Step5: display the result (add). // Output
Step6: stop algorithm
Flowchart:
start
declare num1,
num2 & add
input/read num1,
num2
print/display add
stop
3. Write an algorithm and flowchart to find area of rectangle.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare length, breadth and area.
Step3: input/read length and breadth. // Input
Step4: area = length * breadth // Process
Step5: display the result (area). // Output
Step6: stop algorithm
Flowchart:
start
declare length,
breadth and area
input/read length
and breadth
print/display area
stop
4. Write an algorithm and flowchart to find area of circle.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare pi, radius and area.
Step3: input/read pi and radius. // Input
Step4: area = pi * radius *radius // Process
Step5: display the result (area). // Output
Step6: stop algorithm
Flowchart:
start
input/read pi and
radius
print/display area
stop
5. Write an algorithm and flowchart to check whether the given number is even or odd.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare num.
Step3: input/read num.
Step4: check num%2==0
print “even number”
Step5: otherwise
print “odd number”
Step6: stop algorithm
Flowchart:
start
declare num
input/read num
check NO
num%2==
0
YES
stop
6. Write an algorithm and flowchart to check whether the given year is leap year or not.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare year.
Step3: input/read year.
Step4: check year%4==0
print “leap year”
Step5: otherwise
print “not leap year”
Step6: stop algorithm
Flowchart:
start
declare year
input/read year
check NO
year%4==0
YES
stop
7. Write an algorithm and flowchart to find largest among the two numbers.
Sol:
Algorithm:
Step1: start algorithm
Step2: declare num1 and num2.
Step3: input/read num1 and num2.
Step4: check num1>num2
print “num1 is greater”
Step5: otherwise
print “num2 is greater”
Step6: stop algorithm
Flowchart:
start
Check NO
num1>num
2
YES
stop
Introduction of C programming:
C programming is a general-purpose, procedural programming language was developed
by Dennis M. Ritchie in the year 1972 at the location bell laboratories (AT &T - American
Telephone and Telegraph) labs.
Structure of C Program:
→The structure of the C program is divided into several key components and elements
which makes it easy to read, modify, document and understand how well a C program
is organized.
→C program is a collection of one or more functions.
→Every function is a collection of statements that performs some specific tasks.
1. Documentation (Comments):
→ Comments are used for documentation and clarification.
→ In any C program, comments won’t be considered for compilation and execution.
→ C supports both the single-line comments (//) & the multi-line comments (/* ... */).
2. Preprocessor Directives:
→Preprocessor directives in C are the commands used by the preprocessor, that tell
the compiler to process the source code before beginning the actual compilation
process. All the preprocessor directives begin with a ‘#’ (hash) symbol. The
commonly used preprocessor directives are #include and #define.
#include is used for including header file in the source code program.
Example:
#include<stdio.h>: It is used to include contents of the standard input/output (I/O)
library header file “stdio.h” in a c program. The functions like printf(), scanf(),
fprintf(), fscanf(), fgets(), fputs() allows you to perform input and output operations in
your C program.
Syntax:
#define macro_name value
Example:
#define PI 3.14159
Here, PI is a symbolic constant that represents the value of pi (3.14159). Once defined,
the value of PI cannot be changed during program execution.
Note: Remember that the # symbol only provides a path to the preprocessor.
4. main( ) function:
→ Every C program must have one main( ) function, where program execution begins.
→ Statements in the main( ) function are executed one by one.
→ Statements typically end with a semicolon (;).
Note:
void main( ) tells the compiler that the program will not return any value.
int main( ) tells the compiler that the program will return an integer value.
int main()
{
printf("%d\n", a); // Print the value of the constant 'a'
display(); // Function Call
return 0; // return 0 to indicate successful execution
}
// Function Definition
void display()
{
printf("Learning C Programming");
}
Elements in C:
→ Every programming language has some basic elements and grammatical rules.
→ Before understanding the programming, a programmer must to know the basic
elements of C language.
→The basic elements in C are Character Set, Identifiers, Keywords (Reserved Words),
Datatypes, Variables, Constants, Operators, Expressions, Statements and so on, all
these are used to construct a C program.
Note: In the C programming language, C Tokens are the smallest individual units in
the source code. C Tokens are used to represent the various elements of a program.
1. C Character Set:
→ In C programming, a character set refers to the collection of valid characters that
can be used to write source code.
→ These characters include alphabets, digits, special symbols, whitespace and escape
sequence character.
Note:
→ Semicolon (;) is used to terminate statements in C.
→ Comma (,) is used to separate multiple statements.
→ Braces{ } is used to define block of code and to enclose the body of functions, loops
and conditional statements.
→ Parentheses ( ) is used for function calls and function parameters.
→ Quotes ' and " is used to define character (') and string literals (").
3. C Identifiers:
→ Identifiers are user-defined names given to program elements such as variables,
arrays, functions, structures, etc. They make the code more readable and
manageable.
4. C Data Types:
→ A data type defines the type and size of data that a variable can store.
void: The void data type has no values and no operations, used in functions and
pointers.
Key Point: In standard C, sizeof(void) is invalid and results in a compilation error
because void is an incomplete type. Some modern compilers may allow it as an
extension and return 1 byte, but this is non-standard behaviour.
int: An Integer data type is used to store numbers (positive, negative, or zero)
without fraction part.
Size: 2 bytes (16 bits) or 4 bytes (32 bits)
Example: 10, -25, 0
float: The float data type is used to store decimal values (fractional numbers).
Size: 4 bytes (32 bits)
Example: 3.14, -0.001, 2.71828
double: The double data type is used to store decimal values with higher precision
than float.
Size: 8 bytes (64 bits)
Example: 3.14159265358979, -0.0000001, 3.579e-13 (3.579*10-13)
Example1: C program to display size of data types.
Code:
#include<stdio.h>
int main()
{
printf("Size of char: %zu byte\n", sizeof(char));
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of double: %zu bytes\n", sizeof(double));
return 0;
}
Note: The sizeof operator in C is used to find the size (in bytes) of a data type or
variable. It’s very useful for beginners to understand how much memory each type
takes.
→ Sign Qualifiers: These are signed and unsigned. When the unsigned qualifier is
used, the number is always positive. When signed qualifier is used, the number can
be either positive or negative. If no sign qualifier is mentioned, by default, the signed
qualifier is assumed.
The following table describes about datatype with type qualifiers, format
specifiers, size and range:
Size(bytes)
With Type Format
Datatype on Range
Qualifiers Specifier
64-bit
char %c 1 byte -128 to 127
char signed char %c, %hhd 1 byte -128 to 127
unsigned char %c, %hhu 1 byte 0 to 255
signed short int
%hd 2 bytes -32768 to 32767
or short int
unsigned short int %hu 2 bytes 0 to 65535
-2,147,483,648 to
signed int or int %d 4 bytes 2,147,483,647
int
unsigned int %u 4 bytes 0 to 4,294,967,295
signed long int or -2,147,483,648 to
%ld 4 bytes
long int 2,147,483,647
unsigned long int %lu 4 bytes 0 to 4,294,967,295
1.2E-38 to
float float %f 4 bytes
3.4E+38
2.3E-308 to
double %lf 8 bytes 1.7E+308
double
3.4E-4932 to
long double %Lf 16 bytes
1.1E+4932
5. C Variables:
→ In C programming, a variable is a named memory location used to store data that
your program can manipulate. Each variable has a type, which determines what kind
of data it can hold (like integers, floating-point numbers, or characters).
Variable Declaration: Before using a variable, you must declare it by specifying its
data type and name.
Syntax: datatype variable_name;
or
datatype variable_name1, variable_name2, variable_nameN;
Example:
int width, height;
char grade;
float area;
double salary;
Note: If you try to print a local variable without initializing it, it will show a garbage
value (random numbers or characters from memory).
Variable Initialization: Assigning an initial value to a variable at the time of
declaration.
Example:
int n = 5;
int x = 10, y = 20, z = 30;
char grade = ‘A’;
float age = 34.5;
double salary = 96570.75;
double num = 0.15197e-7;
Types of Constants in C:
Char Constants:
→ A single character enclosed in single quotes.
Example: 'A', '1', '\n'
Integer Constants:
→Whole numbers without a fractional part.
→Can be written in different number systems.
Binary (base2):
Prefix: 0b or 0B
Digits allowed: 0 and 1 only
Example:
int bin = 0b1010;
Octal (base 8):
Prefix: 0 (zero at the beginning)
Digits allowed: 0–7
Example:
int oct = 021;
1. Fractional form
→ A number with a decimal point.
Examples:
0.5, 5.3, -4000.0, 0.0073, -5597.0, 39.0807, 735.0
Suffix Type
f or F float
l or L long double
none double (default)
Some examples of string constants are: "C Programming", "59.7", "8", " ", "A"
Note: "A" and 'A' are different, the first one is a string constant which consists of
character A. While the second one is a character constant which represents integer
value 65.
Types of Operators in C:
1. Arithmetic operators
2. Relational operators
3. Assignment operators
4. Logical operators
5. Bitwise operators
6. Conditional operator
7. Comma operator
8. sizeof operator
9. Increment and Decrement operators
1. Arithmetic Operators
→ Arithmetic operators are used to perform mathematical calculation.
2. Relational Operators:
→ Compare two values and return 1 (true) or 0 (false).
4. Logical Operators:
→ Operate on Boolean values (true / false).
Example2:
#include<stdio.h>
int main()
{
int a = 15, b = 15, c = 20, res1, res2;
res1 = (a==b)||(c>b)&&(a<b);
printf("%d\n", res1);
res2 = (a!=b)&&(c<=b)||(a>b);
printf("%d\n", res2);
return 0;
}
5. Bitwise Operators:
→ Operate on individual bits of integers.
Explanation:
a = 12 // 12 integer value converted into binary value 00001100
b = 25 // 25 integer value converted into binary value 00011001
00001000 // 8
a | b means 00001100
00011001
00011101 // 29
a ^ b means 00001100
00011001
00010101 // 21
Example1:
#include<stdio.h>
int main()
{
int a=10, b=20;
int max;
max=(a>b)? a:b; // if a > b, max = a; else max = b
printf("Maximum = %d\n", max);
return 0;
}
Example2:
#include<stdio.h>
int main()
{
int a = 29, b = 15, result;
result = (a==b)? (a+b) : (a-b);
printf("result = %d", result);
return 0;
}
Example3:
#include<stdio.h>
int main()
{
int num1, num2;
printf("Enter Num1 & Num2:");
scanf("%d %d", &num1, &num2);
(num1>num2)? printf("%d is Largest", num1) : printf("%d is Largest", num2);
return 0;
}
7. Comma Operator:
→ The comma operator (,) is used to separate expressions in various contexts.
→ It evaluates each of its operands (from left to right) and returns the value of the
rightmost operand.
→ The comma operator has the lowest precedence among C operators.
8. sizeof Operator:
→ The sizeof operator is used to determine the size, in bytes, of a data type or a
variable.
Syntax: sizeof(type);
Or
sizeof(expression);
Example:
#include<stdio.h>
int main()
{
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of char: %zu bytes\n", sizeof(char));
return 0;
}
Example2:
#include<stdio.h>
int main()
{
int x=5, y;
y = --x;
printf("x=%d\ty=%d", x, y);
return 0;
}
Explanation:
Here first the value of variable x is decrement then the new value is used in the
operation.
Initially x = 5
x=x-1
x=5-1
x=4
Then, the value of x is assigned to y.
y=x
y=4
Hence now value of x is 4 and value of y is 4.
Example3:
#include<stdio.h>
int main()
{
int x=5, y;
y = x++;
printf("x=%d\ty=%d", x, y);
return 0;
}
Explanation:
Here first the value of variable x is used in the operation and then increment is
performed.
Initially x = 5
First, the value of x is assigned to y.
y=x
Then x is incremented,
x=x+1
x=5+1
Hence now value of x is 6 and value of y is 5.
Example4:
#include<stdio.h>
int main()
{
int x=5, y;
y = x--;
printf("x=%d\ty=%d", x, y);
return 0;
}
Explanation:
Here first the value of variable x is used in the operation and then decrement is
performed.
Initially x = 5
First, the value of x is assigned to y.
y=x
Then x is decrement,
x=x-1
x=5-1
Hence now value of x is 4 and value of y is 5.
Type Conversion (type casting) in C:
→ Converting the value of one data type to another data type is known as type
conversion.
→ For example, if you try to divide two integers, 5 by 2, you would expect the result to
be 2.5. But since we are working with integers (and not floating-point values), the
following example will just output 2:
int x = 5;
int y = 2;
int sum = 5 / 2;
printf("%d", sum); // Outputs 2
→ To get the right result, you need to know how type conversion works.
Example1:
If you assign an int value to a float type:
#include<stdio.h>
int main()
{
float a = 50; // Automatic conversion: int to float
printf("%f", a); // 50.000000
return 0;
}
Example2:
#include<stdio.h>
int main()
{
int a = 10;
float b = 4.7;
float result = a + b; // 'a' (int) is implicitly converted to 'float'
printf("%.2f", result); // 14.70 is result
return 0;
}
Example3:
#include<stdio.h>
int main()
{
char a = 10;
short b = 20;
int result = a + b; // 'a', 'b' is implicitly converted to 'int' before the addition.
printf("%d", result); // 30
return 0;
}
Example4:
#include<stdio.h>
int main()
{
double value = 41.25e1;
printf("Double Value: %.2lf\n", value);
int number = value;
printf("Integer Value: %d", number);
return 0;
}
Example2:
#include<stdio.h>
int main()
{
float x = 9.99;
int y = (int)x; // Convert float to int, truncating the decimal part.
printf("%d", y); // Output: 9
return 0;
}
Example3:
#include<stdio.h>
int main()
{
char c = 'A';
int asciiValue = (int)c; // Convert char to int to get its ASCII value.
printf("%d", asciiValue); // Output: 65
return 0;
}
Note:
→ When converting from higher data type to lower data type, there will be data loss.
Example:
long double type is converted to double type; long double type is converted to int
type.
→ When converting from lower data type to higher data type, there will be no data
loss.
Example:
If char is converted to int, int is converted to float.
Expression Evaluation:
→ For evaluation of expressions having more than one operator, there are certain
operator precedence and associativity rules defined in C.
→The operator precedence determines which operator is executed first if there is more
than one operator in an expression.
→ The associativity determines the direction in which an expression is evaluated.
Input (scanf):
→ Used to read data from user (keyboard → memory).
→ Defined in <stdio.h>.
Syntax:
scanf("format_string", &var1, &var2, ...);
Examples:
int n;
scanf("%d", &n);
int a; float b;
scanf("%d %f", &a, &b);
Output (printf):
→ Used to display data (memory → screen).
→ Defined in <stdio.h>.
Syntax:
printf("control_string", var1, var2, ...);
Examples:
int a = 5, b = 10;
printf("a=%d, b=%d\n", a, b); // prints values
printf("Hello World!\n"); // prints string
Format Specifiers (Conversion Specifications):
Specifier Meaning
%c Single character
%d Decimal integer
%f Floating-point number
%e Floating-point (scientific notation)
%lf Double precision floating-point
%h Short integer
%o Octal integer
%x Hexadecimal integer
%s String
%u Unsigned integer
Formatted Input:
Format:
%wd (for integers), %wf (for floats).
w = field width (max number of characters read).
Example:
int a;
scanf("%2d", &a);
Input: 20 → stores 20.
Input: 206 → stores 20 (extra digits ignored).
Multiple fields:
scanf("%2d %3d", &a, &b);
Input: 269 3845 → a=26, b=9.
Formatted Output:
Format:
%wd (integer), %w.pf (float).
w = min field width
p = precision (digits after decimal).
Values are right-justified if shorter than width.
Integer Example:
int a=6, b=39;
printf("a=%3d, b=%4d", a, b);
Output:
a= 6, b= 39
Format For Integer Output:
%wd
→ Here w is the integer number specifying the minimum field width of the output data.
→ If the length of the variable is less than the specified field width, then the variable is
right justified with leading blanks.
Example:
printf("a=%3d, b=%4d", a, b );
Floating-Point Example:
float x=5.3, y=65.87;
printf("x = %4.1f, y = %7.2f", x, y);
Output:
x = 5.3, y = 65.87
2) C program to print/display name of the student, branch and college in three lines
using \n.
Code:
#include<stdio.h>
int main()
{
printf("Name: Anirudh\n"); // \n moves cursor to the next line
printf("Branch: CSC\n");
printf("College: Raghu Engineering College");
return 0;
}
15) Write a C program that take a base (floating number) and an exponent (integer)
from the user and calculates the power.
Code:
#include<stdio.h>
#include<math.h>
int main()
{
float base, result;
int exponent;
printf("Enter base: ");
scanf("%f", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
result=pow(base, exponent);
printf("Result is %.2f\n", result);
return 0;
}
18) C program to convert a temperature from Fahrenheit to Celsius and vice versa.
Code:
#include<stdio.h>
int main()
{
float t, f, c;
printf("Enter Temperature: ");
scanf("%f", &t);
c=(t-32.0)*0.56;
f=(t*1.8)+32.0;
printf("celsius=%.2f\tfahrenheit=%.2f", c,f);
return 0;
}