0% found this document useful (0 votes)
23 views16 pages

C Programming Concepts and Functions

Uploaded by

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

C Programming Concepts and Functions

Uploaded by

skunus1998ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2018-19

2. Describe the function of various unit of a digital computer using a


neat block diagram
Organizer Page 11-12

Logical operators in C are used to combine multiple conditions/constraints. Logical


Operators returns either 0 or 1, it depends on whether the expression result is true
or false. In C programming for decision-making, we use logical operators.
We have 3 logical operators in the C language:
 Logical AND ( && )
 Logical OR ( || )
 Logical NOT ( ! )
a) Two's complement offers several advantages over one's
complement in representing signed integers. Primarily, two's
complement has only one representation for zero
A void pointer is a pointer that has no associated data type with it. A void
pointer can hold an address of any type and can be typecasted to any
type.
#include <stdio.h>
int main()
{
int a = 10;
char b = 'x';
void* p = &a;
p = &b;
}

In call by value method of parameter passing, the values of actual


parameters are copied to the function’s formal parameters.
 There are two copies of parameters stored in different memory
locations.
 One is the original copy and the other is the function copy.
 Any changes made inside functions are not reflected in the actual
parameters of the caller.
#include <stdio.h>
void swapx(int x, int y) {
int t;
t = x;
x = y;
y = t;
printf("Inside swapx: x = %d y = %d\n", x, y);
}
int main() {
int a = 10, b = 20;
swapx(a, b);
printf("Inside main: a = %d b = %d", a, b);
return 0;
}

In call by reference method of parameter passing, the address of the


actual parameters is passed to the function as the formal parameters. In
C, we use pointers to achieve call-by-reference.
 Both the actual and formal parameters refer to the same locations.
 Any changes made inside the function are actually reflected in the
actual parameters of the caller.

#include <stdio.h>
void swapx(int* x, int* y) {
int t;
t = *x;
*x = *y;
*y = t;
printf("Inside swapx: x = %d y = %d\n", *x, *y);
}
int main() {
int a = 10, b = 20;
swapx(&a, &b);
printf("Inside main: a = %d b = %d", a, b);
return 0;
}
#include <stdio.h>
#include <limits.h>

int main() {
int n, matrix[10][10], max_element = INT_MIN;
printf("Enter the size of the square matrix (n, max 10): ");
scanf("%d", &n);
if (n <= 0 || n > 10) {
printf("Invalid matrix size. Please enter a value between 1
and 10.\n");
return 1;
}

printf("Enter matrix elements row by row:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Enter element at position (%d,%d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] > max_element) {
max_element = matrix[i][j];
}
}
}

printf("The maximum element in the matrix is: %d\n",


max_element);
return 0;
}
In C, bitwise operators are used to perform operations directly on the
binary representations of numbers. These operators work by manipulating
individual bits (0s and 1s) in a number.
The following 6 operators are bitwise operators (also known as bit
operators as they work at the bit-level). They are used to perform bitwise
operations in C.
1. The & (bitwise AND) in C takes two numbers as operands and does
AND on every bit of two numbers. The result of AND is 1 only if both
bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR
on every bit of two numbers. The result of OR is 1 if any of the two bits
is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does
XOR on every bit of two numbers. The result of XOR is 1 if the two bits
are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the
first operand, and the second operand decides the number of places to
shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the
first operand, and the second operand decides the number of places to
shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
Bitwise operators allow precise manipulation of bits, giving you control
over hardware operations.
A function is like a specialized mini-program or a reusable "recipe" within your main
program. You give it a specific job to do, and it performs that task whenever you call upon it.

Advantages of using functions:

 Organization: It helps you break down big, complex problems into smaller, manageable
parts.
 Reusability: Write a piece of code once, and use it many times throughout your program (or
even in other programs!), saving effort.
 Readability: Makes your main code cleaner and easier to understand, as you can see what
tasks are being performed by just looking at the function names.
 Easier Debugging: If something goes wrong, you only need to check the specific function
responsible for that task, not the entire program.

The purpose of a return statement is to send a result or value back from the function to the
part of the code that called it. Think of it as the function handing over the "answer" or
"output" of its specific job. It also signals that the function has finished its execution.

#include <stdio.h>
double calculateSquare(double num) {
return num * num;
}

int main() {
double x, y, z;
printf("Enter x, y, z: ");
scanf("%lf %lf %lf", &x, &y, &z);
double sumOfSquares = calculateSquare(x) + calculateSquare(y) +
calculateSquare(z);
printf("x^2 + y^2 + z^2 = %.2lf\n", sumOfSquares);
return 0;

 auto (Automatic):
o Scope: Local to the block/function.
o Lifetime: Created when block entered, destroyed when block exited.
o Default: Variables inside functions are auto by default.
o Use: Temporary variables, loop counters.

 extern (External/Global):
o Scope: Global across multiple files.
o Lifetime: Throughout program execution.
o Use: Declare a global variable defined in another file, making it accessible.

 static (Static):
o Scope & Lifetime depend on where it's declared:
 Inside a function:
 Scope: Local to the function.
 Lifetime: Throughout program execution (retains value between calls).
 Use: Counters, persistent state within a function.
 Outside a function (global/file scope):
 Scope: Local to the file it's declared in.
 Lifetime: Throughout program execution.
 Use: Hide a global variable from other source files.
In C, a pointer array is a homogeneous collection of indexed pointer
variables that are references to a memory location. It is generally used in
C Programming when we want to point at multiple memory locations of a
similar data type in our C program. We can access the data by
dereferencing the pointer pointing to it.
Syntax:
pointer_type *array_name [array_size];
Here,
 pointer_type: Type of data the pointer is pointing to.
 array_name: Name of the array of pointers.
 array_size: Size of the array of pointers.
#include <stdio.h>
int main()
{
int var1 = 10, var2 = 20, var3 = 30;
int* ptr_arr[3] = { &var1, &var2, &var3 };
for (int i = 0; i < 3; i++) {
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i],
ptr_arr[i]);
}

return 0;

Here are compact short notes on each of the requested topics:


a) Dynamic Allocation of Memory

Dynamic memory allocation is the process of assigning memory space at program runtime
rather than at compile time. This is crucial when the exact memory requirement is unknown
beforehand (e.g., processing user input of variable size). In C, functions like malloc()
(allocates a block of memory), calloc() (allocates and initializes to zero), realloc()
(resizes an existing block), and free() (releases allocated memory) from <stdlib.h> are
used. It allows efficient memory utilization by allocating only what's needed and deallocating
it when no longer required, preventing memory wastage.

b) Bitwise Operators

Bitwise operators perform operations directly on the individual bits of integer data types.
They are used for low-level programming, data manipulation, and efficient computations.
Common bitwise operators include:

 & (AND): Sets bit if both corresponding bits are 1.


 | (OR): Sets bit if at least one corresponding bit is 1.
 ^ (XOR): Sets bit if corresponding bits are different.
 ~ (NOT / One's Complement): Inverts all bits.
 << (Left Shift): Shifts bits to the left, filling with zeros (effectively multiplies by powers of
2).
 >> (Right Shift): Shifts bits to the right (effectively divides by powers of 2). These are vital
for tasks like setting/clearing specific bits in a register, optimizing certain arithmetic
operations, or compressing data.

c) Pointer Arithmetic

Pointer arithmetic involves performing arithmetic operations (addition and subtraction) on


pointers. When an integer is added to or subtracted from a pointer, the pointer moves by a
multiple of the size of the data type it points to. For example, if an int pointer is
incremented, it moves by 4 bytes (assuming sizeof(int) is 4).

 pointer + integer: Moves the pointer forward by integer * sizeof(data_type)


bytes.
 pointer - integer: Moves the pointer backward by integer * sizeof(data_type)
bytes.
 pointer - pointer: Valid only for pointers of the same type, returning the number of
elements between them (not bytes). Pointer arithmetic is primarily used for traversing arrays
and accessing elements in contiguous memory blocks efficiently.

d) Functions of Memory Unit of a Digital Computer


The memory unit (typically RAM - Random Access Memory) is a fundamental component of
a digital computer responsible for storing data and program instructions that the CPU needs
to access quickly. Its primary functions include:

1. Storage: Temporarily holding data and instructions that are currently being processed by the
CPU.
2. Retrieval (Read Operation): Providing fast access to stored information when requested by
the CPU.
3. Writing (Write Operation): Storing new data or updated information into specific memory
locations.
4. Addressing: Organizing stored data using unique memory addresses, allowing the CPU to
locate and access specific data efficiently.
5. Buffering: Acting as a high-speed buffer between the CPU and slower peripheral devices.

e) Array of Structure

An array of structures is a collection of variables of the same structure type, arranged in a


contiguous block of memory. A structure is a user-defined data type that groups related
data items of possibly different data types under a single name (e.g., student record with
name, roll number, marks).

 Declaration: struct Student students[50]; (declares an array students capable of


holding 50 Student structures).
 Use: It is used to store multiple records or objects of the same kind, making it easy to manage
collections of complex data. For example, an array of Student structures can store details of
many students.
 Access: Individual structures are accessed using array indexing (students[0],
students[1]), and their members are accessed using the dot operator (students[0].name,
students[1].roll_no).

f) Pointer to Function and Function Returning a Pointer

 Pointer to Function:
o A pointer to function is a variable that stores the memory address of an executable function.
It allows functions to be passed as arguments to other functions, stored in data structures, or
returned from functions.
o Syntax: return_type (*pointer_name)(parameter_types);
o Use: Implementing callback mechanisms, creating jump tables for state machines, or
designing generic algorithms.
 Function Returning a Pointer:
o A function returning a pointer is a function whose return type is a pointer. It means the
function computes an address and sends it back to the caller. This address often points to
dynamically allocated memory or a variable declared static within the function.
o Syntax: return_type *function_name(parameters);
o Use: Commonly used in memory management (e.g., malloc returns a pointer), creating
linked list nodes, or when a function needs to return a complex data structure that is too large
to pass by value.

You might also like