Programming1(SEM1)
Programming1(SEM1)
Introduc�on to Computer
Programming
Computer Programming involves crea�ng a set of instruc�ons that
computers use to perform specific tasks. It’s a fundamental skill in
the field of computer science, allowing us to develop so�ware,
solve problems, and automate processes. Programming languages
like C are tools that enable this by providing a framework to write
code.
Key Concepts in Computer Programming:
• Programming Language: A language with a specific syntax and
grammar that is used to write code. C is a high-level language,
which means it is closer to human language and further from
machine code (binary).
• Source Code: The original code writen by the programmer in a
high-level language like C. This code needs to be translated into
machine code for the computer to execute it.
• Compila�on: The process of conver�ng source code into
machine code. A compiler checks the code for errors and
generates an executable file.
• Syntax and Seman�cs:
o Syntax: The rules governing the structure of statements in
a programming language. For instance, in C, every
statement ends with a semicolon (;).
o Seman�cs: The meaning of the statements and
expressions. While syntax is about structure, seman�cs is
about what the code actually does.
• Data Types: Define the type of data a variable can hold.
Common data types in C include:
o int for integers (e.g., int x = 5;)
o float for floa�ng-point numbers (e.g., float y = 3.14;)
o char for characters (e.g., char c = 'A';)
• Variables: Named storage loca�ons in memory that can hold
data. In C, variables must be declared with a specific data type
before use.
• Func�ons: Self-contained blocks of code designed to perform a
specific task. Func�ons can take inputs (parameters) and may
return a value. The main() func�on is the star�ng point of any C
program.
• Control Structures: Statements that control the flow of
execu�on in a program, such as loops (for, while) and
condi�onals (if, else).
Example: Suppose you want to create a simple program that adds
two numbers and displays the result. In C, this could be writen as:
#include <stdio.h>
#include <conio.h>
void main() {
int num1, num2, sum;
getch();
}
Example in C: Here’s a simple C program that calculates the area of a
circle:
#include <stdio.h>
#include <conio.h>
#define PI 3.14159
void main() {
float radius, area;
getch();
}
• Explana�on:
o #include <stdio.h>: This line includes the Standard Input
Output library, which is necessary for using func�ons like
prin� and scanf.
o #define PI 3.14159: Defines a constant named PI with a
value of 3.14159. This is used instead of wri�ng 3.14159
directly in the code, making it easier to update the value in
the future.
o float radius, area;: Declares two variables of type float to
store the radius of the circle and the calculated area.
o scanf("%f", &radius);: This func�on reads a floa�ng-point
number input by the user and stores it in the variable
radius.
o area = PI * radius * radius;: This line calculates the area of
the circle using the formula Area=π×radius2\text{Area} =
\pi \�mes \text{radius}^2Area=π×radius2.
o prin�("Area of the circle: %.2f\n", area);: This func�on
prints the calculated area, formated to two decimal
places.
o return 0;: Indicates that the program has executed
successfully.
3. Design:
• The design phase translates the requirements into a blueprint
for the software. This includes designing the architecture, user
interfaces, data structures, and algorithms.
• Activities: Creating flowcharts, class diagrams, and pseudo
code.
• Deliverables: Design specification document.
Example: Design an algorithm for a sor�ng method like Bubble Sort.
4. Coding:
• In this phase, the design is translated into actual code using a
programming language. This is where the software is built by
writing, compiling, and debugging code.
• Activities: Writing code, compiling, debugging, and version
control.
• Deliverables: Source code, executable files.
6. Implementa�on:
• The software is deployed to the target environment, where it is
made available to users. This phase may also include training
users and providing documentation.
• Activities: Deployment, user training, data migration.
• Deliverables: Deployed software, user manuals, installation
guides.
Example: Make the sor�ng program available to users or integrate it
into a larger system.
7. Maintenance:
• After deployment, the software needs to be maintained to fix
any issues, improve performance, or add new features.
Maintenance is an ongoing process that ensures the software
remains useful and relevant.
• Activities: Bug fixes, performance optimization, feature
updates.
• Deliverables: Updated software versions, maintenance reports.
Example: Modify the sor�ng program to handle larger lists more
efficiently or to sort in descending order if required.
3. Algorithms
An algorithm is a well-defined set of instruc�ons designed to solve a
problem or perform a specific task. Algorithms are essen�al in
computer programming because they provide a clear sequence of
steps to follow.
Proper�es of an Algorithm:
• Finite: The algorithm must terminate a�er a finite number of
steps.
• Definite: Each step of the algorithm must be clear and
unambiguous.
• Input: The algorithm takes zero or more inputs.
• Output: The algorithm produces at least one output.
• Effec�ve: The steps of the algorithm must be basic enough to
be carried out, in principle, by a person using only pencil and
paper.
Algorithm Example in C:
This algorithm can be implemented in C like this:
#include <stdio.h>
#include <conio.h>
void main() {
int A, B, C;
getch();
}
4. Flowchart
A flowchart is a graphical representa�on of an algorithm or a
process, using various symbols to denote different types of ac�ons or
steps. Flowcharts help in visualizing the flow of control in a program.
Flowchart Symbols:
• Oval: Represents the start or end of a process.
• Rectangle: Represents a process or instruc�on.
• Diamond: Represents a decision point (Yes/No).
• Parallelogram: Represents input/output opera�ons.
• Arrows: Indicate the direc�on of the flow of control.
Example: Flowchart to Find the Largest of Three Numbers
1. Start: The process begins.
2. Input A, B, C: The program accepts three numbers as input.
3. A > B?: Decision point to compare A and B.
o Yes: Move to the next decision point.
o No: Move to compare B and C.
4. A > C?: Decision point to compare A and C.
o Yes: Print A as the largest.
o No: Print C as the largest.
5. B > C?: Decision point to compare B and C.
o Yes: Print B as the largest.
o No: Print C as the largest.
6. End: The process ends.
5. Decision Table
A decision table is a tabular method for represen�ng condi�onal
logic, showing different combina�ons of inputs (condi�ons) and the
corresponding outputs (ac�ons). It is a powerful tool for handling
complex decision-making scenarios in programming.
Components of a Decision Table:
• Condi�ons: The input variables or scenarios that are evaluated.
• Ac�ons: The resul�ng ac�ons or outputs based on the condi�ons.
• Rules: Each possible combina�on of condi�ons and the
corresponding ac�on.
Example1: Decision Table for Finding the Largest of Three Numbers
Condi�ons A>B A>C B>C Ac�on
Rule 1 T T - Print A
Rule 2 F - T Print B
Rule 3 F F - Print C
Explana�on:
• Rule 1: If A > B and A > C, then A is the largest.
• Rule 2: If A is not greater than B, but B > C, then B is the largest.
• Rule 3: If neither A nor B is the largest, then C must be the
largest.
Example2: Decision Table for Discount Calcula�on
Scenario:
• If a customer is a member and the purchase amount is above
$100, they get a 20% discount.
• If they are not a member but the purchase amount is above
$100, they get a 10% discount.
• Otherwise, no discount is applied.
Condition Rule 1 Rule 2 Rule 3 Rule 4
Customer is a Yes Yes No No
member
Purchase
Yes No Yes No
amount > $100
Action
Apply 20%
Yes No No No
discount
Apply 10%
No No Yes No
discount
No discount No Yes No Yes
6. Pseudo Code
Pseudo code is a way of wri�ng algorithms in a human-readable form
that resembles programming language constructs, but without the
strict syntax. Pseudo code is used to outline the logic and flow of a
program before actual coding begins.
Benefits of Pseudo Code:
• Clarity: Helps in understanding the logic without ge�ng bogged
down by syntax.
• Language Agnos�c: Can be translated into any programming
language.
• Ease of Use: Allows the programmer to focus on the problem-
solving aspect.
Example: Pseudo Code for Bubble Sort Algorithm
START
Set N to the length of the list
FOR each element in the list (i = 0 to N-1)
FOR each element in the list (j = 0 to N-i-
1)
IF list[j] > list[j+1]
Swap list[j] and list[j+1]
ENDIF
ENDFOR
ENDFOR
PRINT sorted list
END
Explana�on:
• The pseudo code outlines the logic of the Bubble Sort
algorithm, where the list is iterated mul�ple �mes, and
adjacent elements are swapped if they are in the wrong order.
• The code is easy to understand and can be translated into any
programming language.
C Implementa�on: Here's how you might implement the above
pseudo code in C:
#include <stdio.h>
#include <conio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("\n");
getch();
}
Why Learn C?
• Founda�on Language: Many modern programming languages
like C++, Java, and Python are based on C. Learning C gives you
a strong founda�on for learning these other languages.
• Performance: C programs are very fast because they are close
to the machine’s code (the language your computer’s processor
understands).
• Portability: C code can be writen on one computer and then
run on almost any other computer without much or any
change.
• Wide Use: C is used in many areas, like opera�ng systems (like
Windows, Linux), embedded systems (like the so�ware in
microwaves and cars), and even game development.
Characteris�cs of C Language:
1. Simple: C has a small number of keywords and syntax rules,
making it easier to learn and use.
2. Procedural: C is a procedural programming language, which
means the focus is on func�ons and procedures. You break your
program into small parts (func�ons), each performing a specific
task.
3. Low-Level Language: While C is higher-level than machine
code, it s�ll allows you to interact closely with the computer’s
memory and hardware. This makes it suitable for system
programming.
4. Portable: C programs can be easily moved from one machine to
another, with litle to no modifica�on, making it highly
portable.
5. Rich Library: C comes with a rich set of built-in func�ons that
make coding easier. For example, func�ons for input/output,
math opera�ons, and more.
Uses of C Language:
• Opera�ng Systems: Many opera�ng systems, like UNIX, Linux,
and parts of Windows, are writen in C.
• Embedded Systems: C is widely used in programming
microcontrollers and other embedded systems found in cars,
appliances, and gadgets.
• Compilers: Compilers for other programming languages are
o�en writen in C.
• Games: C is used in game development, especially for systems
that require high performance.
Summary
C is a powerful, efficient, and widely-used programming language that serves
as a founda�on for many other languages and systems. It’s known for its
simplicity, speed, and flexibility, making it an essen�al language for anyone
looking to get into programming.
2. Data Types
Data types in C define the type of data a variable can hold. They determine
the amount of memory allocated to the variable and the opera�ons that can be
performed on it.
short int Integer Stores 2 bytes -32,768 to short int score = 32767;
smaller 32,767
whole
numbers.
Note:
Yes, "Primary" and "Derived" are different terms used to describe
data types, and they are closely related to "Primi�ve" and "Non-
Primi�ve" data types. Here's how these terms relate to each other:
1. Primary Data Types (Primi�ve Data Types)
• Primary Data Types are also known as Primi�ve Data Types.
These are the most basic data types provided by a
programming language. They are predefined in the language
and are used to store simple values like integers, characters,
and floa�ng-point numbers.
• Examples: int, float, char, double, void
2. Derived Data Types (Non-Primi�ve Data Types)
• Derived Data Types are created by combining or modifying
Primary Data Types. These types are more complex and can
represent collec�ons of data or more sophis�cated data
structures. In many cases, Derived Data Types are also referred
to as Non-Primi�ve Data Types.
• Examples: Array, Pointer, Structure, Union, Enumera�on
2. Rela�onal Operators
• Used to compare two values.
Operator Descrip�on Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
Greater than or
>= a >= b
equal to
Less than or equal
<= a <= b
to
Example:
int a = 5, b = 10;
int isEqual = (a == b); // isEqual = 0 (false)
int isGreater = (a > b); // isGreater = 0
(false)
int isLess = (a < b); // isLess = 1 (true)
2. Logical Operators
• Used to perform logical opera�ons.
Example Explana�on:
• &&: (a > 0 && b > 0) returns true only if both a and b are
greater than 0.
• ||: (a > 0 || b > 0) returns true if either a or b is greater
than 0.
• !: !(a > 0) returns true if a is not greater than 0 (i.e., a is
zero or nega�ve).
Another Example:
Operator Name Descrip�on Example
Returns true if
Logical (a > 0 && b >
&& both operands
AND 0)
are true.
Returns true if
at least one
|| Logical OR (a > 0 || b > 0)
operand is
true.
Reverses the
Logical
! logical state of !(a > 0)
NOT
its operand.
int a = 1, b = 0;
int result = (a && b); // result = 0 (false)
result = (a || b); // result = 1 (true)
result = !a; // result = 0 (false)
INPUT/OUTPUT FUNCTIONS
Input/output func�ons in C are essen�al for interac�ng with the user
and handling data through input (ge�ng data from the user) and
output (displaying data to the user). These func�ons are part of the
standard I/O library in C, and they allow a program to read data from
the keyboard (standard input) and display data on the screen
(standard output).
Input Statements in C
• Input statements allow the program to receive data from the user
or other sources. In C, the scanf() func�on is commonly used for
this purpose.
Output Statements in C
• Output statements allow the program to display data to the user.
In C, the prin�() func�on is commonly used for this purpose.
Example: Adding Two Integers
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter the first integer: ");
scanf("%d", &num1);
printf("Enter the second integer: ");
scanf("%d", &num2);
sum = num1 + num2;
printf("The sum of %d and %d is %d\n",
num1, num2, sum);
return 0;
}
Summary:
• Input Statement: scanf("%d", &num1); and scanf("%d",
&num2);
• Output Statement: prin�("The sum of %d and %d is %d\n",
num1, num2, sum);
• The program reads two integers from the user, adds them, and
prints the result.
Selec�on Decision-making
structure that allows
choosing different
paths based on
condi�ons. It
includes condi�onal
statements like if,
else if, else, and
switch.
1. Branching Statements
Statement Descrip�on Example
if Executes a block of code if a if (a > b) { prin�("a is
specified condi�on is true. greater than b"); }
2. Jumping Statements
Statement Descrip�on Example
goto Transfers control to another part goto label; ... label:
of the program uncondi�onally. prin�("Jumped!");
(Should be used sparingly as it
makes code hard to follow.)
con�nue Skips the rest of the loop’s current for (i = 0; i < 5; i++) { if
itera�on and proceeds with the (i == 3) con�nue; }
next itera�on.
3. Looping Statements
Statement Descrip�on Example
for Repeats a block of code a specified for (i = 0; i < 10;
number of �mes. Typically used i++) {
when the number of itera�ons is prin�("%d", i); }
known beforehand.
while Repeats a block of code while a while (i < 10) {
specified condi�on is true. Typically prin�("%d", i);
used when the number of i++; }
itera�ons is not known
beforehand.
do...while Similar to while, but ensures the do { prin�("%d",
block of code is executed at least i); i++; } while (i
once before the condi�on is tested. < 10);
Detailed Explana�on:
• for: This loop is used when we know exactly how many �mes
we need to repeat a block of code. It consists of three parts:
ini�aliza�on, condi�on, and increment/decrement.
o Use Case: Looping over arrays, itera�ng through fixed-
range values.
• while: This loop con�nues as long as the condi�on remains
true. It's used when we don’t know how many �mes the loop
should run beforehand.
o Use Case: Reading input from a user un�l a valid input is
given.
• do...while: This is similar to the while loop, but it ensures the
code runs at least once before checking the condi�on.
o Use Case: Running a menu at least once and then
repea�ng based on user input.
Types of Arrays in C
Type Descrip�on Example
void main() {
int numbers[5] = {10, 20, 30, 40, 50};
int i;
void main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int i, j;
Mul�-Dimensional Array
A mul�-dimensional array is an array with more than two
dimensions. These arrays are useful for storing complex data
structures, such as a 3D grid of points or color values in a 3D space.
EXAMPLE:
#include <stdio.h>
#include <conio.h>
void main() {
int arr[2][2][2] = {
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};
int i, j, k;
Disadvantages:
• Fixed Size: The size of an array is fixed at the �me of declara�on
#include <stdio.h>
#include <conio.h>
void main() {
// Print Hello, World! to the console
printf("Hello, World!\n");
#include <stdio.h>
#include <conio.h>
void main() {
int x = 10, y = 5;
int sum, diff, prod, quotient, remainder;
#include <stdio.h>
#include <conio.h>
void main() {
int a, b, sum;
#include <stdio.h>
#include <conio.h>
void main() {
int length, breadth, area;
#include <stdio.h>
#include <conio.h>
void main() {
int number;
#include <stdio.h>
#include <conio.h>
void main() {
int i;
#include <stdio.h>
#include <conio.h>
void main() {
int numbers[5], sum = 0, i;
#include <stdio.h>
#include <conio.h>
void main() {
int day;
#include <stdio.h>
#include <conio.h>
void main() {
int option;
#include <stdio.h>
#include <conio.h>
void main() {
int i = 1;
#include <stdio.h>
#include <conio.h>
void main() {
int number;
#include <stdio.h>
#include <conio.h>
// Function to calculate the square of a number
int square(int num) {
return num * num;
}
void main() {
int number, result;
#include <stdio.h>
#include <conio.h>
void main() {
int i;
// Demonstrate the use of break and
continue
for (i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the rest of the
loop for i == 5
}
if (i == 8) {
break; // Exit the loop when i == 8
}
printf("%d\n", i);
}
#include <stdio.h>
#include <conio.h>
void main() {
int arr[5] = {1, 2, 3, 4, 5};
int i, temp;
#include <stdio.h>
#include <conio.h>
void main() {
int month;