Unit 1.
PROBLEM SOLVING USING COMPUTERS
Introduction to problem solving: Some common problems that are solved using
computers like rail/air ticket reservation, online purchases and utility bill
payments. Defining the problem. Algorithms: Definition, Characteristics,
Advantages. Flow charts: Definition, symbols used, Advantages. Coding and
choice of proper computer language. Testing and Debugging. Analyze a
computational problem and develop an algorithm/flowchart to find its solution (6
Hrs)
Introduction to Problem Solving:
Common Problems Solved Using Computers:
● Rail/Air Ticket Reservation: Computers streamline booking processes, manage seat
availability, and facilitate transactions.
● Online Purchases: E-commerce platforms handle transactions, inventory management,
and customer orders.
● Utility Bill Payments: Automated systems manage bill generation, payment
processing, and record-keeping.
Defining the Problem: Defining a problem involves understanding its scope, requirements,
constraints, and desired outcomes. For example, in ticket reservation systems, the problem
might involve managing seat availability, confirming bookings, and handling payments
efficiently.
Algorithms:
Definition: An algorithm is a step-by-step procedure or a set of rules to be followed in problem-solving
operations. It's a precise description of a series of steps to solve a particular problem.
Characteristics:
● Accuracy: Algorithms should produce correct results for all valid inputs.
● Finiteness: They must terminate after a finite number of steps.
● Clear and Unambiguous: Each step should be well-defined and understandable.
● Efficiency: They should solve problems in a reasonable amount of time and using minimal resources.
Advantages:
● Reusability: Algorithms can be applied to similar problems.
● Standardization: They provide a structured approach to problem-solving.
● Efficiency: Well-designed algorithms can optimize resource usage.
Flowcharts:
Definition: Flowcharts are graphical representations of a process or algorithm. They use symbols to
depict different steps, decisions, or actions within the process.
Symbols Used:
● Terminal/Start-End: Indicates the beginning or end of a process.
● Process: Represents a specific action or operation.
● Decision: Represents a branching point based on a condition.
● Input/Output: Represents data input or output.
Advantages:
● Visualization: Easy-to-understand visual representation of a process.
● Clarity: Helps in understanding complex procedures.
● Communication: Effective in conveying processes to different stakeholders.
Coding and Choice of Proper Computer Language:
● Problem Requirements: Certain languages are better suited for specific tasks.
● Available Resources: Familiarity of the team with a particular language.
● Performance: Some languages are faster or more resource-efficient for certain tasks.
Testing and Debugging:
Testing: Involves running the code with various inputs to verify its correctness and ensure it meets
requirements.
Debugging: Identifying and fixing errors or bugs found during testing to make the program function
correctly.
Allocating six hours for this task allows for a detailed analysis, step breakdown, and thorough
documentation of the algorithm or flowchart to solve the identified computational problem, ensuring
accuracy and efficiency.
Unit 2. PROGRAMMING IN C
Structure of C program, Constants, Variables, Keywords,
Operators and Precedence, Input/Output statements,
Assignment statements, Preprocessor directives, Compilation
process, Decision making statements-Switch Statement and
Looping Statements
Structure of a C Program:
Documentation Section: Contains comments, including details about the
program, author, creation date, etc.
Link Section: Includes statements that specify external libraries to be linked.
Definition Section: Involves defining global constants and variables.
Main Function: The entry point of the program where execution begins.
Other Functions: Additional functions called from the main function or
elsewhere in the program.
Constants:
Constants are fixed values that do not change during the program execution. They can be of various
types:
● Numeric Constants: Integer constants (e.g., 5, -10), floating-point constants (e.g., 3.14), and
hexadecimal/octal constants.
● Character Constants: Enclosed in single quotes (e.g., 'A', '\n').
● String Constants: Series of characters enclosed in double quotes (e.g., "Hello").
Variables:
Variables are memory locations that hold values. They have a specific type (int, float, char, etc.) and a
unique name. Variables can change their values during program execution.
Keywords:
Keywords are reserved words in C that have predefined meanings and cannot be used as identifiers
(variable or function names). Examples include int, float, if, else, for, while, etc.
Operators and Precedence:
Operators perform operations on operands. They can be arithmetic (+, -, *, /), relational (<, >, <=, >=), logical (&&, ||, !), bitwise (&, |, ^),
assignment (=), etc.
Precedence refers to the order in which operators are evaluated in an expression. For instance, multiplication (*) has higher
precedence than addition (+), so in the expression 2 + 3 * 4, 3 * 4 will be evaluated first due to the precedence of the
multiplication operator.
Input/Output Statements:
● Input: scanf() function is used to take input from the user.
● Output: printf() function is used to display output on the screen.
Assignment Statements:
Assignment statements are used to assign values to variables. For example: int x = 5;
Preprocessor Directives:
Preprocessor directives are commands to the compiler that begin with #. They are processed before the compilation of the
program. Examples include #include to include header files and #define to define constants.
Compilation Process:
The compilation process involves translating the source code written in C
into machine code that the computer can understand and execute. It
typically includes the following steps:
● Preprocessing: Handles preprocessor directives.
● Compilation: Translates source code to assembly code.
● Assembly: Converts assembly code to object code.
● Linking: Combines object code with libraries to generate an
executable file.
Decision-Making Statements:
1. if-else Statement:
The if-else statement allows you to execute a block of code based on the evaluation of a condition.
int num = 10;
if (num > 0) {
// Code executes if 'num' is greater than 0
} else {
// Code executes if 'num' is not greater than 0
}
2. switch Statement:
The switch statement checks the value of a variable against multiple cases and executes the block of code associated with the matched case.
int option = 2;
switch (option) {
case 1:
// Code for case 1
break;
case 2:
// Code for case 2
break;
default:
// Code if no case matches
break;
Looping Statements:
1. for Loop:
The for loop is used when the number of iterations is known. It consists of initialization, condition, and increment/decrement.
for (int i = 0; i < 5; i++) {
// Code executes 5 times (i = 0 to 4)
}
2. while Loop:
The while loop repeats a block of code as long as a specified condition is true.
int count = 0;
while (count < 3) {
// Code executes as long as 'count' is less than 3
count++;
}
3. do-while Loop:
The do-while loop is similar to a while loop but ensures the code block executes at least once before checking the condition.
int x = 5;
do {
// Code executes at least once before checking the condition
x--;
Unit 3. ARRAYS AND STRINGS
Introduction to Arrays: Declaration, Initialization of one
dimensional array ,Multi dimensional arrays
Strings and standard operations: length, compare,
concatenate, copy
Introduction to Arrays:
Declaration of Arrays:
To declare an array in C, you specify the data type of the elements it will hold and the array's name followed by square brackets [ ] indicating
the size or number of elements in the array.
// Syntax for declaring an array
dataType arrayName[arraySize];
For example, to declare an array of integers with ten elements: int numbers[10]; // Declaring an array 'numbers' capable of holding 10
integers
Initialization of One-Dimensional Array:
Arrays can be initialized during declaration or afterward using a set of initial values enclosed in curly braces { }.
int numbers[5] = {1, 2, 3, 4, 5}; // Initializing 'numbers' with 5 integers
Alternatively, you can initialize individual elements of the array:
int numbers[5];
numbers[0] = 10; // Assigning 10 to the first element
numbers[1] = 20; // Assigning 20 to the second element
Multi-Dimensional Arrays:
Declaration of Multi-Dimensional Arrays:
A multi-dimensional array in C is an array of arrays. It can have two or more dimensions. For instance, a two-dimensional array is
like a table with rows and columns.
// Syntax for declaring a two-dimensional array
dataType arrayName[rows][columns];
For example, to declare a 2D array: int matrix[3][3]; // Declaring a 3x3 matrix
Initialization of Multi-Dimensional Arrays:
Multi-dimensional arrays can be initialized similarly to one-dimensional arrays, using nested curly braces { } to represent each
dimension.
int matrix[2][2] = {
{1, 2},
{3, 4}
}; // Initializing a 2x2 matrix
Alternatively, you can initialize individual elements in a multidimensional array.
int matrix[2][2];
matrix[0][0] = 1;
matrix[0][1] = 2;
// and so on...
Importance and Usage:
● Data Storage: Arrays provide a structured way to store elements of the same
data type.
● Access and Manipulation: Elements in arrays can be accessed and
manipulated using index values.
● Efficient Processing: Arrays facilitate efficient processing of data sets by
allowing iteration and manipulation of elements.
Strings
Strings are represented as arrays of characters terminated by a null character \0.
String handling in C involves using various standard operations like determining
length, comparing strings, concatenating them, and copying one string into another.
Strings in C:
In C, a string is an array of characters terminated by a null character ('\0'). For
example:
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// OR
char greeting[] = "Hello"; // Automatically includes the null terminato
Standard String Operations:
1. Finding String Length (strlen): The strlen() function is used to determine the length of a string. It counts
all characters in the string until the null terminator is encountered.
#include <string.h>
char str[] = "Hello";
int length = strlen(str); // length will be 5
2. Comparing Strings (strcmp): The strcmp() function compares two strings and returns an integer.
● If the strings are equal, it returns 0.
● If the first string is less than the second, it returns a negative value.
● If the first string is greater than the second, it returns a positive value.
#include <string.h>
char str1[] = "Hello";
char str2[] = "World";
Concatenating Strings (strcat): The strcat() function concatenates two strings. It appends a copy of the second string to the
end of the first string. Make sure the first string has enough space to accommodate the concatenated result.
#include <string.h>
char str1[20] = "Hello";
char str2[] = "World";
strcat(str1, str2); // str1 will be "HelloWorld"
4. Copying Strings (strcpy): The strcpy() function is used to copy one string into another. Ensure that the destination
string has enough space to hold the content of the source string.
#include <string.h>
char source[] = "Hello";
char destination[20];
strcpy(destination, source); // destination will be "Hello
Unit 4. FUNCTIONS AND POINTERS
Need for functions: Function prototype, function
definition, function call, Built-in functions, Recursion.
Declaration of Pointers Pointer arithmetic, Arrays and
pointers , Array of pointers , Pass by value, Pass by
reference
Need for Functions:
Function Prototype: A function prototype is a declaration that provides the function's signature before its actual
implementation. It includes the function name, return type, and parameters (if any). It informs the compiler about the
function's existence and its expected interface.
// Function prototype
returnType functionName(parameterType parameter);
Function Definition: A function definition contains the actual implementation of the function, where the logic or
operations are written. It consists of the function's body enclosed within curly braces {}.
// Function definition
returnType functionName(parameterType parameter) {
// Function body
}
Function Call: A function call is the process of executing a function from another part of the program. It involves using
the function's name along with the required arguments.
// Function call
Built-in Functions: Built-in functions are functions provided by the programming language or libraries that
perform specific tasks. In C, examples include printf(), scanf(), strlen(), etc. These functions are readily
available and can be used directly in the code.
#include <stdio.h>
int main() {
printf("Hello, world!\n"); // Using the built-in printf() function
return 0;
}
Recursion: Recursion is a programming technique where a function calls itself. It's often used to solve
problems by breaking them down into smaller, similar sub-problems until reaching a base case.
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
Declaration of Pointers:
● Declaration of a Pointer: A pointer is a variable that holds the memory address of another
variable. To declare a pointer, use the * symbol followed by the pointer's name and the
data type it will point to.
int *ptr; // Declaration of an integer pointer
float *floatPtr; // Declaration of a float pointer
Pointer Arithmetic:
● Pointer Arithmetic: Pointers in C can be incremented, decremented, added, or subtracted.
The pointer arithmetic depends on the data type it points to.
int *ptr;
ptr++; // Moves to the next memory location of an integer size
ptr = ptr + 2; // Moves two integers ahead
Arrays and Pointers:
● Arrays and Pointers Relationship: In C, arrays and pointers have a close
relationship. An array's name can be used as a pointer to its first element.
int arr[5]; // Declaration of an integer array
int *ptr = arr; // 'ptr' points to the first element of 'arr'
Array of Pointers:
● Array of Pointers: An array of pointers is an array in which each element is a
pointer. It can hold addresses of variables or arrays.
int *ptrArr[5]; // Array of integer pointers
Pass by Value: Pass by Value: In C, Pass by Reference: Pass by Reference:
when passing arguments to functions, they Passing by reference in C is achieved using
are passed by value by default. This means pointers. Instead of passing the value directly,
a copy of the argument's value is passed the address of the variable is passed, allowing
to the function, and modifications within modifications to reflect on the original data.
the function do not affect the original void changeValue(int *x) {
(*x) = (*x) + 5;
value. }
void changeValue(int x) {
x = x + 5; int main() {
} int num = 10;
changeValue(&num); // num gets updated
int main() { to 15
int num = 10; return 0;
changeValue(num); // num remains }
unchanged
Unit-5: Structures
Need for structure data type. Creating and accessing
elements of structures Pointer and Structures, Array of
structures, Dynamic memory allocation, type of Unions,
difference between Union and Structure data types
Need for Structure Data Type:
Structure (struct):
● Definition: A structure in C is a user-defined data type that allows bundling different data types under
one name.
struct Person {
char name[50];
int age;
float salary;
};
Pointer and Structures:
● Pointer and Structures: Pointers can be used to access and manipulate structures by using the arrow
operator -> to access structure members.
struct Person person1;
struct Person *ptrPerson = &person1;
Array of Structures:
● It involves creating an array where each element is a structure.
struct Person people[5]; // Array of structures
people[0].age = 30;
Dynamic Memory Allocation:
● Dynamic Memory Allocation: malloc() and free() functions are used to
allocate and deallocate memory dynamically.
struct Person *ptrPerson = malloc(sizeof(struct Person));
// Use ptrPerson...
free(ptrPerson); // Free dynamically allocated memory
Unions: Unions are similar to structures but share the same memory location for all members. The union keyword is used to
define a union.
union Data {
int i;
float f;
char str[20];
};
Difference between Union and Structure Data Types: The main difference between structures and unions is
how they allocate memory. In a structure, each member has its own memory space, while in a union, all members share the same
memory space.
struct {
int x;
char y;
float z;
}; // Allocates memory for x, y, and z separately
union {
int x;
char y;
float z;
}; // Allocates memory for x, y, and z at the same location
Unit 6. Files
Need for [Link] a file, opening, reading and
closing files, types of file processing: Sequential
access, Random access. Command line arguments
Need for Files:
Files in C: Files are used to store data persistently on secondary storage devices. They allow data to be
stored, retrieved, and manipulated beyond the program's execution.
Creating, Opening, Reading, and Closing Files:
Creating a File: The fopen() function is used to create a new file or open an existing file in a specified
mode. Modes include read, write, append, etc.
FILE *filePointer;
filePointer = fopen("[Link]", "w"); // Opens a file in write mode
Writing to a File: Functions like fprintf() or fputs() are used to write data to a file.
fprintf(filePointer, "This is a sample text.");
Reading from a File: fscanf() or fgets() functions are used to read data
from a file.
char buffer[255];
fgets(buffer, 255, filePointer);
Closing a File: Use the fclose() function to close an opened file after
finishing operations.
fclose(filePointer);
Types of File Processing:
Sequential Access: Data in a file is read or written sequentially, one after another, from the
beginning to the end. Functions like fseek() and ftell() manage the file pointer's position.
FILE *file = fopen("[Link]", "r");
char ch;
while ((ch = fgetc(file)) != EOF) {
// Process character 'ch'
}
fclose(file);
Random Access: Allows direct reading or writing at any position within the file using functions
like fseek() and ftell() to manipulate the file pointer's position.
FILE *file = fopen("[Link]", "r+");
fseek(file, 10, SEEK_SET); // Move to the 10th byte from the beginning of the file
fputc('X', file); // Write 'X' at the current position
fclose(file);
Command-Line Arguments: Arguments passed to a program from the command line when it's
executed. The main() function in C can accept command-line arguments.
int main(int argc, char *argv[]) {
// argc - number of arguments passed
// argv - array of pointers to the arguments
printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Importance:
● File Handling: Essential for reading, writing, and manipulating external data, allowing data persistence
between program runs.
● Sequential vs. Random Access: Understanding the difference helps in choosing the appropriate file
access method based on the application's requirements.
● Command-Line Arguments: Allow passing inputs to programs during execution, enhancing flexibility
and usability.
LIST OF PRACTICALS
● Determine average of two integers
● Find the largest number in an array of 10 numbers
● Determine volume of sphere
● Determine roots of quadratic equation
● Implement a calculator with basic arithmetic functions using switch-case.
● Determine whether given string is palindrome
● Program to add two matrices and display result
● Implement function that multiply two integers
● Implement function that swap integers using pass by reference
● Create a structure Student that contains name, roll number and marks obtained Determine the grade
and generate the mark sheet ]
● Read and display the contents of a file
● Copy the contents of a file to another fill.
1. Determine Average of Two Integers:
#include <stdio.h>
float calculateAverage(int num1, int num2)
{
return (float)(num1 + num2) / 2;
}
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
float avg = calculateAverage(a, b);
printf("Average: %.2f\n", avg);
return 0;
}
2. Find the Largest Number in an Array of 10 Numbers:
#include <stdio.h>
int findLargest(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int numbers[10] = { /* Initialize array with 10 numbers */ };
// Assume array is initialized with 10 values
int largest = findLargest(numbers, 10);
printf("Largest number: %d\n", largest);
return 0;
3. Determine Volume of a Sphere:
#include <stdio.h>
float calculateSphereVolume(float radius)
{
return (4.0 / 3.0) * 3.1416 * radius * radius * radius;
}
int main() {
float r;
printf("Enter radius of sphere: ");
scanf("%f", &r);
float volume = calculateSphereVolume(r);
printf("Volume of the sphere: %.2f\n", volume);
return 0;
}
else if (discriminant == 0)
4. Determine Roots of Quadratic Equation: {
#include <stdio.h> root1 = root2 = -b / (2 * a);
#include <math.h>
printf("Roots are real and equal.\n");
void calculateRoots(float a, float b, float c)
{ printf("Root1 = Root2 = %.2f\n", root1);
float discriminant, root1, root2; }
discriminant = b * b - 4 * a * c; else {
printf("Roots are complex.\n");
if (discriminant > 0) }
{ }
root1 = (-b + sqrt(discriminant)) / (2 * a); int main() {
float a, b, c;
root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Enter coefficients a, b, and c:
");
printf("Roots are real and different.\n"); scanf("%f %f %f", &a, &b, &c);
printf("Root1 = %.2f and Root2 = %.2f\n", calculateRoots(a, b, c);
root1, root2);
return 0;
}
}
5. Implement a Calculator with Basic case '/':
if (num2 != 0) {
Arithmetic Functions Using Switch-Case. result = num1 / num2;
} else {
#include <stdio.h> printf("Error! Division by zero is not
allowed.\n");
int main() { return 1;
char operator; }
float num1, num2, result; break;
default:
printf("Enter an operator (+, -, *, /): "); printf("Invalid operator!\n");
scanf("%c", &operator); return 1;
}
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2); printf("Result: %.2f\n", result);
switch (operator) { return 0;
case '+':
}
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
6. Determine Whether Given String is Palindrome
#include <stdio.h>
#include <string.h>
int isPalindrome(char str[]) {
int left = 0;
int right = strlen(str) - 1;
while (right > left) {
if (str[left++] != str[right--]) {
return 0; // Not a palindrome
}
}
return 1; // Palindrome
}
int main() {
char input[100];
printf("Enter a string: ");
scanf("%s", input);
if (isPalindrome(input)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
7. Program to Add Two Matrices and Display Result:
8. Implement a Function that Multiplies Two Integers.
#include <stdio.h>
int multiply(int num1, int num2) {
return num1 * num2;
}
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
int product = multiply(a, b);
printf("Product: %d\n", product);
return 0;
}
9. Implement a Function that Swaps Integers Using Pass by Reference
#include <stdio.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int num1 = 10, num2 = 20;
printf("Before swap: num1 = %d, num2 = %d\n", num1, num2);
swap(&num1, &num2);
printf("After swap: num1 = %d, num2 = %d\n", num1, num2);
return 0;
10. Create a Structure Student and int main() {
struct Student student;
Determine Grade to Generate Mark Sheet.
printf("Enter student name: ");
#include <stdio.h> scanf("%s", [Link]);
printf("Enter roll number: ");
struct Student { scanf("%d", &[Link]);
char name[50]; printf("Enter marks obtained: ");
int rollNumber; scanf("%f", &[Link]);
float marks;
}; char grade = determineGrade([Link]);
char determineGrade(float marks) { printf("\nMark Sheet\n");
if (marks >= 90) { printf("Name: %s\n", [Link]);
return 'A'; printf("Roll Number: %d\n",
} else if (marks >= 80) { [Link]);
return 'B'; printf("Marks Obtained: %.2f\n",
} else if (marks >= 70) { [Link]);
return 'C'; printf("Grade: %c\n", grade);
} else if (marks >= 60) {
return 'D'; return 0;
} else {
}
return 'F';
}
}
11. Read and Display the Contents of a File
#include <stdio.h>
int main() {
FILE *file;
char ch;
file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!");
return 1;
}
printf("Contents of the file:\n");
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
fclose(file);
return 0;
}
12. Copy the Contents of a File to Another File
#include <stdio.h>
int main() {
FILE *source, *destination;
char ch;
source = fopen("[Link]", "r");
destination = fopen("[Link]", "w");
if (source == NULL || destination == NULL) {
printf("Error opening file!");
return 1;
}
while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination);
}
fclose(source);
fclose(destination);
printf("Contents copied successfully!\n");
return 0;
}