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

Computer Reduced Syllabus Sindh Board Solved

Solved paper of Computer Reduced Syllabus Sindh Board
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Computer Reduced Syllabus Sindh Board Solved

Solved paper of Computer Reduced Syllabus Sindh Board
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Computer Class Notes acc.

to Reduced Syllabus
It includes:
1.​ C language and its history.
2.​ Basic structure of c program
3.​ Variables, identifiers, token and constant
4.​ Data types and its sizes
5.​ Operators and its usages
6.​ Functions
7.​ Array and strings
8.​ pointers

↪ What is C language?
➤ C is a powerful, versatile, and widely used general-purpose computer programming
language. It's known for several key characteristics:

1.​ Procedural: C follows a structured, procedural paradigm where programs are built
from functions or procedures.
2.​ Efficiency: It produces highly efficient code that runs quickly, often close to the speed
of assembly language.
3.​ Low-Level Access: C provides features that allow programmers to manipulate
memory addresses directly (using pointers), interact closely with hardware, and
perform bit-level operations. This makes it suitable for system programming.
4.​ Portability: While providing low-level access, C was designed with portability in mind.
C code written on one system can often be compiled and run on another system with
minimal changes.
5.​ Structured: It encourages breaking down problems into smaller, manageable
functions, leading to more organized code.
6.​ Foundation: C has served as the basis or inspiration for many other popular
programming languages, including C++, C#, Java, Objective-C, Perl, and PHP.

Because of these features, C is often described as a "middle-level" language – bridging the


gap between low-level assembly languages and high-level, more abstract languages.

↪ History of C language.
➤ C was developed by Dennis Ritchie at Bell Labs between 1972 and 1973. It evolved from an
earlier language called B (created by Ken Thompson) primarily to write the Unix operating
system. C provided essential features like data types that B lacked.

The publication of the book "The C Programming Language" (K&R) by Kernighan and Ritchie in
1978 served as its first specification and popularized it. It was later formally standardized by
ANSI (C89) and ISO (C90), with subsequent updates like C99, C11, and C18. C remains highly
influential and widely used, especially in system programming and embedded systems.

↪ Basic Structure of C Language.

➤ Pre-Processor Directive Section

This section is processed before the actual compilation of your code begins. It instructs
the preprocessor (part of the compiler) to perform certain actions, like including other files or
defining constants.

Common Directives:

#include: This is the most common directive. #include <stdio.h> (usually a "header file"
ending in .h) into your current file. Header files typically contain declarations for predefined
functions (like printf from stdio.h) or types.

These appear at the very beginning of each C code.

➤ Global Declaration Section

This section is where you declare elements that need to be accessible throughout the
entire program (or at least across multiple functions within the same file). This is done outside
of any function block.

➤ The main Function


This is the heart of every executable C program. It's a special function where the
program's execution always begins when it is run. Every C program must have exactly one
main function.

It typically has a return type of int (integer). It must be named main. For simple programs,
int main(void) or just int main() is common.

➤ Braces

The primary purpose of curly braces {} is to group multiple programming statements


together into a single block or compound statement. The compiler treats everything between
an opening brace { and its corresponding closing brace } as one logical unit.

int main(void)
{
//Start of main function block
//Statements go here...
printf("Hello!");
return 0; }

➤ Source Code

★​ Source code is the set of human-readable instructions written by a programmer using


a specific programming language (like C, Java, Python, C++, etc.).

Think of it as the blueprint or recipe for a computer program.

It is Human Readable so humans who know the syntax and grammar of the language can
easily read and edit the source code of any program. A machine can not understand source
code; it understands binary code. It needs to be translated into machine language by a
compiler or an interpreter to be understood by a machine. Compiler commonly used for c
language and interpreter commonly used for Python.

↪ Explain Each Variables, Identifiers, Token and Constant


➤ Variables

A variable is a labeled container or named storage location in the computer's memory where
you can put data. The key aspects of a variable are its identifiers, Type, Value and Memory
Location.

An identifier is a unique name you give to a variable so you refer to it later. (eg. age, name,
height, weight).

When you store data in memory it gives you a location that can handle the data type in the
memory to refer to later. And each memory location has a unique address, think of it like a
locker box number. When you use the variable name (identifier) the computer uses the
associated address to retrieve the stored value

The type is what kind of data the variable can store.

Types:

★​ Int (for integers like -5, 0, 100)


★​ Float (for decimals points like 0.5, 3.14)
★​ char( for single characters 7,e,%)

#include <stdio.h>

int main() {
// --- Variable Declaration ---
// Reserves memory for an integer and names it 'score'.
int score;

// Reserves memory for a character and names it 'grade'.


char grade;

// Reserves memory for a floating-point number and names it 'temperature'.


float temperature;

// --- Variable Assignment (Storing Values) ---


score = 85; // Store the value 85 in the 'score' variable.
grade = 'B'; // Store the character 'B' in the 'grade' variable.
temperature = 28.5; // Store the value 28.5 in 'temperature'.

// --- Using Variables ---


printf("Current score: %d\n", score); // Output: Current score: 85
printf("Current grade: %c\n", grade); // Output: Current grade: B

// --- Changing a Variable's Value ---


score = score + 5; // Read 'score' (85), add 5, store the result (90) back into 'score'.
printf("New score: %d\n", score); // Output: New score: 90
return 0;
}

➤ identifiers

An identifier is a name given to various entities in a program.

Just how you give a name to a variable, it is its identifier. However identifiers are used to
name more things than just variables.

For example: Variables, Functions, Macros, Labels etc.

What are functions?

Functions are self-contained blocks of codes that perform a specific task. They are building blocks of structuring
and organizing c programs. Purpose of functions? They allow you to break down large code into sections and more
manageable units. Each function can focus on a specific part of the overall program. Functions are reusable and
can be called from all over the code. This saves time from rewriting the code again and again. Use a clear named
function for better usability and organization and for better debugging experience.

#include <stdio.h>

// Function to add two integers and return the sum


int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
int num1 = 5;
int num2 = 3;
int result;
// Calling the 'add' function
result = add(num1, num2);
printf("The sum of %d and %d is: %d\n", num1, num2, result);
return 0;
}

What are Macros?

In the C programming language, macros are code snippets that are preprocessed before the actual compilation of
your program. They are defined using the #define preprocessor directive. When the preprocessor encounters a
macro, it replaces every occurrence of the macro name in your code with its defined value or code snippet.

They are preprocessor directive so they are handled by the C language itself not the compiler. No type checking is
applied on macros so sometimes they can lead to unexpected errors in the program. Macros are quite faster but
also take up alot of space if used frequently in the program. There are Two Types of Macros, Object-Like Macros and
Function like Macros. Object Like macros are used to define symbolic names for constant values like #define PI =
3.14 and #define MAX_SIZE = 100 etc, in this code every instance of PI will be replaced with 3.14 and every instance of
MAX_SIZE will be replaced by 100 before the code compiles. Function Like Macros resemble function calls but are
expanded inline by the preprocessor. They can take arguments. Like #define SQUARE(x) ((x) * (x)) and #define
MAX(a, b) (((a) > (b)) ? (a) : (b)) When these macros are used, the preprocessor substitutes the macro call with the
defined code, replacing the arguments accordingly. The parentheses around the arguments and the entire
expression are crucial to avoid unintended operator precedence issues.

int num = 5;
int squared = SQUARE(num); // After preprocessing: int squared = ((num) * (num));
int a = 10, b = 20;
int maximum = MAX(a, b); // After preprocessing: int maximum = (((a) > (b)) ? (a) : (b));
int result = SQUARE(num + 2); // After preprocessing: int result = ((num + 2) * (num + 2));

Here are some rules to identifiers that must be noted before giving a name to any entity. Like
you can only use A-Z, a-z, numbers and underscore. Identifiers can not start with numbers
and they are case sensitive (eg. myvariable and Myvariable are different). Identifiers can not
be reserved keywords like int, return, if and while.

➤ Tokens

When your source code is compiled by the compiler, a part called lexer or scanner breaks the
stream of characters into a sequence of tokens. A token is the smallest individual unit of a
program's source code meaningful to the compiler.

Consider a line of code:

Int cash = 0;

The lexer would break this down to these tokens:

1.​ Int (keyword)


2.​ Cash (identifier)
3.​ = (operator)
4.​ 0 (constant/literal)
5.​ ; (punctuator)
➤ constant

A constant is a value that does not change during the execution of a program. Quite
opposite of variables whose value can be changed during the execution of a program.

Constants can appear in two forms: literals and symbolic constants.

↪ Explain Data types and their Sizes

➤ Data types

In computer science, a data type is a classification that specifies which type of value a
variable can hold. It defines the kind of data that can be stored and manipulated. Different
programming languages have their own sets of built-in data types, and they also allow users
to define their own custom data types.

Sizes of Data types:

The size of a data type refers to the amount of memory allocated to store a variable of that
type.

Think of your memory like a street with houses. Each house has an address and can hold information. Different types
of info need different-sized houses. int houses are for whole numbers, like 1, 2, 100. char houses are small, just for one
letter or symbol. float houses have extra space for numbers with decimals.

5 common data types in the C programming language along with their typical sizes on a
32-bit and 64-bit system. The sizes can vary slightly depending on the compiler and the
specific architecture.

Int (integer)

●​ 32-bit systems: Typically 4 bytes (32 bits)


●​ 64-bit systems: Typically 4 bytes (32 bits)

Char (character)
●​ Both 32-bit and 64-bit systems: Typically 1 byte (8 bits). This is enough to store a
single character from the ASCII character set.

Float (floating point number)

●​ Both 32-bit and 64-bit systems: Typically 4 bytes (32 bits). This provides
single-precision floating-point values.

Double (double precision floating point number)

●​ Both 32-bit and 64-bit systems: Typically 8 bytes (64 bits). This provides higher
precision than float.

Void (void pointer)

●​ 32-bit systems: Typically 4 bytes (32 bits) - A pointer needs to hold a memory
address, and on a 32-bit system, addresses are typically 32 bits.
●​ 64-bit systems: Typically 8 bytes (64 bits) - On a 64-bit system, memory addresses
are typically 64 bits. A void * can point to any data type.

Data Types 32 bit system 64 bit system

int 4 bytes 4 bytes (sometimes 8)

char 1 byte 1 byte

float 4 bytes 4 bytes

double 8 bytes 8 bytes

void 4 bytes 8 bytes

Tips:

The sizeof() operator in C can be used at runtime to determine the exact size of a data type on your specific
system and compiler. The C standard does not strictly define the exact number of bytes for int, long, etc., only the
minimum ranges they must be able to represent.
↪ Operators and its usages

➤ Operators

Operators are special symbols that perform operations on one or more values (operands).

These operations can include arithmetic calculations, logical comparisons, logical evaluation, and
much more.

USAGES:

Some key usages of operators are:

1.​ Arithmetic operators (+, -, *, /, %) are used to perform mathematical operations on


numerical data.

int sum = 10 + 5; // Addition


float difference = 20.5 - 7.2; // Subtraction
int product = 6 * 3; // Multiplication
float quotient = 15.0 / 4.0; // Division
int remainder = 17 % 5; // Modulo (remainder)

2.​ Assignment Operators (=, +=, -=, *=, /=, %=) are used to store or modify the values of
variables.

int age = 25; // Simple assignment


int counter = 0; counter++; // Increment (shorthand for counter = counter + 1)
int total = 100;
total -= 20; // Subtract and assign (total = total - 20)

3.​ Comparison (Relational) operators (==, !=, >, <, >=, <=) are used to compare two
values and determine their relationship, resulting in a boolean (true or false)
outcome. These are crucial for decision-making in programs.
int score = 85;
if (score >= 60) {
printf("Pass\n");
} else {
printf("Fail\n");
}

if (age == 18) {
printf("Eligible to vote\n");
}

4.​ Logical operators (&& - AND, || - OR, ! - NOT) combine or negate boolean expressions,
allowing for more complex conditions.

int temperature = 25;


bool isRaining = false;

if (temperature > 20 && !isRaining) {


printf("It's a pleasant day.\n");
}

if (temperature < 0 || temperature > 35) {


printf("Extreme temperature.\n");
}

5.​ The sizeof() operator is used to find the size (in bytes) of a data type or a variable. This
is useful for memory management and understanding data structures.

printf("Size of int: %zu bytes\n", sizeof(int));


int numbers[10];
printf("Size of numbers array: %zu bytes\n", sizeof(numbers));

↪ Control Structures

➤ Selection/decision making structure


Control structures are fundamental constructs in programming that allow you to control the
flow of execution of your code based on certain conditions. They enable your program to
make decisions and execute different blocks of code accordingly. Here's an explanation of if,
if-else, else if, and switch case control structures with their syntax in a C language.

1. if Statement:

The if statement executes a block of code only if a specified condition is true.

Syntax:

#include <stdio.h>

int main() {
int age = 20;

if (age >= 18) {


printf("You are eligible to vote.\n");
}

printf("End of program.\n");

return 0;
}

Explanation: an integer variable age is declared and initialized to 20. An if statement then checks if age is greater than or equal
to 18. If this condition is true (which it is in this case), the code block within the curly braces is executed, printing "You are eligible to
vote." to the console. Finally, the program prints "End of program." regardless of the if condition's outcome, and return 0; indicates
successful execution. In essence, the code checks if a person's age (set to 20) qualifies them to vote and prints a corresponding
message.

2. if-else Statement:

The if-else statement executes one block of code if a condition is true and another block of
code if the condition is false.

Syntax:

The syntax of if-else statement is as follows:

#include <stdio.h>

int main() {
int number = 15;

if (number % 2 == 0) {
printf("%d is an even number.\n", number);
} else {
printf("%d is an odd number.\n", number);
}

printf("End of check.\n");

return 0;
}

Explanation:

This code snippet demonstrates an if-else statement used to determine if a number is even or odd. The if condition checks if the
number is divisible by 2 with no remainder (i.e., if it's even). If the condition is true, a message indicating the number is even is printed.
Otherwise (if the condition is false, meaning the number is odd), the code within the else block is executed, printing a message
indicating the number is odd. Regardless of whether the number is even or odd, the line printf("End of check.\n"); is executed
after the if-else structure completes.

3. else if Statement:

The else if statement allows you to check multiple conditions in sequence. If the initial if
condition is false, the else if condition is evaluated. If it's true, its associated code block is
executed. You can have multiple else if statements.

Syntax:

if (condition1) {
// Code to be executed if condition 1 is true
} else if (condition2) {
// Code to be executed if condition1 is false AND condition 2 is true
} else if (condition3) {
// Code to be executed if condition1 and condition2 are false AND condition 3 is true
} else {
// Code to be executed if all preceding conditions are false (optional else block)
}
// Code here will always be executed after the if-else if chain

Explanation:

●​ The conditions are evaluated in order from top to bottom.


●​ Once a condition evaluates to true, its corresponding code block is executed, and the rest of the else if
and the final else block are skipped.
●​ The final else block is optional and is executed if none of the preceding if or else if conditions are true.

4. switch case Statement:

The switch case statement provides a more efficient way to execute different blocks of code
based on the value of a single variable (or expression) compared against multiple constant
values (cases).
Syntax:

#include <stdio.h>

int main() {
char day = 'W';

switch (day) {
case 'M':
printf("Monday\n");
break;
case 'T':
printf("Tuesday\n");
Explanation:
break;
case 'W':
Describes a switch statement where the value of the day variable is
printf("Wednesday\n");
break; compared to different case constants ('M', 'T', 'W', 'Th', 'F', 'S', 'U'). When a
case 'H': match is found, the corresponding code is executed. The break statement
printf("Thursday\n");
is essential for exiting the switch block after a match. Multiple case labels
break;
case 'F': can share the same code. An optional default case handles values that
printf("Friday\n"); don't match any other case. Finally, a line of code after the switch
break;
statement is always executed.
case 'S':
case 'U':
printf("Weekend\n");
break;
default:
printf("Invalid day\n");
}

printf("Day checked.\n");

return 0;}

➤ Iterative Structure for, while, and do while with syntax

Iterative structures, also known as loops, are control flow statements in programming that
allow a block of code to be executed repeatedly for a specific number of times or until a
certain condition is met. They are fundamental for automating repetitive tasks and
processing collections of data.

The main purpose of iterative structures is to avoid writing the same code multiple times.
Instead, you define a block of code once and specify the conditions under which it should be
executed repeatedly.

For Loop:
The for loop is typically used when you know in advance how many times you want to
iterate. It usually involves three parts:

●​ Initialization, condition, increment or decrement (update)

Syntax:

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


// Code to be executed in each iteration
printf("Iteration number: %d\n", i);
}

While Loop:

The while loop is a control flow statement that repeatedly executes a block of code as long as
a specified condition remains true. The condition is checked before each iteration 2 of the
loop.

A while loop repeatedly executes a block of


Syntax: code as long as a specified condition (a boolean
expression) remains true. The condition is
checked before each iteration, including the very
while (condition) { first one. If the condition is initially false, the loop
// Code to be executed as long as the condition is true body is skipped entirely, meaning the loop can
} execute zero or more times. To avoid an infinite
loop, it's essential to have a control variable that
// Code here will be executed after the loop terminates
is initialized before the loop and modified within
the loop body in a way that will eventually make
the condition false, thus terminating the loop.
Syntax in C language:

#include <stdio.h>

int main() {
int count = 0;

while (count < 5) {


printf("Count is: %d\n", count);
count++; // Incrementing the control variable to eventually make the condition false
}

printf("Loop finished.\n");

return 0;}

Do-While Loop:

The do-while loop is another control flow statement that repeatedly executes a block of
code. However, unlike the while loop, the do-while loop checks the condition after the loop
body is executed. This guarantees that the loop body will execute at least once.
Syntax:

do {
// Code to be executed at least once, and then repeatedly
// as long as the condition is true
} while (condition);
// Code here will be executed after the loop terminates

↪ Functions

Functions are self-contained blocks of codes that perform a specific task. They are building
blocks of structuring and organizing c programs. Purpose of functions? They allow you to
break down large code into sections and more manageable units. Each function can focus
on a specific part of the overall program. Functions are reusable and can be called from all
over the code. This saves time from rewriting the code again and again. Use a clear named
function for better usability and organization and for better debugging experience.

➤ System Defined Functions

These are functions created by the programming language itself; you just need to use them.
These functions perform common and essential tasks, saving you a lot of time. Typically
organized into libraries or modules and you need to include these to use them.

You can use these functions once you have included the necessary header file or imported
the module. Predefined functions handle various common programming tasks like
input/output, string manipulation, math, and memory management. Users don't need to
know their internal workings, only their purpose, arguments, and return values.

In C, functions like:

●​ printf() — prints output​

●​ scanf() — takes input​

●​ sqrt() — finds square root


Syntax:

#include <stdio.h>
#include <math.h>

int main() {
int x = 16;
double result = sqrt(x); // sqrt is a predefined function
printf("Square root of %d is %.2f", x, result);
return 0;
}

➤ User Defined Functions

User-defined functions are blocks of code that are created and named by the programmer
to perform specific tasks within their program. Unlike predefined (or system-defined)
functions that are built into the programming language or its libraries, user-defined functions
are tailored to the unique requirements and logic of a particular program.

Syntax:

return_type function_name(parameters) {
// code
}

Example:

#include <stdio.h>

void greet() {
printf("Hello, Fareed!\n");
}

int main() {
greet();
return 0;
}

●​ When we talk about methods of user-defined functions, especially in C programming,


there are four types (methods) based on function arguments and return values.
Method No. Function Type Meaning

1️⃣ Function with no arguments and no Function takes nothing, returns


return value nothing

2️⃣ Function with arguments but no Function takes input, but doesn't
return value return anything

3️⃣ Function with no arguments but with Function takes no input, but returns
return value something

4️⃣ Function with arguments and with Function takes input and returns a
return value value

Explaining each with example in C:

1️⃣ No arguments, no return value

#include <stdio.h>

void greet() {
printf("Hello, Fareed!\n");
}

int main() {
greet(); // function call
return 0;
}

●​ No input. No return value.


●​ Just perform a task.
2️⃣ With arguments, no return value

#include <stdio.h>

void greet(char name[]) {


printf("Hello, %s!\n", name);
}

int main() {
greet("Fareed"); // passing argument
return 0;
}

●​ Takes input. No return value


●​ Receives data, performs action.

3️⃣ No arguments, with return value

#include <stdio.h>

int getNumber() {
int num = 10;
return num;
}

int main() {
int result = getNumber();
printf("Number is: %d\n", result);
return 0;
}

●​ No input. Returns value.


●​ Useful when internal logic gives you a result.

4️⃣ With arguments, with return value

#include <stdio.h>

int add(int a, int b) {


return a + b;
}

int main() {
int sum = add(5, 7); // passing arguments
printf("Sum is: %d\n", sum);
return 0;
}
●​ Takes input and returns result

↪ Array and Strings

➤ Array

An array is a data structure that stores a fixed-size sequential collection of elements of the
same data type. In simpler terms, it's a way to group together multiple variables of the same
type under a single name, where each element can be accessed using an index (a numerical
position).

It helps to store multiple values in a single variable, instead of declaring separate variables
for each value.

Instead of:

●​ int a = 1;
●​ int b = 2;
●​ int c = 3;

We use:

●​ int arr[3] = {1, 2, 3};

Characteristics of Arrays:

1.​ All elements in an array must be of the same data type.


2.​ Once an array is declared with a fixed size it cannot be changed during the execution
of the program.
3.​ The elements of an array are stored in contiguous (adjacent) memory locations. This
allows for efficient access to any element using its index.
4.​ Each element in an array is accessed using an index, which is usually an integer
starting from 0 for the first element, 1 for the second, and so on.

Array Declaration:
data_type array_name[size];

Example:

int numbers[5]; // declares an array of 5 integers

Array Initialization:

There are two ways of initializing array

1.​ At Declaration

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

2.​ After Declaration

int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

2D Arrays (two dimensional arrays)

A 2D array is an array of arrays. It can be visualized as a table with rows and columns.

Declaration of a 2d array is something like this:

data_type array_name[rows][columns];

Example of Array in C:

int matrix[2][3]; // 2 rows, 3 columns

Initialization:

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

How to Access Elements in this array?

printf("%d", matrix[1][2]); // Output: 6

This is how anybody can access the 2d arrays

➤ Strings

A string is a collection of characters terminated by a null character in C.

●​ string is an array of characters!

You can declare a string like:

Char name[6] = {‘F', 'a', 'r', 'e', 'e', 'd'};

Easier Way is:

Char name[] = ‘’fareed’’;

The compiler adds the /0 at the end automatically.

➤ Strings Functions

C string functions in string.h are ready-made tools for common text tasks. They let you find
the length, copy, combine, compare, and search within strings (which are just character
arrays ending with a special '\0'). They make working with text in C much easier.

1.​ GETS()

The C function gets() reads a line of text from the keyboard and stores it in a string
(character array), replacing the Enter key press with a null terminator. However, it's extremely
dangerous because it doesn't limit the input size, leading to potential buffer overflows and
security risks. Therefore, gets() should never be used. Safer alternatives like fgets() should
be used instead to prevent these vulnerabilities by specifying a maximum input length.

Syntax:

gets(string);

2.​ GETC()

Reads a single character from input and returns it as an integer.

Syntax:

char ch;
ch = getc(stdin); // stdin means standard input (keyboard)

3.​ PUTS()

Used to print a string to the output with a newline at the end.

Syntax:

puts(string);
—----------------
char name[] = "Fareed";
puts(name); // Output: Fareed

4.​ PUTC()

Prints a single character to output.

Syntax:

putc(character, stdout);
—----------------------
char c = 'F';
putc(c, stdout);

5.​ STRLEN()
Returns the length of the string (number of characters excluding null character)

Syntax:

int length = strlen(string);


—----------------------
char name[] = "Fareed";
int len = strlen(name); // len = 6

6.​ STRCPY()

Copies one string to another.

Syntax:

strcpy(destination, source);
—------------------------
char src[] = "Fareed";
char dest[20];
strcpy(dest, src); // dest now contains "Fareed"

7.​ STRCMP()

Compare two strings.

Returns:

●​ 0 if both strings are equal


●​ <0 if first string is less
●​ >0 if first string is greater

Syntax:

int result = strcmp(string1, string2);


—------------------------------
strcmp("abc", "abc"); // returns 0
strcmp("abc", "abd"); // returns negative
strcmp("abd", "abc"); // returns positive

8.​ STRCAT()
Joins two Strings.

Syntax:

strcat(destination, source);
—------------------------
char str1[20] = "Hello ";
char str2[] = "Fareed";
strcat(str1, str2); // str1 becomes "Hello Fareed"
↪ Pointers

A pointer is a variable that stores the memory address of another variable.

Instead of storing a value directly, like an integer or character, a pointer stores the location
(address) of that value in memory.

You can think of it like this:

●​ Normal variable: What is the value?


●​ Pointer: Where is the value stored?

Why do we use pointers?

●​ To directly access and modify memory.


●​ To pass large structures or arrays to functions efficiently.
●​ For dynamic memory allocation.
●​ To work with data structures like linked lists, trees, etc.

Declaration of Pointer

When you declare a pointer, you tell the compiler:

"Hey, I want a variable that can store an address of a specific data type."

Syntax:

data_type *pointer_name;

Example:

int *ptr; // Pointer to an integer


char *cptr; // Pointer to a character
float *fptr; // Pointer to a float
2. Initialization of Pointer

Once declared, you should initialize it by assigning the address of a variable.

Syntax:

pointer_name = &variable;

Example:

int x = 5;
int *ptr = &x; // ptr stores the address of x

3. Using the Pointer (Access value)

To access the value stored at the address, use * (called dereferencing).

Example:

printf("Value of x: %d\n", *ptr); // Output: 5

AN EXAMPLE OF USING POINTERS:

#include <stdio.h>

int main() {
int num = 10; // Variable
int *ptr; // Pointer declaration
ptr = &num; // Pointer initialization

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


Value of num: 10
printf("Address of num: %p\n", &num);
Address of num:
printf("Pointer storing address: %p\n", ptr);
0x7ffeebc7a4dc
printf("Value at address stored by pointer: %d\n", *ptr); Pointer storing address:
0x7ffeebc7a4dc
return 0; Value at address stored by
} pointer: 10

You might also like