0% found this document useful (0 votes)
6 views15 pages

Comprog 1-17

The document outlines a comprehensive review of programming concepts, focusing on the programming process, including problem analysis, design, coding, testing, and documentation. It emphasizes the significance of the C programming language, its history, features, and the Turbo C development environment. Additionally, it covers fundamental programming elements such as data types, variables, constants, and operators essential for effective coding.

Uploaded by

JM Hiponia Jaem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

Comprog 1-17

The document outlines a comprehensive review of programming concepts, focusing on the programming process, including problem analysis, design, coding, testing, and documentation. It emphasizes the significance of the C programming language, its history, features, and the Turbo C development environment. Additionally, it covers fundamental programming elements such as data types, variables, constants, and operators essential for effective coding.

Uploaded by

JM Hiponia Jaem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

COMPROG 1 FINALS REVIEWER Steps:

WEEK 1  Select an appropriate programming language


based on the program's purpose.
Understanding Computers:
 Follow the syntax rules of the programming
Computers are not inherently intelligent; they merely
language strictly.
execute instructions given to them at high speeds.
Their ability to process complex computations Program Testing and Debugging:
quickly does not equate to intelligence. They are as
Definition: Ensuring the program is error-free and
good as the instructions or programs fed into them.
functions as intended.
This fundamental understanding is crucial in
programming, as it highlights the importance of Types of Testing:
writing clear, logical, and accurate programs.
Alpha Testing: Includes desk-checking and
What is Programming? debugging.
Programming is both an art and a science. It involves Beta Testing: Running real data through the
creating programs—organized sets of instructions program.
that a computer follows to transform data into
Steps:
meaningful information. Programming goes beyond
just writing code; it's a structured process that  Perform desk checking to identify errors.
involves problem-solving and logical thinking.
 Debug the program to resolve any errors.
Program Development Process
 Test the program with both real and bad data.
Programming, also known as software engineering,
Program Documentation and Maintenance:
is a multi-step process. It involves several stages,
each critical to developing a successful program. Definition: Creating comprehensive guides to help
These stages are: users and programmers understand and maintain the
program.
Problem Analysis:
Steps:
Definition: Breaking down the problem into smaller,
manageable parts for detailed study.  Prepare user documentation.
Steps:  Prepare operator documentation.
 Define the problem and identify the users.  Prepare program documentation.
 Determine the desired outputs.  Maintain the program by keeping it up-to-
date and error-free.
 Identify the necessary inputs.
Detailed Look at Key Steps
 Plan the required processing.
1. Problem Analysis:
 Check the feasibility of the program.
This first step is critical as it lays the foundation for
 Document all analysis steps.
the entire programming process. It involves
Program Design: understanding the problem thoroughly, determining
what the program needs to achieve, and considering
Definition: Creating a blueprint for the program
the needs of the end users. By breaking down the
using algorithms.
problem into smaller tasks, the programmer can
Tools: Flowcharts, decision tables, pseudocode. manage complexity and ensure that all aspects of the
problem are addressed.
Steps:
2. Program Design:
Use a top-down approach to define program logic.
Once the problem is fully understood, the next step
Create detailed designs using pseudocode or
is to design a solution. This involves creating
flowcharts.
algorithms—step-by-step instructions that outline
how the program will solve the problem. Flowcharts
and pseudocode are common tools used in this stage
Program Coding:
to visualize the program’s logic before actual coding
Definition: Translating the program design into a begins.
specific programming language.
3. Coding:
Coding is the process of converting the program Mention that C evolved from the earlier B language,
design into a language the computer can understand. which was also developed at Bell Labs.2. The K&R
This involves writing code in a programming Standard:
language, following the syntax rules of that language
2. Publication of K&R C:
to ensure the program functions correctly.
Explain that in 1978, Brian Kernighan and Dennis
4. Testing and Debugging:
Ritchie published the first description of C, which
After coding, it’s essential to test the program to find became known as the K&R standard.
and fix errors. This step ensures that the program
Discuss the significance of this standard in providing
operates as expected in various scenarios, including
a foundation for the widespread adoption of C.
handling incorrect or unexpected input.
5. Documentation and Maintenance:
Finally, documentation is created to help users and 3. C as a System Programming Language:
other programmers understand how to use and
UNIX and C:
maintain the program. Maintenance involves
updating the program as needed to fix any issues and Emphasize that the UNIX operating system,
ensure it remains functional as requirements evolve. including its kernel, was entirely written in C.
Conclusion Explain how this established C as a powerful
language for system programming.
Programming is a structured and logical process that
requires careful planning and execution. By Professional Use of C:
following these steps, programmers can develop
Discuss why C became widely used in professional
efficient, reliable, and maintainable software that
programming due to its efficiency, portability, and
meets the needs of users. Understanding the
structured nature.
importance of each step—from problem analysis to
maintenance—is key to becoming a successful Mention that C can handle low-level activities and is
programmer. compiled on various platforms, making it highly
versatile.
WEEK 2
4. Key Features and Advantages of C:
Lesson 2.1: History of the C Language
Easy to Learn and Use:
I. Introduction:
Highlight that C is considered easy to learn for those
Begin the lesson by discussing the importance of
with basic programming knowledge.
programming languages in the development of
software and operating systems. Highlight that C is Structured Language:
one of the most influential programming languages,
Explain that C supports structured programming,
having laid the foundation for many modern systems
where complex tasks are broken down into
and languages.
manageable functions or modules.
Objective:
Efficient and Fast:
Students will understand the historical development
Discuss how C produces efficient programs that can
of the C programming language, its key features, and
run almost as fast as assembly language code.
its impact on modern computing.
Portability:
II. Main Content:
Explain C's portability, where programs written in C
1. The Origins of C:
can be compiled and run-on different computer
Development at Bell Labs: systems with minimal changes.
Introduce Dennis M. Ritchie, who developed C in the
early 1970s.
5. Formalization of C by ANSI:
Explain that C was developed to create the UNIX
operating system, which required a powerful, ANSI C Standard:
flexible, and efficient language.
Discuss how the American National Standards
First Implementation: Institute (ANSI) formalized C in 1988.
Discuss how C was first implemented on the DEC
PDP-11 computer in 1972.
Explain the significance of having a standardized
version of C, which ensured consistency across
different implementations and platforms.
2. Components of Turbo C:
6. Legacy and Influence of C:
o Integrated Development
C as a Foundation for Other Languages: Environment (IDE):
Discuss how C has influenced the development of  Highlight the key features of
other programming languages, particularly C++ and the Turbo C IDE, which
Java. allows programmers to edit,
compile, link, debug, and run
Explain that many of the concepts and
C programs within a single
methodologies from C have been carried forward
environment.
into these languages, making C a foundational
language in computer science.  Discuss how the IDE
improves programming
Current Use of C:
efficiency by eliminating the
Mention that C is still widely used today in system need to switch between
programming, embedded systems, and other different tools and
performance-critical applications. environments.
WEEK 3 o Command-Line Interface:
Introduction:  Mention that Turbo C also
provides a traditional
Begin the lesson by discussing the significance
command-line version,
of development environments in the programming
catering to the preferences of
process. Highlight how the Turbo C Compiler has
different programmers.
been an essential tool for C programmers, offering
both a command-line interface and an Integrated
Development Environment (IDE) that streamlines
the programming process. 3. Key Features of Turbo C:
Objective: Students will understand the o Editor:
components, features, and functionality of the Turbo
 Explain that the Turbo C
C Compiler, and its role in facilitating the
Editor is used to create and
development of C programs.
edit the source code of C
Main Content: programs.
1. Overview of Turbo C: o Extended C Language:
o Development and Release:  Discuss how Turbo C extends
the original specifications of
 Introduce Turbo C as a
the C language, making it
version of the C language
compatible with the ANSI C
developed by Borland
standard.
International Corporation in
1987. o Compiler:
 Discuss how Turbo C was  Describe the role of the
designed to run on various compiler in translating source
microcomputer systems, code into machine language
offering both a command-line object code, and how Turbo C
interface and an IDE. is known for its speed and
efficiency.
o Comparison with Borland C:
o Debugger:
 Explain that Borland C is the
professional version of Turbo  Explain the importance of the
C, containing additional debugger in testing programs
programming support tools and locating programming
while maintaining the same errors.
compiler.
o Run-Time Environment:
 Discuss the role of the Run-  Highlight the user-friendly
Time Environment in nature of the Turbo C IDE,
executing compiled programs which simplifies the coding
within the Turbo C system. process for both beginners and
experienced programmers.
o User Interface:
o Portability:
 Highlight how the user
interface integrates various  Mention the portability of
features into a single program, Turbo C programs, which can
allowing seamless transition be compiled and run on
between coding, compiling, different computer systems
and debugging. with minimal changes.
WEEK 5
Definition:
4. Using the Turbo C IDE:
In C, data types define the kind of data that can be
o Starting and Quitting Turbo C:
stored in a variable. There are five elementary data
 Provide instructions on how types:
to start Turbo C in a Windows
environment by locating and
Character (char): Used to hold ASCII characters or
running the TC.EXE file.
any 8-bit quantity.
 Explain the process of Integer (int): Used to store integer quantities.
navigating the main menu and Floating-point (float): Used to store real numbers
using shortcut keys to access with both integer and fractional components.
different functions. Double floating-point (double): Similar to float but
with double precision.
 Discuss how to quit Turbo C,
Void: Used to declare functions that do not return any
emphasizing the importance
value or to create generic pointers.
of saving any changes before
exiting. Example:
o Program Development Workflow: char letter = 'A'; // Holds a single character
int number = 100; // Holds an integer
 Discuss the typical workflow
float pi = 3.14; // Holds a floating-point number
within the Turbo C IDE, from
double largePi = 3.1415926535; // Holds a double
writing and editing the source
floating-point number
code to compiling, debugging,
void function(); // Void function
and running the program.
2. Type Modifiers:
 Explain how the integrated
environment accelerates the Definition:
development process by
Modifiers are used to alter the meaning of the base
allowing rapid compilation
data types, allowing for greater precision and range.
and recompilation cycles.
The following are the common type modifiers in C:
Signed: Can represent both positive and negative
values.
5. Advantages of Turbo C:
Unsigned: Can only represent non-negative values.
o Speed and Efficiency: Long: Used to increase the range of integer values.
Short: Used to reduce the range of integer values,
 Discuss how Turbo C’s
saving memory.
compiler produces efficient
machine code that runs almost Example:
as fast as assembly language,
unsigned int positiveNumber = 50; // Holds only
making it suitable for
non-negative integers
performance-critical
long int bigNumber = 100000; // Holds large
applications.
integers
o Ease of Use: short int smallNumber = 5; // Holds small
integers
3. Variables: 5. Operators:
Definition: Definition:
Variables are identifiers that store changeable values Operators are symbols used to perform operations on
in a program. Each variable must be declared with a variables and values. In C, operators are categorized
data type and a unique name before it is used in the into four classes:
program.
3.1 Variable Declaration:
5.1 Arithmetic Operators:
Variables must be declared before use. The general
These operators are used for mathematical
form of a declaration is:
calculations.
Example:
Syntax:
int sum = 10 + 5; // Adds two numbers
type variable1, variable2, variable3; int product = 10 * 5; // Multiplies two numbers
Common arithmetic operators: +, -, *, /, % (modulus)
Example:
int i, j, k; // Declare three integer variables 5.2 Logical Operators:
float x, y; // Declare two floating-point variables
These operators are used for logical comparisons,
Note: Variables must be separated by commas, and returning either true or false.
all declarations must end with a semicolon.
Example:
3.2 Types of Variables:
if (x > 5 && y < 10) {
A. Local Variables: // Executes if both conditions are true
}
Local variables are declared inside a function and can
Common logical operators: && (AND), || (OR), !
only be accessed within that function.
(NOT)
Example:
void myFunction() {
5.3 Relational Operators:
int localVar = 10; // Local variable
printf("%d", localVar); These operators are used to compare two values.
}
Example:
B. Global Variables:
if (x == y) {
Global variables are declared outside any function // Executes if x is equal to y
and can be accessed by any part of the program. }
Common relational operators: ==, !=, >, <, >=, <=
Example:
int globalVar = 20; // Global variable
5.4 Bitwise Operators:
void myFunction() {
These operators perform operations on the bit level.
printf("%d", globalVar); // Accessing global
variable Example:
}
int result = x & y; // Bitwise AND
int result = x | y; // Bitwise OR
Common bitwise operators: &, |, ^, ~, <<, >>
4. Constants:
III. Conclusion:
Definition:
Understanding data types, type modifiers, variables,
Constants are similar to variables, but their values
constants, and operators is fundamental for any C
cannot be changed during program execution. They
programmer. These elements form the building
are declared using the const keyword.
blocks of C programs, enabling programmers to
Example: define how data is stored, manipulated, and used
within a program. Proper use of data types and
const int maxStudents = 50; // A constant integer
with a fixed value
operators ensures efficient and functional code that All format specifiers start with a percent sign (%) and
can handle a wide range of computations. are followed by a single letter indicating the type of
data and how data are to be formatted.
WEEK 7
%c - used for single char in C
Input and Output Statement
scanf("%c", &ch);
A statement used to input a single character or a
sequence of characters from the keyboard. printf("%c", ch);
1. getch – a function to input a single character %d - decimal number (whole number)
from the keyboard without echoing the
scanf("%d", &num);
character on the monitor.
Syntax: getch(); printf("%d", num):
2. getche – a function used to input a single
%e – scientific notation/exponential form
character from the keyboard, the character
pressed echoed on the monitor, like the scanf(“%e”, &result);
READLN in PASCAL.
printf(“%e”, result);
Syntax: getche();
3. getchar – a function used to input a single %f - number with floating or decimal point
character from the keyboard, the character
scanf("%f", &pesos);
pressed echoed on the monitor, terminated by
pressing ENTER key, printf("%f", pesos);
Syntax: getchar();
%o - octal number
4. gets - a function used to input sequence of
characters from the keyboard, spaces are scanf("%0", &value);
accepted, terminated by pressing ENTER
printf("%0", value);
key,
Syntax: gets(); %s - string of characters
5. scanf – a function used to input single
scanf("%s", &str);
character or sequence of characters from the
keyboard, it needs the control string codes in printf ("%s", str);
able to recognized. . Spaces are not accepted
%u - unsigned number
upon inputting. Terminated by pressing
spacebar. scanf("%u", &nos);
Syntax: scanf("control string codes",
printf ("%u", nos);
identifier);
Example: scanf ("%d", &num); %x - hexadecimal number
Output Statements scanf("%x", &value);
A statement used to display the ar- gument list or printf("%x", value);
string on the monitor.
%X -capital letter for hexadecimal number
1. printf - a function used to display the
scanf("%X", &nos);
argument list on the monitor. It sometimes
needs the control string codes to help display printf("%X", nos);
the remaining arguments on the screen.
%% - print a percent sign
Syntax: printf("control string codes",
argument list); scanf("%%", &value);
Example: printf("Hello, %s, you are %d
printf ("%%", value);
years old", name, age);
2. putchar - a function used to display the WEEK 8
argument list or string on the monitor. It is
Conditional Statements
like overwriting a character.
Syntax: putchar(); Conditional statements are statements that check an
Example: putchar(tolower(ch)); expression then may or may not execute a statement
3. puts - a function used to display the argument or group of statements de- pending on the result of
list or string on the monitor. Syntax: puts (); the execution.
Example: puts ("Welcome to BESTLINK);
The IF Statement
Format Strings and Escape Sequences
The general form of the if statement is:
Syntax: }else if{
if(expression){ statement_sequence;
statement_sequence; }else if{
} statement_sequence;
Where: if is a reserved word expression is a relational } else if{
or boolean expression that evaluates to a TRUE (1)
statement_sequence;
or FALSE (0) value
} else if{
statement may either be a single Turbo C statement
or a block of Turbo C statements. statement_sequence;
In an if statement, if the expression evaluates to }else
TRUE (1), the statement or the block of statements
statement_sequence;
that forms the target of the if statement will be
executed. Otherwise, the program will ignore the Where:
statement or the block of statements.
if and else are reserve words in Turbo C
NOTE: Never place a semicolon after the expression
expression_1, expression_2 up to expression_n is a
in an if statement.
relational or bool- ean expression that evaluates to a
The IF-ELSE Statement TRUE (1) or FALSE(0) value
The general form of the if-else statement with block statement_1, statement_2 up to statement_else may
of statements is: either be a single Turbo C statement or a block of
Turbo C statements.
Syntax:
In an if-else-if ladder statement, the expressions are
if(expression){
evaluated from the top downward. As soon as a true
statement_sequence; condition is found, the statement associated with it is
executed, and the rest of the ladder will not be
}else{
executed. If none of the condition is true, the final
statement_sequence; else is executed.
} The final else act as a default condition. If all other
conditions are false, the last else statement is
Expression is a relational or boolean expression that
performed. If the final else is not present, then no
evaluates to a TRUE (1) or FALSE (0) value
action takes place.
The NESTED-IF Statement
The SWITCH Statement
One of the confusing aspects of the if statement in
The switch statement is a multiple-branch decision
any programming language is nested if. A nested if is
statement.
an if statement that is the object of either an if or else.
This is sometimes referred to as "an if within an if. The general form of the switch statement is:
The reason that nested if are so confusing is that it Syntax:
can be difficult to know what else associates with
Switch(variable)
what if.
{
Fortunately, Turbo C provides a very simple rule for
resolving this type of situation. In Turbo C, the "else Case constant 1:
is linked to the closest preceding if that does not
Statement sequence_1;
already have an else statement associated with it"
Break;
The IF-ELSE-IF Ladder
case constant 2:
A common programming construct in Turbo C is the
if-else-if ladder. statement sequence 2;
Syntax: Break;
if(expression){ Default:
statement_sequence; Statement_sequence_defult:
} The WHILE Statement
In a switch, a variable is successively tested against The while statement or while loop is an open-ended
a list of integer or character constants. If a match is or event-con- trolled loop. The while loop iterates
found, a statement or block of statements is executed. while the condition is TRUE (1). When it becomes
The default part of the switch is executed if no FALSE (0), the program control passes to the line
matches are found. after the loop code.
According to Herbert Schildt (1992), there are three The general for the while statement is:
important things to know about switch statements:
Syntax:
1. The switch differs from if statements in such
While(conditional)
a way that switch can only test for a equality
whereas if can evaluate a relational or logi cal {
expression.
Statement_sequence;
2. No two case constants in the same switch can
have identical values Of course, a switch }
statement enclosed by an outer switch may
have case constants that are the same.
3. If character constants are used in the switch,
they are automatically converted to integer
The DO-WHILE Statement
values.
The second type of open-ended or event-controlled
WEEK 9
loop is the do- while statement or do-while loop.
Looping Statements
The general form of the do-while statement is:
Looping statements (loops) allow a set of
Syntax:
instructions to be executed or performed several
times until certain conditions are met. It can be do
predefined as in the for loop, or open-ended as in
{
while and do-while.
statement_sequence;
The FOR Statement
}
The for statement or for loop is considered as a
predefined loop wolle because the number of times it while (condition);
iterates to perform its body is pre- determined in the
do-while is a variation of the while statement which
loop's definition.
checks the condition at the bottom / end of the loop.
The for loop contains a counter whose values This means that a do-while loop "always execute at
determine the num ber of times the loop iterates. The least once".
iteration stops upon reaching the number of times
In the do-while loop, when the condition evaluates to
specified in the loop.
TRUE(1), the loop body will be executed, but when
The general form of the for statement is: FALSE(0), program control proceeds to the next
instruction after the do-while loop.
Syntax:
WEEK 10
For(initialization; condition; increment)
Function
{
A function is a group of statements that together
Statement_sequence;
perform a task. Every C program has at least one
} function, which is main(), and all the most trivial
programs can define additional functions.
NOTE:
You can divide up your code into separate functions.
a) never place a semi-colon right after the for header.
How you di- vide up your code among different
This is a logical error.
functions is up to you, but logically the division is
b) never change the value of the for loop's counter such that each function performs a specific task.
inside the body of the loop. This will affect then
A function declaration tells the compiler about a
result of the program.
function's name, return type, and parameters. A
c) the increment part of the for loop is executed after function definition provides the actual body of the
the first iteration of the loop function.
The C standard library provides numerous built-in
functions that your program can call. For example,
strcat() to concatenate two strings,
memcpy() to copy one memory location to another in another file. In such case, you should declare the
locations, and many more functions. function at the top of the file calling the function.
A function can also be referred as a method or a sub- Calling a Function
routine or a procedure, etc.
While creating a C function, you give a definition of
Defining a Function what the function has to do. To use a function, you
will have to call that function to perform the defined
The general form of a function definition in C
task.
programming language is as follows:
When a program calls a function, the program control
A function definition in C programming consists of a
is trans- ferred to the called function. A called
function header and a function body. Here are all the
function performs a defined task and when its return
parts of a function –
statement is executed or when its function-ending
Syntax: closing brace is reached, it returns the program
control back to the main program.
Return_type function_name (parameter list)
To call a function, you simply need to pass the
{
required parameters along with the function name,
Body off the function and if the function returns a value, then you can store
the returned value. For example –
}
#include <stdio.h>
Return Type A function may return a value. The
return_type is the data type of the value the function /* function declaration */
returns. Some functions perform the desired
int max(int num1, int num2);
operations without returning a value. In this case, the
re- turn_type is the keyword void. int main ()
Function Name - This is the actual name of the {
function. The function name and the parameter list
/* local variable definition */
together constitute the function signature.
int a = 100;
Parameters - A parameter is like a placeholder.
When a function is invoked, you pass a value to the int b = 200;
parameter. This value is referred to as actual
int ret;
parameter or argument. The parameter list refers to
the type order, and number of the parameters of a /*calling a function to get max value */
function. Parameters are op tional; that is, a function
Ret = max(a,b);
may contain no parameters.
Printf(“Max value is: %d\n”, ret);
Function Body The function body contains a
collection of statements that define what the function Return 0;
does.
}
Function Declarations
/*function returning the max between two numbers
A function declaration tells the compiler about a */
function name and how to call the function. The
int max(int num1, int num2) 1
actual body of the function can be defined separately.
/local variable declaration */ int result;
A function declaration has the following parts -
return_type func- tion_name(parameter list); if (num1 > num2)
For the above defined function max(), the function result = num1;
declaration is as follows - int max(int num1, int
else result = num2;
num2);
return result;
Parameter names are not important in function
declaration only their type is required, so the }
following is also a valid declaration - int max(int,
We have kept max() along with main() and compiled
int);
the source code. While running the final executable,
Function declaration is required when you define a it would produce the follow- ing result –
function in one source file and you call that function
Max value is: 200
Function Arguments an exit condition from the function, otherwise it will
go into an infinite loop.
If a function is to use arguments, it must declare
variables that ac- cept the values of the arguments. Recursive functions are very useful to solve many
These variables are called the formal parameters of mathematical problems, such as calculating the
the function. factorial of a number, generating Fibonacci series,
etc.
Formal parameters behave like other local variables
inside the function and are created upon entry into Number Factorial
the function and destroyed upon exit.
The following example calculates the factorial of a
While calling a function, there are two ways in which given number using a recursive function
arguments can be passed to a function.
#include <stdio.h>
By default, C uses call by value to pass arguments.
Int factorial(unsigned int i){
In general, it means the code within a function cannot
alter the arguments used to call the function. If(i <= 1)
{
Return 1;
}
Call Type & Description Return 1 * factorial(i – 1);
Call by value }
This method copies the actual value of an argument Int main()
into the formal parameter of the function. In this case,
{
changes made to the parameter inside the function
have no effect on the argument. Int i = 15;
Call by reference Printf(“Factorial of %d is %d\n”, i,
factorial(i));
This method copies the address of an argument into
the formal parameter. Inside the function, the address Return 0;
is used to access the actual argument used in the call.
}
This means that changes made to the parameter affect
the argument. When the above code is complied and executed, it
produces the following results.
WEEK 11
Fibonacci Series
Recursion
The following examples generates the Fibonacci
Recursion is the process of repeating items in a self-
series for a given number using a recursive function.
similar way. In programming languages, if a program
allows you to call a function in- side the same #include <stdio.h>
function, then it is called a recursive call of the
Int Fibonacci (int i)
function.
{
void recursion()
If ( 1 == 0)
{
{
recursion(); /* function calls itself */
Return 0;
}
}
int main()
If ( i == 1
{
{
recursion();
Return 1;
}
}
The C programming Language supports recursion,
i.e., a function to call itself. But while using Return Fibonacci(i – 1) + Fibonacci(i – 2);
recursion, programmers need to be careful to define
}
Int main()  numbers[0] = 10;
numbers[1] = 20;
{
Accessing Array Elements:
Int i;
 Use the index (starting from 0):
For (i = 0; i < 10; i ++)
printf("%d", numbers[0]);
{
 Looping through an array:
Prinf(“%d\t\n”, Fibonacci(i));
 for (int i = 0; i < 5; i++) {
}
 printf("%d ", numbers[i]);
Return 0;
}
}
Multi-Dimensional Arrays:
 Syntax:
WEEK 13
data_type array_name[rows][columns];
1. Array Declaration:
 Example:
An array is a collection of elements, typically
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
of the same data type, stored in contiguous memory
locations. Arrays allow multiple elements to be Exercise 1: Input and Output
stored and accessed using a single variable name
Write a program to input and display an array of 5
with an index.
integers.
 What are Arrays?
#include <stdio.h>
o An array is a collection of variables
int main() {
of the same type stored in contiguous
int numbers[5];
memory locations.
printf("Enter 5 integers:\n");
o It allows the management of large
for (int i = 0; i < 5; i++) {
amounts of data with a single
scanf("%d", &numbers[i]);
identifier.
}
o Example Use Case: Storing marks of
all students in a class. printf("You entered:\n");
for (int i = 0; i < 5; i++) {
 Real-World Analogy:
printf("%d ", numbers[i]);
o Consider a row of lockers, each
}
identified by a number. The locker
represents a memory location, and return 0;
the numbers are the indices of an
}
array.
Exercise 2: Finding the Largest Element
Write a program to find the largest element in an
2. Main Concepts array of integers.
Array Declaration: #include <stdio.h>
 Syntax: int main() {
int numbers[5] = {10, 20, 30, 40, 50};
data_type array_name[size];
int max = numbers[0];
 Example:
for (int i = 1; i < 5; i++) {
 int numbers[5];
if (numbers[i] > max) {
char letters[10];
max = numbers[i];
Array Initialization: }
}
 During Declaration:
int numbers[5] = {1, 2, 3, 4, 5}; printf("Largest element: %d\n", max);
return 0;
 Later Initialization:
}
What happens if you access an index outside the  Key Notes:
array bounds?
o * is used to declare a pointer.
How is memory allocated for arrays?
o & retrieves the address of a variable.
Compare arrays with pointers. Are they the same?
b. Accessing and Modifying Values Using
Problem 1: Sum of Array Elements Pointers
 Write a program to calculate the sum of all  Dereferencing: Using * to access the value
elements in an array. stored at the memory address.
Problem 2: Multi-Dimensional Array  printf("Value of a: %d\n", *p); // Access
value of a
 Create a 2x3 matrix and display its elements
*p = 20; // Modify value of a via pointer
row by row.
c. Null Pointers
 Definition: A pointer that does not point to
Summary:
any valid memory location.
 Arrays are a fundamental tool in C for int *p = NULL;
managing collections of data.
 Useful for indicating uninitialized pointers.
 Key operations include declaration,
d. Pointer Arithmetic
initialization, and traversal.
 Incrementing or decrementing pointers to
 Arrays are versatile and form the basis for
traverse memory locations.
more complex data structures.
 int arr[3] = {1, 2, 3};
WEEK 14
 int *p = arr;
1. Form of Pointers:
printf("%d\n", *(p + 1)); // Access second
A pointer is a variable that stores the memory element
address of another variable. Pointers provide a
e. Common Mistakes and Best Practices
powerful way to manipulate memory directly.
 Uninitialized Pointers: Always initialize
 Definition: A pointer is a variable that stores
pointers.
the memory address of another variable.
 Dangling Pointers: Avoid accessing freed
 Why Pointers Matter:
memory.
o Enable dynamic memory allocation.
 Memory Leaks: Properly deallocate
o Facilitate the creation of complex dynamically allocated memory.
data structures (e.g., linked lists,

trees).
o Enhance performance by allowing
3. Hands-On Practice
direct memory access.
Activity 1: Pointer Basics
o Simplify function parameter passing,
especially for large data. 1. Declare an integer variable and a pointer.
 Real-Life Analogy: Think of a pointer as a 2. Initialize the pointer to the address of the
signpost that points to the location of an variable.
object (variable) rather than the object itself.
3. Print the variable’s value using the pointer.
2. Main Concepts
Activity 2: Swap Two Numbers Using Pointers
a. Pointer Declaration and Initialization
#include <stdio.h>
 Syntax:
void swap(int *x, int *y) {
data_type *pointer_name;
int temp = *x;
 Example:
*x = *y;
int a = 10;
*y = temp;
int *p = &a; // p stores the address of a
}
int main() {  What are Strings in C?
int a = 5, b = 10; o Strings are arrays of characters
terminated by a null character (\0).
printf("Before swap: a = %d, b = %d\n", a, b);
o They are widely used for text
swap(&a, &b);
manipulation in programming, such
printf("After swap: a = %d, b = %d\n", a, b); as handling names, messages, and
file paths.
return 0;
 Why Use String Functions?
}
o To simplify common string
 Objective: Understand how pointers can be
operations like finding the length,
used to modify variables through function
copying, concatenation, and
parameters.
comparison.
Activity 3: Dynamic Memory Allocation
o String functions reduce development
 Allocate memory for an array using malloc. time and ensure consistent behavior.
#include <stdio.h>
#include <stdlib.h>
2. Common String Functions in C
int main() {
 1. strlen()
int *arr;
Purpose: Returns the length of a string (excluding
int n = 5; the null character).
arr = (int *)malloc(n * sizeof(int)); Syntax: size_t strlen(const char *str);
if (arr == NULL) { Example:
printf("Memory allocation failed\n"); #include <stdio.h>
#include <string.h>
return 1;
} int main() {
char name[] = "Hello";
for (int i = 0; i < n; i++) {
printf("Length of the string: %lu\n",
arr[i] = i + 1; strlen(name));
return 0;
}
}
for (int i = 0; i < n; i++) {
 2. strcpy()
printf("%d ", arr[i]);
Purpose: Copies one string to another.
}
Syntax: char *strcpy(char *destination, const char
free(arr); // Free allocated memory *source);

return 0; Example:

} #include <stdio.h>
#include <string.h>
 Objective: Learn to dynamically allocate
and deallocate memory.
int main() {
4. Summary char source[] = "World";
char destination[20];
 Recap the importance of pointers in memory
manipulation and dynamic programming.
strcpy(destination, source);
 Highlight best practices: initialize pointers, printf("Copied String: %s\n", destination);
avoid dangling pointers, and free allocated return 0;
memory. }

WEEK 15  3. strcat()
1. Introduction to Strings and String Functions
Purpose: Concatenates (appends) one string to
another. int main() {
char source[] = "Hello World";
Syntax: char *strcat(char *destination, const char
char destination[6];
*source);
Example: strncpy(destination, source, 5);
destination[5] = '\0'; // Manually adding null
#include <stdio.h>
character
#include <string.h>
printf("Copied String: %s\n", destination);
return 0;
int main() {
}
char str1[20] = "Hello ";
char str2[] = "World";

strcat(str1, str2);
printf("Concatenated String: %s\n", str1);
return 0;
}
 4. strcmp()
Purpose: Compares two strings lexicographically.
Syntax: int strcmp(const char *str1, const char
*str2);
Return Values:
0: Strings are equal.
< 0: First string is less than the second.
> 0: First string is greater than the second.
Example:
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Apple";
char str2[] = "Banana";

int result = strcmp(str1, str2);


if (result == 0) {
printf("Strings are equal.\n");
} else if (result < 0) {
printf("%s is less than %s\n", str1, str2);
} else {
printf("%s is greater than %s\n", str1, str2);
}
return 0;
}
 5. strncpy() (Safe Copy)
Purpose: Copies up to a specified number of
characters from one string to another.
Syntax: char *strncpy(char *destination, const char
*source, size_t num);
Example:
#include <stdio.h>
#include <string.h>

You might also like