Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
14 views18 pages

C Prog Notes

notes
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)
14 views18 pages

C Prog Notes

notes
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/ 18

📘 Module 1 – Flowcharts, Algorithms, and

Basics of C

Flowcharts and Algorithms

Every program begins with a logical plan. An algorithm is a step-by-step sequence of


instructions designed to solve a particular problem. Algorithms are written in plain English or
pseudocode so that they can be understood easily. For example, if we want to calculate the sum
of two numbers, the algorithm can be written as: start the program, read two numbers, add them,
display the result, and then stop. To make this logic clearer, we often use flowcharts. A
flowchart uses standardized symbols: an oval for start and stop, a parallelogram for input and
output operations, a rectangle for processes like calculations, and a diamond for decision making.
Flowcharts are helpful because they give a visual representation of the problem-solving process
before we begin coding.

Overview of C

Once we have an algorithm or flowchart, we convert it into a program. The C language was
developed in 1972 by Dennis Ritchie at Bell Laboratories. It soon became the most widely used
programming language because UNIX, a powerful operating system, was written in C. The
importance of C lies in its portability, structured programming style, and its position as a middle-
level language—it supports both low-level operations such as bit manipulation and high-level
constructs such as structured program design. Because of these features, C has influenced many
later languages such as C++, Java, and even aspects of Python.

A basic C program has a structure that always begins with preprocessor directives, followed by
the main() function where execution starts. Inside the main function, we declare variables, write
our logic, and provide input/output operations. For example:

#include <stdio.h>
int main() {
int a, b, sum;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum = %d", sum);
return 0;
}

This program highlights the basic elements of a C program: header files for input/output, the
main() function, variable declarations, computation, and finally, output.
Constants, Variables, and Data Types

In C, we use variables to store data values. A variable is simply a name given to a memory
location. For instance, an integer variable age may hold the value 20. Constants, on the other
hand, are fixed values that do not change during the execution of a program. They can be defined
using #define or the const keyword. For example:

const float PI = 3.14159;

This ensures that the value of PI remains constant throughout the program.

C provides different data types to represent different kinds of values. The int type stores
integers, float stores decimal numbers with single precision, double allows more precision, and
char stores single characters. Each has its own size in memory—integers usually take 2 or 4
bytes, floats 4 bytes, doubles 8 bytes, and characters 1 byte. Understanding data types helps in
efficient memory usage and correct program behavior.

Declaring and Assigning Variables

Before using a variable in C, it must be declared with its data type. For instance:

int x; // Declaration
x = 10; // Assignment
int y = 20; // Declaration with initialization

We can also define symbolic constants using #define to avoid using “magic numbers” in
programs. For example, instead of repeatedly writing 3.14159, we define #define PI 3.14159.

Input and Output in C

C interacts with the user through the printf and scanf functions. printf displays information
on the screen, while scanf reads data from the user. Both use format specifiers—%d for integers,
%f for floating-point values, %c for characters, and %s for strings. For instance:

int age;
printf("Enter age: ");
scanf("%d", &age);
printf("Age = %d", age);

Here, the ampersand & in scanf is used to provide the memory address of the variable where the
input will be stored.
Example Programs

To see all these ideas in action, let us look at two simple programs. The first one converts a
temperature in Celsius to Fahrenheit:

#include <stdio.h>
int main() {
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 9 / 5) + 32;
printf("Temperature in Fahrenheit = %.2f", fahrenheit);
return 0;
}

The second program calculates the area of a circle, making use of a symbolic constant for pi:

#include <stdio.h>
#define PI 3.14159
int main() {
float radius, area;
printf("Enter radius: ");
scanf("%f", &radius);
area = PI * radius * radius;
printf("Area of Circle = %.2f", area);
return 0;
}

Conclusion

In this first module, we have learned how problem solving begins with algorithms and
flowcharts, how C emerged as a powerful and portable programming language, the structure of a
C program, and the use of variables, constants, and data types. We also explored input and output
through scanf and printf. These concepts form the foundation for everything that follows in C
programming.
📘 Module 2 – Operators, Decision Making,
and Looping

Operators in C

In programming, operators are symbols that tell the compiler to perform specific operations on
data. C provides a rich set of operators to handle computations, comparisons, and logical
decisions. The most basic are the arithmetic operators, such as +, -, *, /, and %. They work on
numerical values to perform addition, subtraction, multiplication, division, and modulus
(remainder) operations. For example, a % b gives the remainder when a is divided by b.

C also includes relational operators, such as ==, !=, <, >, <=, and >=. These are used to compare
two values and the result is always either true (1) or false (0). Logical decisions often depend on
these results. For example, the condition age >= 18 becomes true if age is 18 or more, otherwise
false.

To combine conditions, we use logical operators. The && operator represents logical AND, ||
represents logical OR, and ! represents logical NOT. These are essential in situations where
multiple conditions must be evaluated together.

There are also assignment operators, the simplest being = which assigns a value to a variable.
Compound assignment operators like +=, -=, *=, and /= allow us to update the value of a
variable more compactly. Similarly, increment and decrement operators (++ and --) are
shorthand notations to increase or decrease a variable’s value by one.

Finally, C has the conditional operator (also called the ternary operator ?:). It is a compact
form of if-else. For instance, max = (a > b) ? a : b; assigns the greater of two numbers to
max.

Because many operators can appear in the same expression, C defines a clear precedence of
operators. For example, multiplication and division are evaluated before addition and
subtraction. Parentheses can always be used to make the order of evaluation explicit.

Decision Making in C

Programming often requires making choices. C provides decision-making statements to control


the flow of execution. The simplest is the if statement, which executes a block of code only if a
condition is true. For example:

if (marks >= 35) {


printf("Pass");
}

If we need to choose between two alternatives, we use the if-else statement. For example:

if (marks >= 35) {


printf("Pass");
} else {
printf("Fail");
}

When multiple conditions need to be checked, nested if-else statements can be used.
Alternatively, the else-if ladder provides a more readable approach:

if (marks >= 85) {


printf("Distinction");
} else if (marks >= 60) {
printf("First Class");
} else if (marks >= 35) {
printf("Pass");
} else {
printf("Fail");
}

Another useful construct is the switch statement, which allows selection among many options
based on the value of an expression. Each option is written as a case. For example:

switch(day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid day");
}

The default case is executed when none of the other cases match.

In rare situations, programmers may use the goto statement to transfer control unconditionally
to a labeled part of the program. However, this is discouraged because it makes code harder to
read and maintain.

Looping in C

Often we need to repeat a set of instructions multiple times. C provides loops for such repetitive
tasks. The while loop executes a block of code as long as a given condition is true. For example:

int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}

This loop prints numbers from 1 to 5.

The do-while loop is similar, but the condition is checked after executing the loop body. This
ensures that the loop body runs at least once, even if the condition is false initially. For instance:

int num;
do {
printf("Enter a number (0 to stop): ");
scanf("%d", &num);
} while (num != 0);

The for loop is the most compact form and is widely used when the number of iterations is
known. It combines initialization, condition checking, and update in one line:

for (int i = 1; i <= 5; i++) {


printf("%d ", i);
}

Within loops, special statements allow finer control. The break statement terminates the loop
immediately, while the continue statement skips the current iteration and proceeds with the next
one.

Example Programs

1. Find the largest of three numbers using if-else:

#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);

if (a >= b && a >= c)


printf("Largest = %d", a);
else if (b >= a && b >= c)
printf("Largest = %d", b);
else
printf("Largest = %d", c);

return 0;
}

2. Print multiplication table using for loop:

#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);

for (int i = 1; i <= 10; i++) {


printf("%d x %d = %d\n", n, i, n * i);
}
return 0;
}

3. Check whether a number is prime using while loop:

#include <stdio.h>
int main() {
int n, i = 2, flag = 1;
printf("Enter a number: ");
scanf("%d", &n);

while (i <= n / 2) {
if (n % i == 0) {
flag = 0;
break;
}
i++;
}

if (flag && n > 1)


printf("%d is a prime number", n);
else
printf("%d is not a prime number", n);

return 0;
}

Conclusion

This module taught us the use of operators for performing calculations and comparisons, and
how decision-making statements like if-else and switch control program flow. We also
explored loops such as while, do-while, and for, which allow us to repeat tasks efficiently.
Together, these constructs form the backbone of problem-solving in C, making it possible to
handle complex logic and repetitive tasks with ease.
📘 Module 3 – Arrays and Strings

Introduction to Arrays

In many problems, we need to store and process a collection of data items, such as marks of 50
students or salaries of 100 employees. Using individual variables for each value is not practical.
C provides arrays, which are collections of elements of the same data type, stored in contiguous
memory locations. Each element is accessed by an index, starting from zero.

For example, an array of integers to store the marks of 5 students can be declared as:

int marks[5];

Here, marks[0] refers to the first element, marks[1] to the second, and so on. Arrays make it
easy to process large volumes of data using loops.

Declaration and Initialization of Arrays

Arrays must be declared before use, specifying the type and the number of elements.
Initialization can be done at the time of declaration.

int numbers[5] = {10, 20, 30, 40, 50};

If fewer values are provided, the remaining elements are initialized to zero. For example:

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

This creates an array with values {1, 2, 0, 0, 0}.

Two-Dimensional Arrays

Sometimes data is organized in rows and columns, such as a matrix. For this, C provides two-
dimensional arrays. A 2D array can be declared as:

int matrix[3][3];
This creates a 3×3 matrix with 9 elements. Two-dimensional arrays are accessed with two
indices, for row and column. For example, matrix[0][1] refers to the element in the first row
and second column.

Example Program: Matrix Transpose


#include <stdio.h>
int main() {
int a[3][3], transpose[3][3];
printf("Enter elements of 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
transpose[j][i] = a[i][j];
}
}
printf("Transpose of the matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}

Introduction to Strings

In C, a string is a sequence of characters terminated by a special null character \0. Unlike in


higher-level languages, strings in C are represented as arrays of type char.

For example:

char name[10] = "C Language";

Here, the array name stores the characters C, , L, a, … and finally \0 at the end.

Declaring and Initializing Strings

Strings can be declared and initialized in two ways:


char str1[6] = {'H','e','l','l','o','\0'};
char str2[6] = "Hello";

The second form is simpler and more common.

Reading and Writing Strings

Strings can be read using scanf and displayed using printf.

char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello %s", name);

Here, %s is the format specifier for strings. However, note that scanf stops reading at a
whitespace. To read a full line with spaces, we use the gets function (though it is unsafe and
replaced by fgets in modern compilers).

Arithmetic and Comparison of Characters

Since characters are internally stored as ASCII codes, arithmetic operations are possible. For
example, 'A' + 1 gives 'B'. Comparison operators also work, so "cat" > "bat" evaluates true
because ASCII value of 'c' is greater than 'b'.

String-Handling Functions

C provides many library functions in <string.h> to manipulate strings.

 strlen(str) – returns length of string


 strcpy(dest, src) – copies one string to another
 strcat(str1, str2) – concatenates two strings
 strcmp(str1, str2) – compares two strings

Example Program: Concatenate Two Strings


#include <stdio.h>
#include <string.h>
int main() {
char str1[50], str2[50];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);

strcat(str1, str2);
printf("Concatenated String = %s", str1);
return 0;
}

Example Program: Compare Two Strings


#include <stdio.h>
#include <string.h>
int main() {
char str1[20], str2[20];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);

if (strcmp(str1, str2) == 0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

Conclusion

In this module, we explored arrays for handling large sets of data and two-dimensional arrays
for working with matrices. We then studied strings, which are arrays of characters, and the
various functions provided by the C standard library to process them. Arrays and strings are
indispensable in solving real-world problems such as handling student records, manipulating
text, and performing matrix operations.
📘 Module 4 – User-Defined Functions

Introduction

As programs grow larger, writing everything inside main() becomes unmanageable. To improve
readability, reusability, and modularity, C allows us to divide a program into smaller parts called
functions. A function is a block of code that performs a specific task. C already provides many
built-in library functions such as printf(), scanf(), strlen(), and sqrt(). But in addition to
these, programmers can also define their own functions, called user-defined functions.

Need for User-Defined Functions

Functions bring several advantages to programming:

1. Modularity – The program is divided into smaller units, each handling a specific job.
2. Reusability – Once defined, a function can be used many times in the program without
rewriting the code.
3. Simplicity – Each function can be developed, tested, and debugged independently.
4. Maintainability – If a change is needed, only the function definition must be updated.

For example, if we need to compute the factorial of numbers at many points in a program, it is
convenient to write a factorial function once and call it whenever needed.

Elements of a Function

Every user-defined function in C has the following elements:

1. Function Definition – This specifies what the function does.


2. int square(int n) {
3. return n * n;
4. }
5. Function Declaration (Prototype) – Tells the compiler about the function’s name,
return type, and parameters, before it is used.
6. int square(int n);
7. Function Call – Invokes the function to perform its task.
8. int result = square(5);

Thus, the three steps—declaration, definition, and call—make functions work seamlessly in C.
Return Values and Their Types

A function may or may not return a value. If it returns, the type must be specified. For instance, a
function that computes the sum of two integers returns an integer:

int add(int a, int b) {


return a + b;
}

Some functions, like those that only print a message, may not return anything. In such cases, the
return type is void.

Different Types of Functions

Depending on whether arguments are passed and whether return values are provided, functions
can be of different categories:

1. No arguments, no return value – Performs a task but does not take inputs or return
outputs.
2. void greet() {
3. printf("Hello, welcome to C programming!");
4. }
5. Arguments but no return value – Takes input values but does not return a result.
6. void printSquare(int n) {
7. printf("Square = %d", n * n);
8. }
9. No arguments but return value – Produces a result without taking any inputs.
10. int giveNumber() {
11. return 100;
12. }
13. Arguments with return value – The most common type, takes inputs and produces a
result.
14. int max(int x, int y) {
15. if (x > y)
16. return x;
17. else
18. return y;
19. }

Nesting of Functions

One function can call another function. This is called nesting of functions. For example, a
function to calculate the area of a circle might call another function to compute the square of a
number.

float square(float x) {
return x * x;
}

float areaOfCircle(float r) {
return 3.14159 * square(r);
}

Here, the areaOfCircle function calls the square function internally.

Example Programs

1. Factorial using a function

#include <stdio.h>
int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial = %d", factorial(num));
return 0;
}

2. Greatest Common Divisor (GCD) using functions

#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("GCD = %d", gcd(x, y));
return 0;
}

Conclusion
This module introduced the idea of user-defined functions in C. We learned why they are
needed, the elements involved in defining and calling them, and the different categories based on
arguments and return values. Functions make programs more organized, reusable, and easier to
maintain. Mastery of functions is essential, as they form the foundation for structured
programming and are heavily used in larger projects.

📘 Module 5 – Structures and Pointers

Introduction to Structures

So far, we have dealt with simple data types like integers, floats, and characters. These types
allow us to store single values. However, real-world problems often require grouping different
types of data together. For example, to represent an employee, we need to store their ID (an
integer), name (a string), and salary (a float). Using separate variables for each employee
becomes messy.

To solve this, C provides structures, which are user-defined data types that group variables of
different types under a single name. A structure creates a new data type that can represent a more
complex entity.

Defining and Using Structures

A structure is defined using the struct keyword. For example:

struct Employee {
int id;
char name[30];
float salary;
};

This defines a structure called Employee with three members. Once defined, we can declare
variables of this structure type:

struct Employee e1;

The members are accessed using the dot (.) operator:

e1.id = 101;
strcpy(e1.name, "Alice");
e1.salary = 50000.75;
printf("%d %s %.2f", e1.id, e1.name, e1.salary);

Initialization, Copying, and Arrays of Structures

A structure variable can be initialized at the time of declaration:

struct Employee e2 = {102, "Bob", 60000.50};

One structure variable can be assigned to another of the same type (copying):

struct Employee e3 = e2;

We can also create arrays of structures to store multiple records:

struct Employee employees[3];

This is particularly useful for handling student databases, employee payrolls, and book
inventories.

Example Program: Find Employee with Higher Salary


#include <stdio.h>
#include <string.h>
struct Employee {
int id;
char name[30];
float salary;
};
int main() {
struct Employee e1 = {101, "Alice", 55000.50};
struct Employee e2 = {102, "Bob", 65000.75};

if (e1.salary > e2.salary)


printf("%s has a higher salary", e1.name);
else
printf("%s has a higher salary", e2.name);

return 0;
}

Pointers in C

A pointer is a variable that stores the memory address of another variable. While normal
variables directly contain values, pointers contain addresses. For example:
int a = 10;
int *p; // pointer to int
p = &a; // p stores address of a

Here, p holds the address of a. Using the dereference operator *, we can access the value stored
at that address:

printf("%d", *p); // prints 10

Thus, pointers provide a way to directly access and manipulate memory.

Initialization and Pointer Arithmetic

Pointers must be initialized before use, usually with the address of a variable. Since arrays are
stored in contiguous memory locations, pointers are very useful in traversing arrays. For
instance, the name of an array acts as a pointer to its first element.

int arr[3] = {10, 20, 30};


int *p = arr;
printf("%d", *(p+1)); // prints 20

Here, pointer arithmetic allows moving to the next element.

Example Program: Add Two Numbers Using Pointers


#include <stdio.h>
int main() {
int a, b, sum;
int *p1, *p2;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);

p1 = &a;
p2 = &b;

sum = *p1 + *p2;


printf("Sum = %d", sum);

return 0;
}

Pointers with Structures

Pointers can also point to structures. Instead of using the dot operator, we use the arrow operator
(->) to access members through a pointer.
struct Student {
int roll;
char name[30];
};
int main() {
struct Student s1 = {1, "Rahul"};
struct Student *ptr = &s1;

printf("%d %s", ptr->roll, ptr->name);


return 0;
}

This is useful when passing structures to functions, as it avoids copying large amounts of data.

Conclusion

In this module, we explored structures, which allow grouping of heterogeneous data types into a
single entity, and pointers, which give us direct access to memory and provide powerful features
like pointer arithmetic and dynamic data handling. Together, structures and pointers make C a
flexible language capable of handling complex data representations, such as linked lists, trees,
and other advanced data structures.

You might also like