0% found this document useful (0 votes)
7 views34 pages

BIT2201-BIT1210 Computer Programming Methodology Notes

The document outlines a C programming course covering fundamental concepts, programming languages, and the program development process. It includes structured lessons on programming concepts, design tools, data types, operators, and error types, along with class tasks and assignments for practical application. The course emphasizes the importance of clarity, efficiency, and maintainability in programming.

Uploaded by

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

BIT2201-BIT1210 Computer Programming Methodology Notes

The document outlines a C programming course covering fundamental concepts, programming languages, and the program development process. It includes structured lessons on programming concepts, design tools, data types, operators, and error types, along with class tasks and assignments for practical application. The course emphasizes the importance of clarity, efficiency, and maintainability in programming.

Uploaded by

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

Programming in C – May/Aug 2025

BIT2201 computer Programming


methodology notes – Groups
BHRIM/BSS/BSNE/BEDS
Programming in C - Week 1: Introduction to
Programming
Objectives
By the end of this lesson, students should be able to:

1. Understand basic programming concepts.


2. Differentiate between various programming languages.
3. Comprehend the program development process and its stages.

1. Programming Concepts
Programming involves writing instructions for a computer to perform tasks. Key concepts
include:

 Algorithm: A step-by-step approach to solving a problem.


 Source Code: The human-readable instructions written in a programming language.
 Compilation: The process of converting source code into machine code.
 Execution: Running the compiled program to perform tasks.
 Debugging: Finding and fixing errors in a program.

Example of a Simple C Program:


#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}

2. Programming Languages
Programming languages are classified into different types:
Programming in C – May/Aug 2025
a) Low-Level Languages

 Machine Language: Binary code (0s and 1s) directly understood by the CPU.
 Assembly Language: Uses symbolic representations of machine instructions.

b) High-Level Languages

 Procedural Languages: C, Pascal – follow a step-by-step approach.


 Object-Oriented Languages: Java, C++ – based on objects and classes.
 Scripting Languages: Python, JavaScript – used for automation and web development.

3. Program Development and Design


Developing a program follows a structured approach:

Stages of Program Development

1. Problem Definition: Understanding what the program should do.


2. Algorithm Design: Writing step-by-step procedures.
3. Coding: Writing the program in a programming language.
4. Compilation: Translating the code into machine language.
5. Testing and Debugging: Checking for errors and fixing them.
6. Execution and Maintenance: Running the program and updating it as needed.

Example Algorithm: Calculate the Area of a Rectangle

1. Start
2. Read length and width
3. Compute area = length * width
4. Print area
5. Stop

Flowchart for Rectangle Area Calculation:

Start
|
[Input length, width]
|
[area = length * width]
|
[Print area]
|
Stop
Programming in C – May/Aug 2025
Class Tasks
Task 1

Define key programming concepts and provide real-world examples.

Task 2

Differentiate between low-level and high-level programming languages with examples.

Task 3

Write an algorithm and draw a flowchart for a program that converts temperature from Celsius to
Fahrenheit.

Assignments
Assignment 1

Write a simple C program that takes user input for two numbers and prints their sum.

Assignment 2

Explain the stages of program development with examples.

Conclusion
Understanding programming concepts, language types, and the development process is crucial
for writing efficient programs. A structured approach ensures that programs are clear, efficient,
and maintainable.

Programming in C - Week 2: Program


Design Tools, Program Features, and Errors
Objectives
Programming in C – May/Aug 2025
By the end of this lesson, students should be able to:

1. Understand program design tools such as algorithms, flowcharts, and decision trees.
2. Identify the features of a well-designed program.
3. Recognize different types of program errors and their causes.

1. Program Design Tools


Before writing a program, it is essential to design it using structured tools. The main tools are:

a) Algorithms

An algorithm is a step-by-step procedure to solve a problem.

Example Algorithm: Finding the Sum of Two Numbers

1. Start
2. Declare variables a, b, and sum.
3. Read values of a and b.
4. Compute sum = a + b.
5. Print sum.
6. Stop

b) Flowcharts

A flowchart is a graphical representation of an algorithm using symbols.

Basic Flowchart Symbols:

Symbol Meaning
Oval Start/Stop
Parallelogra Input/Output
m
Rectangle Process (Calculation)
Diamond Decision

Example Flowchart for Adding Two Numbers:

Start
|
[Input a, b]
|
[sum = a + b]
|
Programming in C – May/Aug 2025
[Print sum]
|
Stop

c) Decision Trees

A decision tree is a diagram that represents different choices and their possible outcomes.

Example: A decision tree for grading a student:

Start
|
Score >= 50?
/ \
Yes No
"Pass" "Fail"

2. Features of a Good Program


A well-designed program should have the following characteristics:

1. Clarity and Readability: Proper indentation and meaningful variable names.


2. Efficiency: Uses minimal resources (memory and processing time).
3. Modularity: Divides the program into reusable functions.
4. Robustness: Can handle invalid inputs and errors.
5. Maintainability: Easy to update and modify.

3. Types of Program Errors


Errors in a program can be classified into three types:

a) Syntax Errors

 Occur when the program violates the language rules.


 Example:

int main() {
printf("Hello, World!\n") // Missing semicolon
return 0;
}

b) Logical Errors

 The program runs but produces incorrect results.


Programming in C – May/Aug 2025
 Example:

int main() {
int a = 5, b = 2;
printf("Sum: %d\n", a - b); // Wrong operator used
return 0;
}

c) Runtime Errors

 Occur when the program is running, such as division by zero.


 Example:

int main() {
int x = 10, y = 0;
printf("Result: %d\n", x / y); // Division by zero error
return 0;
}

Class Tasks
Task 1

Write an algorithm and draw a flowchart for finding the largest of three numbers.

Task 2

Create a simple C program that demonstrates syntax, logical, and runtime errors, then fix them.

Task 3

List and explain five features of a good program with examples.

Assignments
Assignment 1

Write a C program to calculate the factorial of a number using a decision tree approach.

Assignment 2

Identify and explain three common errors in C programming with examples.


Programming in C – May/Aug 2025

Conclusion
Program design tools such as algorithms, flowcharts, and decision trees help in writing structured
programs. A good program should be clear, efficient, modular, and robust. Understanding
syntax, logical, and runtime errors is essential for debugging and writing reliable programs.

Programming in C - Week 3: Introduction to


C Programming
Objectives
By the end of this lesson, students should be able to:

1. Understand the layout of a C program and its essential sections.


2. Identify and use different data types and variables.
3. Differentiate between constants and variables in C.
4. Perform input and output operations using standard functions.
5. Write and evaluate expressions and statements in C.

1. Layout of a C Program
A C program follows a structured layout that consists of different sections:

#include <stdio.h> // Preprocessor Directive

// Function Declaration
int main() {
// Variable Declaration
int a;

// Input and Processing


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

// Output
printf("You entered: %d\n", a);

return 0; // Return Statement


}
Programming in C – May/Aug 2025
Explanation of Sections:

1. Preprocessor Directives: Includes necessary header files, e.g., #include <stdio.h>.


2. Function Definition: The main() function is the entry point of a C program.
3. Variable Declaration: Declares variables to store data.
4. Input and Output: Uses printf() for output and scanf() for input.
5. Return Statement: Ends the main() function with return 0;.

2. Data Types and Variables


Data types specify the type of data that a variable can hold.

Data Type Size Example


int 4 bytes int age = 25;
float 4 bytes float pi = 3.14;
double 8 bytes double g = 9.81;
char 1 byte char grade = 'A';

Example:

#include <stdio.h>
int main() {
int age = 25;
float height = 5.9;
char grade = 'A';
printf("Age: %d, Height: %.1f, Grade: %c\n", age, height, grade);
return 0;
}

3. Constants
Constants are fixed values that do not change during program execution.

a) Using #define (Preprocessor Directive)


#define PI 3.1416
int main() {
printf("Value of PI: %f\n", PI);
return 0;
}

b) Using const Keyword


int main() {
Programming in C – May/Aug 2025
const int MAX = 100;
printf("Max value: %d\n", MAX);
return 0;
}

4. Input and Output Operations


C uses scanf() for input and printf() for output.

Example:

#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}

5. Expressions and Statements


a) Expressions

An expression is a combination of variables, constants, and operators. Example:

int sum = a + b;

b) Statements

A statement performs an action and ends with a semicolon (;). Example:

printf("Hello, World!\n");

Class Tasks
Task 1

Write a C program that declares an int, float, and char variable, assigns values, and prints
them.

Task 2

Write a C program that uses a constant and prints its value.


Programming in C – May/Aug 2025
Task 3

Write a program that takes two numbers as input and prints their sum.

Assignments
Assignment 1

Write a C program that takes user input for name, age, and grade, then prints them using
printf().

Assignment 2

Write a C program that calculates the area of a circle using PI = 3.1416.

Conclusion
Understanding the structure of a C program, data types, input/output operations, and expressions
is fundamental to writing efficient C programs. Mastery of these concepts will enable the
development of more complex applications.

Programming in C - Week 4: Operators,


Type Conversion, Comments, and Reserved
Words
Objectives
By the end of this lesson, students should be able to:

1. Understand different types of operators in C.


2. Use operands effectively in expressions.
Programming in C – May/Aug 2025
3. Perform type conversion (casting) in C programs.
4. Write and use comments in C programs.
5. Identify system-reserved words in C.

Assignment- Key

Falcon - Download and install In PC, Play store IDE In C programming.

Procedure of running a program in C using Falcon

Definition of Terms
 Operator: A symbol that performs an operation on one or more operands.
 Operand: A value or variable on which an operator acts.
 Type Conversion (Casting): The process of converting one data type to another.
 Comment: A line of code ignored by the compiler, used to describe or explain code.
 Reserved Words: Predefined keywords in C that cannot be used as identifiers.

1. Operator Types and Operands


Operators in C are classified into different types:

a) Arithmetic Operators

Used for basic mathematical operations:

Operator Description Example


+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus a % b
(remainder)

Example:

#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Sum: %d\n", a + b);
Programming in C – May/Aug 2025
printf("Difference: %d\n", a - b);
printf("Product: %d\n", a * b);
printf("Quotient: %d\n", a / b);
printf("Remainder: %d\n", a % b);
return 0;
}

b) Relational (Comparison) Operators

Used to compare values:

Operator Description Example


== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

Example:

if (a > b) {
printf("a is greater than b\n");
}

c) Logical Operators

Used for logical expressions:

Operator Description Example


&& Logical AND (a > 0 && b > 0)
` `
! Logical NOT !(a > b)

Example:

if (a > 0 && b > 0) {


printf("Both are positive\n");
}

d) Assignment Operators

Used to assign values to variables:


Programming in C – May/Aug 2025
Operator Exampl Equivalent To
e
= a = b a = b
+= a += b a = a + b
-= a -= b a = a - b
*= a *= b a = a * b
/= a /= b a = a / b
%= a %= b a = a % b

Example:

int a = 10;
a += 5; // Equivalent to a = a + 5;

e) Bitwise Operators

Operate at the binary level.

Operator Description Example


& AND a & b
` ` OR
^ XOR a ^ b
<< Left shift a << 1
>> Right shift a >> 1

Example:

int a = 5; // 0101 in binary


int b = a << 1; // Left shift: 1010 (10 in decimal)

2. Type Conversion (Casting)


a) Implicit Type Conversion

The compiler automatically converts data types.

int a = 10;
double b = a; // a is automatically converted to double

b) Explicit Type Conversion (Casting)

Manually converting data types using (type).

int a = 10, b = 3;
double result = (double)a / b;
printf("Result: %.2f\n", result);
Programming in C – May/Aug 2025

3. Comments in C
Comments are ignored by the compiler and help document the code.

a) Single-line comment
// This is a single-line comment
printf("Hello, World!\n");

b) Multi-line comment
/* This is a
multi-line comment */
printf("Hello, World!\n");

4. System Reserved Words


Reserved words are predefined keywords in C that cannot be used as variable names.

Reserved Word Reserved Word


int double
char float
return if
else switch
while for
do break
continue void
static const

Example:

int main() {
int number = 10; // 'int' is a reserved word
return 0;
}

Class Tasks
Task 1

Write a program to perform the following operations on two numbers:

 Addition
Programming in C – May/Aug 2025
 Subtraction
 Multiplication
 Division
 Modulus

Task 2

Write a program to demonstrate type conversion:

 Assign an int to a double variable.


 Use explicit casting in a division operation.

Task 3

Write a program that prints a message using both single-line and multi-line comments.

Assignments
Assignment 1

Write a program that takes two numbers as input and uses logical operators to:

 Check if both numbers are positive.


 Check if at least one number is positive.
 Check if neither number is positive.

Assignment 2

Write a program that prints a table of 10 reserved words and their meanings.

Conclusion

Understanding operators, operands, type conversion, comments, and reserved words is essential
for writing efficient C programs. Mastering these basics will help in building more complex
applications.
Programming in C – May/Aug 2025
Week 5: Control Structures
Objectives
By the end of this lesson, students should be able to:

1. Understand and use sequential execution in C programs.


2. Implement loops (for, while, do-while) to control program flow.
3. Utilize selection structures (if, else if, nested if..else, switch) for decision-making.
4. Write simple C programs that incorporate control structures effectively.

Definition of Terms
 Control Structures: Constructs that dictate the flow of execution in a program.
 Sequential Execution: Statements are executed one after another in the order they
appear.
 Looping (Iteration): Repeating a block of code multiple times.
 Selection (Decision Making): Choosing between multiple execution paths based on
conditions.

1. Sequential Execution
Sequential execution follows a top-to-bottom approach. Example:

#include <stdio.h>
int main() {
printf("Hello, world!\n");
printf("This is sequential execution.\n");
return 0;
}

Explanation:

 The printf function prints messages on the screen.


 Execution follows the order in which statements appear.

2. Loop Structures
Programming in C – May/Aug 2025
Loops allow repeated execution of a block of code.

a) The for loop

Used when the number of iterations is known.

#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}

Explanation:

1. int i = 1; initializes the loop control variable.


2. i <= 5; is the condition for continuation.
3. i++ increments i after each iteration.
4. The loop prints numbers from 1 to 5.

b) The while loop

Executes as long as the condition is true.

#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("Iteration %d\n", i);
i++;
}
return 0;
}

Explanation:

 while (i <= 5) ensures execution continues until i becomes 6.


 i++ increments i in each iteration.

c) The do-while loop

Executes at least once before checking the condition.

#include <stdio.h>
Programming in C – May/Aug 2025
int main() {
int i = 1;
do {
printf("Iteration %d\n", i);
i++;
} while (i <= 5);
return 0;
}

Explanation:

 The block runs at least once before checking while (i <= 5).

3. Selection Structures
a) if Statement

Executes a block if the condition is true.

if (x > 0) {
printf("x is positive\n");
}

b) if-else Statement

Executes one block if the condition is true, another if false.

if (x > 0) {
printf("x is positive\n");
} else {
printf("x is not positive\n");
}

c) Nested if-else
if (x > 0) {
printf("Positive\n");
} else if (x == 0) {
printf("Zero\n");
} else {
printf("Negative\n");
}

d) switch Statement

Used when multiple values need to be checked against a variable.


Programming in C – May/Aug 2025
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
default: printf("Invalid day\n");
}
return 0;
}

Explanation:

 The case labels compare day to values.


 break prevents fall-through.

Class Tasks
Task 1

Write a program that prints numbers from 1 to 10 using:

1. for loop
2. while loop
3. do-while loop

Task 2

Write a program that checks if a number is even or odd using if-else.

Task 3

Write a program that takes a day number (1-7) as input and prints the corresponding day using
switch.

Assignments
Assignment 1

Write a program that prints the sum of even numbers from 1 to 100 using a loop.
Programming in C – May/Aug 2025
Assignment 2

Write a program that asks the user for their age and:

 Prints "Minor" if age < 18


 Prints "Adult" if age is between 18 and 60
 Prints "Senior" if age > 60

Use if-else to implement this.

Conclusion

Control structures help direct program execution logically. Understanding loops and decision-
making statements is crucial for writing efficient C programs.

Week 6- CAT 1 (Skills Week)

Week 7: Functions in C
Learning Objectives
By the end of this lesson, students should be able to:

1. Define a function and explain its purpose in programming.


2. Differentiate between system functions and user-defined functions.
3. Understand function prototypes (function declaration).
4. Write function definitions (implementations).
5. Use function calls effectively in a C program.

Definition of Terms
1. Function: A block of code that performs a specific task and can be reused multiple times
in a program.
2. System Functions: Predefined functions provided by C, such as printf(), scanf(),
sqrt().
3. User-Defined Functions: Functions created by the programmer to perform specific
tasks.
Programming in C – May/Aug 2025
4. Function Prototype (Declaration): A statement that tells the compiler about a function’s
name, return type, and parameters before its actual definition.
5. Function Definition (Implementation): The actual code block of a function where the
logic is written.
6. Function Call: A statement used to execute a function in a program.

System Functions vs. User-Defined Functions


Example of a System Function:
#include <stdio.h>
#include <math.h>

int main() {
double num = 16.0;
double result = sqrt(num);
printf("Square root of %.2f is %.2f", num, result);
return 0;
}

Example of a User-Defined Function:


#include <stdio.h>

// Function Prototype
int addNumbers(int a, int b);

int main() {
int sum = addNumbers(5, 7);
printf("Sum: %d", sum);
return 0;
}

// Function Definition
int addNumbers(int a, int b) {
return a + b;
}

Function Prototypes (Declaration)


A function prototype informs the compiler about the function name, return type, and parameters.
Example:

int multiply(int, int);

Function Definition (Implementation)


Programming in C – May/Aug 2025
The function definition contains the logic of the function. Example:

int multiply(int x, int y) {


return x * y;
}

Function Call
To use a function, we call it within main() or another function. Example:

int result = multiply(4, 5);

Step-by-Step Explanation of a Function


Example: Function to Calculate Factorial
#include <stdio.h>

// Function Prototype
t long factorial(int n);

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %ld", num, factorial(num));
return 0;
}

// Function Definition
long factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}

Breakdown:

1. Function Prototype: long factorial(int n); tells the compiler that factorial is a
function that takes an integer and returns a long integer.
2. User Input: The program takes an integer from the user.
3. Function Call: factorial(num) is called inside printf().
4. Recursive Function: The function calls itself with n-1 until n == 0.

Class Tasks
Programming in C – May/Aug 2025
Task 1: Write a function square() that returns the square of a number entered by
the user.

Task 2: Create a function isEven() that takes an integer and returns 1 if even and
0 if odd.

Task 3: Write a function gcd() to compute the greatest common divisor of two
numbers.

Assignments
Assignment 1:

Write a program that includes a function power() to calculate x^y (x raised to the power y),
where both x and y are user inputs.

Assignment 2:

Create a program with a function reverseDigits() that takes an integer and returns the
reversed number.

These tasks and assignments will help solidify your understanding of functions in C.

Week 8: Advanced Concepts in Functions


(Programming in C)
Learning Objectives
By the end of this lesson, students should be able to:

1. Differentiate between argument passing by value and by reference.


2. Use default values in function arguments.
3. Understand and implement function overloading.
4. Utilize inline functions for optimization.
Programming in C – May/Aug 2025
5. Implement recursive functions such as factorial and Fibonacci series.

Argument Passing
Functions in C can receive arguments in two ways:

1. Pass by Value: A copy of the argument is passed to the function. Changes made inside
the function do not affect the original variable.
2. Pass by Reference: The function receives a reference (memory address) of the variable,
allowing modifications to reflect outside the function.

Example: Pass by Value


#include <stdio.h>

void modifyValue(int x) {
x = x * 2;
printf("Inside function: x = %d\n", x);
}

int main() {
int num = 5;
modifyValue(num);
printf("Outside function: num = %d\n", num);
return 0;
}

Output: The original value remains unchanged outside the function.

Example: Pass by Reference


#include <stdio.h>

void modifyValue(int *x) {


*x = *x * 2;
}

int main() {
int num = 5;
modifyValue(&num);
printf("After function call: num = %d\n", num);
return 0;
}

Output: The original value is modified because the function works on its memory address.
Programming in C – May/Aug 2025
Default Values in Function Arguments
C does not support default values for function arguments like C++, but this can be simulated
using function overloading or by providing optional parameters in another way.

Example:
#include <stdio.h>

void greet(const char *name) {


if (name == NULL) {
printf("Hello, Guest!\n");
} else {
printf("Hello, %s!\n", name);
}
}

int main() {
greet(NULL); // Uses default value
greet("Alice");
return 0;
}

Function Overloading
C does not support function overloading directly. Instead, different function names or function
pointers can be used to achieve similar behavior.

Example: Simulating Function Overloading


#include <stdio.h>

int addInt(int a, int b) {


return a + b;
}

double addDouble(double a, double b) {


return a + b;
}

int main() {
printf("Sum (int): %d\n", addInt(5, 7));
printf("Sum (double): %.2f\n", addDouble(5.5, 7.5));
return 0;
}

Inline Functions
Programming in C – May/Aug 2025
C does not support inline functions like C++, but macros can achieve a similar effect by
replacing function calls with their definitions.

Macro Alternative in C:
#include <stdio.h>
#define square(x) ((x) * (x))

int main() {
printf("Square of 5: %d\n", square(5));
return 0;
}

Recursive Functions
A recursive function is a function that calls itself to solve a problem.

Example: Factorial Calculation


#include <stdio.h>

long factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

int main() {
int num = 5;
printf("Factorial of %d is %ld\n", num, factorial(num));
return 0;
}

Example: Fibonacci Series


#include <stdio.h>

int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int n = 10;
printf("Fibonacci series up to %d terms:\n", n);
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}
Programming in C – May/Aug 2025

Class Tasks
Task 1: Implement a function that swaps two numbers using pass-by-value and
pass-by-reference.

Task 2: Write a function that takes three numbers and returns the maximum,
using default arguments where applicable.

Task 3: Implement a macro function to calculate the cube of a number.

Assignments
Assignment 1:

Write a recursive function to calculate the sum of natural numbers up to n.

Assignment 2:

Write a recursive function to generate and print the first n numbers of the Fibonacci series.

These tasks and assignments will help deepen your understanding of advanced function concepts
in Programming in C.

Week 9-10: Arrays in C


Learning Objectives
By the end of this lesson, students should be able to:

1. Understand the concept of arrays.


2. Declare arrays using the correct syntax.
3. Initialize array elements in different ways.
4. Access elements of an array.
5. Perform manipulations such as summing array elements and searching for values.
Programming in C – May/Aug 2025

Concept of Arrays
An array is a collection of variables of the same type stored in contiguous memory locations.
Arrays allow multiple values to be handled using a single variable name.

Example of an Array:
int numbers[5] = {10, 20, 30, 40, 50};

Here, numbers is an array holding five integer values.

Array Declaration Syntax


The syntax for declaring an array in C:

datatype array_name[size];

Example:
int marks[10]; // Declares an integer array with 10 elements

Initializing Array Elements


Arrays can be initialized in several ways:

Method 1: Specify Values Explicitly


int arr[5] = {1, 2, 3, 4, 5};

Method 2: Partial Initialization (Remaining values set to 0)


int arr[5] = {10, 20}; // arr[2], arr[3], and arr[4] will be initialized to 0

Method 3: Initialize Without Specifying Size


int arr[] = {5, 10, 15, 20}; // Size automatically set to 4

Accessing Array Elements


Programming in C – May/Aug 2025
Array elements are accessed using their index (starting from 0).

Example:
#include <stdio.h>

int main() {
int numbers[3] = {10, 20, 30};
printf("First element: %d\n", numbers[0]);
printf("Second element: %d\n", numbers[1]);
return 0;
}

Manipulating Array Elements


Summing Array Elements
#include <stdio.h>

int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
int size = sizeof(arr) / sizeof(arr[0]);

for (int i = 0; i < size; i++) {


sum += arr[i];
}

printf("Sum of array elements: %d\n", sum);


return 0;
}

Searching for an Element in an Array


#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int key = 30;
int found = 0;
int size = sizeof(arr) / sizeof(arr[0]);

for (int i = 0; i < size; i++) {


if (arr[i] == key) {
printf("Element %d found at index %d\n", key, i);
found = 1;
break;
}
}

if (!found) {
printf("Element %d not found in array\n", key);
Programming in C – May/Aug 2025
}

return 0;
}

Class Tasks
Task 1: Write a C program to find the largest element in an array.

Task 2: Write a program that reverses the elements of an array.

Task 3: Implement a program that counts the occurrences of a given number in


an array.

Assignments
Assignment 1:

Write a program to sort an array in ascending order using the Bubble Sort algorithm.

Assignment 2:

Write a program to find the second largest number in an array.

These tasks and assignments will help deepen your understanding of Arrays in C.

Week 11-12: Pointers in C


Learning Objectives
By the end of this lesson, students should be able to:

1. Understand the concept of pointers.


2. Declare pointers using the correct syntax.
3. Use the address-of (&) and dereference (*) operators.
Programming in C – May/Aug 2025
Concept of Pointers
A pointer is a variable that stores the memory address of another variable. Pointers are powerful
and allow direct memory manipulation.

Example of a Pointer:
int a = 10;
int *p = &a; // Pointer stores the address of variable 'a'

Pointer Declaration Syntax


The syntax for declaring a pointer in C:

datatype *pointer_name;

Example:
int *ptr; // Declares a pointer to an integer

Using the Address-of Operator (&) and Dereference Operator


(*)
The address-of operator (&) is used to get the memory address of a variable. The dereference
operator (*) is used to access the value stored at a pointer's address.

Example:
#include <stdio.h>

int main() {
int num = 10;
int *ptr = &num;

printf("Value of num: %d\n", num);


printf("Address of num: %p\n", &num);
printf("Pointer ptr stores address: %p\n", ptr);
printf("Value stored at ptr: %d\n", *ptr);

return 0;
}

Explanation:

 ptr stores the address of num.


Programming in C – May/Aug 2025
 *ptr dereferences the pointer to access the value stored in num.

Class Tasks
Task 1: Write a C program to print the address of a variable using a pointer.

Task 2: Implement a pointer that swaps the values of two variables.

Task 3: Write a program that uses a pointer to modify the value of a variable.

Assignments
Assignment 1:

Write a program that demonstrates pointer arithmetic by iterating over an integer array using
pointers.

Assignment 2:

Implement a program that uses pointers to find the largest and smallest elements in an array.

These tasks and assignments will help deepen your understanding of Pointers in C.

Week 13-14: File Processing in C


Learning Objectives
By the end of this lesson, students should be able to:

1. Understand the concept of file processing.


2. Work with files and streams in C.
3. Create and manipulate sequential-access and random-access files.

Introduction to File Processing


Programming in C – May/Aug 2025
File processing allows programs to store and retrieve data permanently using files instead of
memory.

Files and Streams


C provides file handling through the FILE structure, using fopen, fclose, fread, fwrite, and
other functions.

Example:
#include <stdio.h>

int main() {
FILE *file;
file = fopen("example.txt", "w");
fprintf(file, "Hello, File Processing in C!\n");
fclose(file);
return 0;
}

Sequential Access Files


Creating a Sequential Access File
#include <stdio.h>

int main() {
FILE *file = fopen("data.txt", "w");
fprintf(file, "This is a sequential file.\n");
fclose(file);
return 0;
}

Reading Data from a Sequential Access File


#include <stdio.h>

int main() {
FILE *file = fopen("data.txt", "r");
char text[100];
fgets(text, 100, file);
printf("%s", text);
fclose(file);
return 0;
}
Programming in C – May/Aug 2025
Random Access Files
Creating and Writing to a Random Access File
#include <stdio.h>

int main() {
FILE *file = fopen("random.dat", "wb");
int data = 42;
fwrite(&data, sizeof(int), 1, file);
fclose(file);
return 0;
}

Reading Data from a Random Access File


#include <stdio.h>

int main() {
FILE *file = fopen("random.dat", "rb");
int data;
fread(&data, sizeof(int), 1, file);
printf("Read value: %d\n", data);
fclose(file);
return 0;
}

Assignments
1. Write a C program to count the number of words in a file.
2. Implement a program that appends text to an existing file and reads the contents.

These tasks will deepen your understanding of File Processing in C.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy