0% found this document useful (0 votes)
1 views

Programming1(SEM1)

The document provides an overview of computer programming, covering key concepts such as programming languages, source code, compilation, and algorithms. It also outlines the Program Development Life Cycle (PDLC), detailing its phases from problem definition to maintenance, and introduces flowcharts, decision tables, and pseudo code as tools for algorithm representation. Additionally, it highlights the C programming language, its significance, and reasons for learning it.

Uploaded by

Mysterious Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Programming1(SEM1)

The document provides an overview of computer programming, covering key concepts such as programming languages, source code, compilation, and algorithms. It also outlines the Program Development Life Cycle (PDLC), detailing its phases from problem definition to maintenance, and introduces flowcharts, decision tables, and pseudo code as tools for algorithm representation. Additionally, it highlights the C programming language, its significance, and reasons for learning it.

Uploaded by

Mysterious Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

1.

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;

printf("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

sum = num1 + num2;

printf("Sum: %d\n", 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;

printf("Enter the radius of the circle: ");


scanf("%f", &radius);

area = PI * radius * radius;

printf("Area of the circle: %.2f\n", 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.

2. Program Development Life Cycle (PDLC)


The Program Development Life Cycle (PDLC) is a systema�c process
used to develop so�ware. It ensures that the so�ware meets user
requirements, is of high quality, and is delivered on �me. Each phase
of the PDLC contributes to the overall success of the so�ware
project.
Phases of PDLC:
1. Problem Defini�on:
• This phase involves clearly understanding and defining the
problem that needs to be solved. It is crucial to gather all
relevant information and constraints that will affect the
solution.
• Activities: Interviews with stakeholders, studying existing
systems, identifying the scope of the project.
• Deliverables: Problem statement document.
Example: You want to create a program that sorts a list of numbers in
ascending order.
2. Analysis:
• In the analysis phase, the problem is broken down into smaller
components. The requirements are analyzed to determine
what the software must do to solve the problem.
• Activities: Creating a requirements specification, data flow
diagrams, and use case analysis.
• Deliverables: Requirements specification document.

Example: Input: A list of unsorted numbers; Output: The list sorted in


ascending order.

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.

Example: Write a C program that implements Bubble Sort.


5. Tes�ng:
• Testing ensures that the software functions correctly and
meets the specified requirements. It involves running the
software under various conditions to identify bugs and errors.
• Activities: Unit testing, integration testing, system testing, and
acceptance testing.
• Deliverables: Test cases, test results, bug reports.
Example: Test the sor�ng program with various lists of numbers to
ensure it works correctly.

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.

Characteris�cs of a Good Algorithm:


• Correctness: The algorithm should produce the correct output
for all valid inputs.
• Efficiency: The algorithm should run within acceptable �me and
space constraints.
• Clarity: The steps of the algorithm should be easy to
understand.
• Generality: The algorithm should be applicable to a broad set
of problems.

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.

Example: Algorithm to Find the Largest of Three


Numbers
1. Step 1: Start
2. Step 2: Input three numbers A, B, C.
3. Step 3: If A > B and A > C, then print A as the largest.
4. Step 4: Else, if B > A and B > C, then print B as the largest.
5. Step 5: Else, print C as the largest.
6. Step 6: End

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;

printf("Enter three numbers: ");


scanf("%d %d %d", &A, &B, &C);

if (A > B && A > C) {


printf("The largest number is: %d\n",
A);
} else if (B > A && B > C) {
printf("The largest number is: %d\n",
B);
} else {
printf("The largest number is: %d\n",
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("Sorted array: \n");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

printf("\n");

getch();
}

This implementa�on sorts an array using the Bubble Sort algorithm,


as described in the pseudo code.
Introduc�on to C Language
What is C Language?
• C is a programming language, which means it's a set of
instruc�ons that you can use to tell a computer what to do.
• It was created by Dennis Ritchie in the early 1970s at Bell Labs.
It’s one of the most important programming languages in
computer science.
• C is known for being powerful, efficient, and flexible, which is
why it's s�ll widely used today.

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.

Basic Structure of a C Program: When you write a program in


C, it typically follows a basic structure:
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}

Let’s break this down:


1. #include <stdio.h>: This is a preprocessor direc�ve. It tells the
compiler to include the standard input-output library, which is
necessary for func�ons like prin�.
2. int main(): This is the main func�on where every C program
starts. The int before main means that this func�on returns an
integer value. main is the name of the func�on.
3. prin�("Hello, World!");: This is a func�on call. prin� is a
func�on that prints whatever is inside the quota�on marks to
the screen.
4. return 0;: This ends the main func�on and returns the value 0
to the opera�ng system, which typically means the program
executed successfully.

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.

Data Types: Primi�ve vs. non-primi�ve


1. Primi�ve Data Types
• Defini�on: Primi�ve data types are the basic building blocks
provided by a programming language. They are predefined in the
language and represent the simplest form of data.
• Characteris�cs:
o Predefined: Already defined by the language itself.
o Single Value: They store a single value.
o Fixed Size: The size (memory) of primi�ve types is generally
fixed and depends on the data type.
o Direct Opera�ons: Opera�ons on primi�ve types are
straigh�orward and usually supported by the language's
syntax.
• Examples in C:
o int: Used to store integers (whole numbers).
o float: Used for floa�ng-point numbers (decimals).
o char: Used to store a single character.
o double: Used for double-precision floa�ng-point numbers.
o void: Represents no value or type, typically used in func�ons.
2. Non-Primi�ve Data Types
• Defini�on: Non-primi�ve data types are more complex types
derived from primi�ve data types. They are not predefined in the
language but are created by the programmer.
• Characteris�cs:
o User-Defined: Created by the programmer or derived from
primi�ve types.
o Mul�ple Values: Can store mul�ple values or a collec�on of
data.
o Variable Size: The size of non-primi�ve types can vary
depending on the data they hold.
o Complex Opera�ons: Manipula�on of non-primi�ve types
o�en requires func�ons or methods.
• Examples in C:
o Array: A collec�on of elements of the same type stored in
con�guous memory.
o Pointer: A variable that stores the address of another
variable.
o Structure: A user-defined data type that groups related
variables of different types.
o Union: Similar to a structure, but all members share the
same memory loca�on.
o Enumera�on: A user-defined type consis�ng of named
integer constants.

Comparison in Table Form


Feature Primitive Data Types Non-Primitive Data Types
Definition Basic types predefined by Complex types derived from
the language. primitive types.
Examples int, float, char, double, void Array, Pointer, Structure,
Union, Enumeration
Storage Store a single value. Can store multiple values or a
collection.
Size Fixed size, defined by the Variable size, depends on the
language. data they hold.
Complexity Simple, direct operations. Complex, often require
functions/methods to
manipulate.
Memory Memory is allocated when Memory allocation can be
Allocation the variable is declared. dynamic or defined by the user.

Creation Predefined in the Created by the programmer.


programming language.
Data Represents fundamental Can represent more complex
Representation values like numbers, data like records, collections.
characters.

TABLE FOR PRIMITIVE DATA TYPES


Data Category Descrip�on Size Range Example
Type (Typical)

int Integer Stores 2 or 4 -32,768 to int age = 25;


whole bytes 32,767
numbers.

short int Integer Stores 2 bytes -32,768 to short int score = 32767;
smaller 32,767
whole
numbers.

long int Integer Stores 4 bytes - long int distance =


larger 2,147,483,648 100000L;
whole to
numbers. 2,147,483,647
unsigned Integer Stores only 4 bytes 0 to unsigned int popula�on =
int posi�ve 4,294,967,295 1000000;
whole
numbers.
float Floa�ng- Stores 4 bytes ~3.4E-38 to float pi = 3.14f;
Point single- 3.4E+38
precision
floa�ng-
point
numbers.
double Floa�ng- Stores 8 bytes ~1.7E-308 to double e = 2.7182818284;
Point double- 1.7E+308
precision
floa�ng-
point
numbers.
long Floa�ng- Stores 10 or ~3.4E-4932 to long double ld =
double Point extended- more 1.1E+4932 3.141592653589793238L;
precision bytes
floa�ng-
point
numbers.
char Character Stores a 1 byte -128 to 127 or char grade = 'A';
single 0 to 255
character.
void Void Represents N/A N/A void display() {
the prin�("Hello"); }
absence of
any data
type. O�en
used in
func�ons
with no
return
value.

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

Operators and Expressions


Operators are symbols that perform opera�ons on variables and
values. Expressions are combina�ons of variables, operators, and
values that produce a result. Understanding operators and how to
form expressions is fundamental in C programming.
1. Arithme�c Operators
• Used for performing basic mathema�cal opera�ons.

Operator Descrip�on Example


+ Addi�on a+b
- Subtrac�on a-b
* Mul�plica�on a*b
/ Division a/b
Modulus
% a%b
(Remainder)
Example:
int a = 10, b = 3;
int sum = a + b; // sum = 13
int difference = a - b; // difference = 7
int product = a * b; // product = 30
int quotient = a / b; // quotient = 3
int remainder = a % b; // remainder = 1

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.

Common I/O Functions:


Function Description Example
printf() Outputs formatted text to the screen printf("Hello World!");
scanf() Reads formatted input from the user scanf("%d", &variable);

getchar() Reads a single character from the user char c = getchar();


putchar() Outputs a single character to the screen putchar('A');
gets() Reads a string from the user gets(str);
puts() Outputs a string to the screen puts("Hello!");

fopen() Opens a file fopen("file.txt", "r");


fclose() Closes an open file fclose(filePointer);
fprintf() Writes formatted data to a file fprintf(filePointer, ...);
fscanf() Reads formatted data from a file fscanf(filePointer, ...);

STRUCTURED PROGRAMMING ELEMENTS


Structured programming is a programming paradigm aimed at
improving the clarity, quality, and development �me of a computer
program by making extensive use of the control structures:
sequence, selec�on, and itera�on. It discourages the use of "goto"
statements and promotes the use of blocks and subrou�nes.

Structured programming is a programming paradigm aimed at


improving the clarity, quality, and development �me of a program.
Elements Include:
Element Descrip�on
Func�ons Blocks of code designed to perform a specific
task.
Loops Allow for repeated execu�on of a block of
code (e.g., for, while).
Condi�onal Allow for decision-making within a program
Statements (e.g., if, else, switch).
Blocks Groups of statements enclosed in {} used for
organizing code.

Key Elements of Structured Programming


Structured programming revolves around three primary control
structures:
1. Sequence
2. Selec�on
3. Itera�on (Looping)
Element Defini�on Example

Sequence Execu�on of int a = 5;


statements one int b = 10;
a�er another in the int sum = a + b;
order they appear in prin�("Sum: %d\n", sum);
the code.

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.

• - if Executes a block of int num = 10;


Statement code if a specified if (num > 0) {
condi�on is true. prin�("Number is posi�ve\n");
}

• - if-else Executes one block int num = -5;


of code if a if (num > 0) {
condi�on is true, prin�("Number is posi�ve\n");
otherwise executes } else {
another block of prin�("Number is not
code. posi�ve\n");
}
• - else if Checks mul�ple int num = 0;
Ladder condi�ons in if (num > 0) {
sequence, execu�ng prin�("Number is posi�ve\n");
the corresponding } else if (num < 0) {
block for the first prin�("Number is nega�ve\n");
true condi�on. } else {
prin�("Number is zero\n");
}
• - switch Selects and executes int choice = 2;
Statement one of many code switch(choice) {
blocks based on the case 1:
value of a variable prin�("Choice is 1\n");
or expression. break;
case 2:
prin�("Choice is 2\n");
break;
case 3:
prin�("Choice is 3\n");
break;
default:
prin�("Invalid choice\n");
}

Itera�on Repeats the


execu�on of a block
of code as long as a
condi�on is true. It
includes loops like
for, while, and do-
while.
• - for Loop Executes a block of for(int i = 0; i < 5; i++) {
code a specific prin�("i = %d\n", i);
number of �mes. }

• - while Executes a block of int i = 0;


Loop code as long as the while(i < 5) {
condi�on is true. prin�("i = %d\n", i);
i++;
}
• - do-while Executes a block of int i = 0;
Loop code once, and then do { prin�("i = %d\n", i); i++; }
repeats as long as while(i < 5);
the condi�on is true.

CONTROL STATEMENTS: BRANCHING, JUMPING,


LOOPING
Control statements manage the flow of a program, allowing the
execu�on to jump between different parts of the code.

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

else if Adds an addi�onal if (a > b) { prin�("a > b"); }


condi�on to an if statement, else if (a == b) { prin�("a
executed if the ini�al equals b"); }
condi�on is false.

else Executes a block of code if if (a > b) { prin�("a > b"); }


all previous condi�ons are else { prin�("a is less than
false. b"); }
switch Selects one of many code switch (day) { case 1:
blocks to execute based on prin�("Monday"); break;
the value of a variable or case 2: prin�("Tuesday");
expression. Each case break; }
represents a possible value.
Detailed Explana�on:
• if, else if, else: These are condi�onal structures that let us
execute different pieces of code based on whether certain
condi�ons are true or false.
o Use Case: Decision-making in programs. For example,
calcula�ng the grade of a student based on their marks.
• switch: This allows us to select one of many code blocks to
execute based on a value or expression. It’s usually used when a
variable needs to be compared against mul�ple possible values.
o Use Case: Menu-driven programs where different choices
trigger different ac�ons, like a calculator.

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

break Exits the current loop or switch for (i = 0; i < 5; i++) { if


statement immediately. (i == 3) break; }

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.

return Exits from a func�on and int sum(int a, int b) {


op�onally returns a value to the return a + b; }
calling func�on.
Detailed Explana�on:
• goto: This statement allows jumping to another part of the
program. It is rarely used because it can make the program
harder to debug and understand.
o Use Case: Excep�on handling or breaking out of deeply
nested loops (but there are beter ways to handle such
situa�ons).
• break: Exits from a loop or a switch case before it has finished
execu�ng.
o Use Case: In loops, when we want to stop the loop when a
certain condi�on is met.
• con�nue: Skips the current itera�on of a loop and jumps to the
next itera�on.
o Use Case: When we want to bypass certain parts of the
loop but con�nue looping.
• return: Exits from a func�on and sends a value back to the
point where the func�on was called.
o Use Case: Returning results from func�ons to be used
elsewhere in the program.

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.

Control statements are essen�al in structuring the flow of a program.


Branching allows condi�onal execu�on of code, jumping alters the
flow by changing the execu�on path, and looping enables repeated
execu�on of code blocks. By mastering these control statements, we
can make our programs more dynamic and efficient.
ARRAYS
An array is a collec�on of data items of the same type stored in
con�guous memory loca�ons. Arrays allow us to store and manage
mul�ple values under a single variable name, where each value can
be accessed using an index.

Why Use Arrays?


In C, without arrays, we would need to declare separate variables for
each value. For instance, to store 100 integer values, you would need
100 individual variables. Arrays simplify this by allowing you to store
all the values in a single structure, indexed by numbers.

Types of Arrays in C
Type Descrip�on Example

One- A list of elements stored in a int arr[10];


Dimensional single row (linear).
Array

Two- A matrix or table with rows and int


Dimensional columns. matrix[3][4];
Array

Mul�- An array with more than two int


Dimensional dimensions, used for complex arr[3][4][5];
Array data structures.
One-Dimensional Array (1D Array)
A 1D array is a collec�on of elements stored in a linear sequence. It is
the simplest form of an array.
EXAMPLE:
#include <stdio.h>
#include <conio.h>

void main() {
int numbers[5] = {10, 20, 30, 40, 50};
int i;

// Print each element of the array


for (i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i,
numbers[i]);
}

// Wait for user input before closing


getch();
}

Two-Dimensional Array (2D Array)


A 2D array is an array of arrays, which can be visualized as a matrix
with rows and columns. It is commonly used to represent tables or
grids of values.
EXAMPLE:
#include <stdio.h>
#include <conio.h>

void main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int i, j;

// Print the elements of the 2D array


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

// Wait for user input before closing


getch();
}

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;

// Print the elements of the 3D array


for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
printf("arr[%d][%d][%d] =
%d\n", i, j, k, arr[i][j][k]);
}
}
}

// Wait for user input before closing


getch();
}

Advantages and Disadvantages of Arrays


Advantages:
• Efficient Memory Usage: Arrays store data in con�guous
memory loca�ons, allowing easy access through indexing.
• Simple Syntax: Arrays provide an easy way to store and
manipulate mul�ple values under a single variable name.

Disadvantages:
• Fixed Size: The size of an array is fixed at the �me of declara�on

and cannot be changed dynamically.


• No Built-in Bounds Checking: In C, there’s no automa�c

checking to ensure you are accessing within the array's bounds,


leading to poten�al errors.

By understanding arrays in C, we can efficiently manage and


manipulate large collec�ons of data, which is essen�al for building
more complex programs. Arrays are a fundamental concept that lays
the founda�on for more advanced data structures like linked lists,
stacks, and queues.
EXAMPLES:
1. Write a program in C to print "Hello, World!" to the
console.
Program:

#include <stdio.h>
#include <conio.h>

void main() {
// Print Hello, World! to the console
printf("Hello, World!\n");

// Wait for user input before closing


getch();
}

2. Write a program to demonstrate arithme�c operators in


C.
Program:

#include <stdio.h>
#include <conio.h>
void main() {
int x = 10, y = 5;
int sum, diff, prod, quotient, remainder;

// Perform arithmetic operations


sum = x + y;
diff = x - y;
prod = x * y;
quotient = x / y;
remainder = x % y;

// Print the results


printf("Sum: %d\n", sum);
printf("Difference: %d\n", diff);
printf("Product: %d\n", prod);
printf("Quotient: %d\n", quotient);
printf("Remainder: %d\n", remainder);

// Wait for user input before closing


getch();
}

3. Write a program to take two integers as input and display


their sum.
Program:

#include <stdio.h>
#include <conio.h>

void main() {
int a, b, sum;

// Taking input from the user


printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);

// Calculate the sum


sum = a + b;

// Print the sum


printf("The sum of %d and %d is: %d\n", a,
b, sum);

// Wait for user input before closing


getch();
}
3. Write a program to calculate the area of a rectangle using
a func�on.
Program:

#include <stdio.h>
#include <conio.h>

// Function to calculate area


int calculateArea(int length, int breadth) {
return length * breadth;
}

void main() {
int length, breadth, area;

// Taking input for length and breadth


printf("Enter the length of the rectangle:
");
scanf("%d", &length);
printf("Enter the breadth of the rectangle:
");
scanf("%d", &breadth);

// Calculate area using the function


area = calculateArea(length, breadth);

// Print the area


printf("The area of the rectangle is:
%d\n", area);

// Wait for user input before closing


getch();
}
4. Write a program to check if a number is posi�ve,
nega�ve, or zero using if...else.
Program:

#include <stdio.h>
#include <conio.h>

void main() {
int number;

// Taking input from the user


printf("Enter a number: ");
scanf("%d", &number);

// Check if the number is positive,


negative, or zero
if (number > 0) {
printf("The number is positive.\n");
} else if (number < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}

// Wait for user input before closing


getch();
}

5. Write a program to print the first 10 natural numbers


using a for loop.
Program:

#include <stdio.h>
#include <conio.h>
void main() {
int i;

// Print the first 10 natural numbers


for (i = 1; i <= 10; i++) {
printf("%d\n", i);
}

// Wait for user input before closing


getch();
}

6. Write a program to find the sum of all elements of a 1D


array.
Program:

#include <stdio.h>
#include <conio.h>

void main() {
int numbers[5], sum = 0, i;

// Taking input for the array elements


printf("Enter 5 numbers: ");
for (i = 0; i < 5; i++) {
scanf("%d", &numbers[i]);
}

// Calculate the sum of the array elements


for (i = 0; i < 5; i++) {
sum += numbers[i];
}

// Print the sum


printf("The sum of the array elements is:
%d\n", sum);
// Wait for user input before closing
getch();
}

7. Write a C program to take a number between 1 to 5 as


input and print the corresponding day of the week using a
switch statement.
Program:

#include <stdio.h>
#include <conio.h>

void main() {
int day;

// Taking input from the user


printf("Enter a number (1-5) to get the
corresponding day of the week: ");
scanf("%d", &day);

// Using switch statement to determine the


day
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Invalid input! Please enter
a number between 1 and 5.\n");
break;
}

// Wait for user input before closing


getch();
}

8. Write a C program that takes a number between 1 and 3


as input and prints the corresponding message using a
switch statement.
Program:

#include <stdio.h>
#include <conio.h>

void main() {
int option;

// Taking input from the user


printf("Enter a number (1-3): ");
scanf("%d", &option);

// Using switch statement to determine the


message
switch (option) {
case 1:
printf("You chose option 1.\n");
break;
case 2:
printf("You chose option 2.\n");
break;
case 3:
printf("You chose option 3.\n");
break;
default:
printf("Invalid option! Please
enter a number between 1 and 3.\n");
break;
}

// Wait for user input before closing


getch();
}

8. Write a C program that prints the numbers from 1 to 5


using a while loop.
Program:

#include <stdio.h>
#include <conio.h>

void main() {
int i = 1;

// Print numbers from 1 to 5 using while


loop
while (i <= 5) {
printf("%d\n", i);
i++;
}

// Wait for user input before closing


getch();
}
9. Write a C program that asks the user to enter a number
greater than 10 and keeps asking un�l the user provides a
valid input using a do...while loop.
Program:

#include <stdio.h>
#include <conio.h>

void main() {
int number;

// Use do...while loop to ensure valid


input
do {
printf("Enter a number greater than 10:
");
scanf("%d", &number);
} while (number <= 10);

// Print the valid number


printf("You entered a valid number: %d\n",
number);

// Wait for user input before closing


getch();
}

10. Write a C program that calculates the square of a


number using a func�on and returns the result.
Program:

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

// Taking input from the user


printf("Enter a number: ");
scanf("%d", &number);

// Calculate the square using the function


result = square(number);

// Print the result


printf("The square of %d is: %d\n", number,
result);

// Wait for user input before closing


getch();
}

11. Write a C program to demonstrate the use of break and


con�nue statements in a loop.
Program:

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

// Wait for user input before closing


getch();
}

12. Write a C program to reverse the elements of an array.


Program:

#include <stdio.h>
#include <conio.h>

void main() {
int arr[5] = {1, 2, 3, 4, 5};
int i, temp;

// Print original array


printf("Original array:\n");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Reverse the array


for (i = 0; i < 5 / 2; i++) {
temp = arr[i];
arr[i] = arr[5 - 1 - i];
arr[5 - 1 - i] = temp;
}

// Print reversed array


printf("Reversed array:\n");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Wait for user input before closing


getch();
}

13. Write a C program that uses a switch statement to print


the name of a month based on a number (1-12).
Program:

#include <stdio.h>
#include <conio.h>

void main() {
int month;

// Taking input from the user


printf("Enter a month number (1-12): ");
scanf("%d", &month);

// Using switch statement to print the


month
switch (month) {
case 1: printf("January\n"); break;
case 2: printf("February\n"); break;
case 3: printf("March\n"); break;
case 4: printf("April\n"); break;
case 5: printf("May\n"); break;
case 6: printf("June\n"); break;
case 7: printf("July\n"); break;
case 8: printf("August\n"); break;
case 9: printf("September\n"); break;
case 10: printf("October\n"); break;
case 11: printf("November\n"); break;
case 12: printf("December\n"); break;
default: printf("Invalid month number.
Please enter a number between 1 and 12.\n");
break;
}

// Wait for user input before closing


getch();
}

You might also like