Computational Skills Theory Notes All Units
Computational Skills Theory Notes All Units
NOTE - TAP ON ABOVE IMAGES COPY GROUP LINK & JOIN TELEGRAM GROUPS FOR ENGINEERING (BEE)
GUYS THIS IS OUR FIRST SERIES OF PROVIDING YOU NOTES FOR YOUR UNIVERSITY EXAMINATION
POINT OF VIEW.
What is C?
C is a general-purpose programming language created by Dennis Ritchie at the Bell
Laboratories in 1972.
It is a very popular language, despite being old.
C is strongly associated with UNIX, as it was developed to write the UNIX
operating system.
Why Learn C?
It is one of the most popular programming language in the world If
you know C, you will have no problem to learn other popular
programming languages such as Java, Python, C++, C#, etc, as the syntax
is similar
C is very fast, compared to other programming languages, like Java
and Python
C is very versatile; it can be used in both applications and
technologies
There are many text editors and compilers to choose from. In this tutorial, we
will use an IDE (see below).
C Install IDE
An IDE (Integrated Development Environment) is used to edit AND compile the
code.
Popular IDE's include Code: : Blocks, Eclipse, and Visual Studio. These are all
free, and they can be used to both edit and debug C code.
Note: Web-based IDE's can work as well, but functionality is limited.
We will use Code::BIocks in our tutorial, which we believe is a good place to
start.
You can find the latest version of Codeblocks at http://www.codeblocks.org/.
Download the mingw-setup.exe file, which will install the text editor with a
compiler.
C Quickstart
Let's create our first C file.
Open Codeblocks and go to File > New > Empty File.
Write the following C code and save the file as myfirstprogram. c (File > Save File as):
myfirstprogram. c
#include < stdio.h>
Syntax
You have already seen the following code a couple of times in the first chapters. Let's
break it down to understand it better:
Example
#include < stdio.h>
YitYoü/öelf•j
Example explained
Line 1: #include is a header file library that lets us work with input and
output functions, such as printf() (used in line 4). Header files add functionality
to C programs.
Don't worry if you donjt understand how ('include €stdio.h> works. Just think of
it as something that (almost) always appears in your program.
Line 2: A blank line. C ignores white space. But we use it to make the code more
readable.
Line 3: Another thing that always appear in a C program, is main(). This is called a
function. Any code inside its curly brackets { ) will be executed.
Line 4: printf() is a function used to output/print text to the screen. In our example
it will output "Hello World"
Note that: Every C statement ends with a semicolon
Note: The body of int main() could also been written as:
int World! 0; )
Remember: The compiler ignores white spaces. However, multiple lines makes the
code more readable.
Example
#include < stdio.h>
itYOürSélv»
You can add as many printf() functions as you want. However, note that it does not
insert a new line at the end of the output:
Example
ttinclude < stdio.
Example
#include < stdio.h>
You can also output multiple lines with a single printf() function. However, be
aware that this will make the code harder to read:
Example
#include < stdio.h>
Tip: Two characters after each other will create a blank line:
Example
#include < stdio.h>
int main() {
What is \n exactly?
The newline character (\n) is called an escape sequence, and it forces the
cursor to change its position to the beginning of the next line on the screen.
This results in a new line.
Examples of other valid escape sequences are:
Comments in C
Comments can be used to explain code, and to make it more readable. It can
also be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between and the end of the line is ignored by the compiler (will not
be executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
print f ("Hello World!
i
') •
it Yoüfself»
This example uses a single-line comment at the end of a line of code:
Example
printf( "Hello World! • // This is a comment klEYourse1f?J
C Multi-line Comments
Multi-line comments start with / * and ends with * /.
Example
/ * The code below will print the words Hello World! to the
screen, and it is amazing * /
World!
C Variables
PreviousNexea
Variables are containers [or storing data values.
In C, there are different types or variables (defined with different keywords),
for example:
int - stores integers (whole numbers), without decimals, such as 123 or
123 float - stores floating point numbers, with decimals, such as 19.99
or -
19.99 char - stores single characters, such as 'a' or Char values
are surrounded by single quotes
Syntax
type variableName = value;
Where type is one of C types (such as int), and variab/eName is the name of the
variable (such as x or myName). The equal sign is used to assign a value to the
variable.
So, to create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign the value 15 to it:
int myNum = 15;
You can also declare a variable without assigning the value, and assign
the value later: Example
int myNum; myNum -
15;
Note: If you assign a new value to an existing variable, it will overwrite the
previous value:
Example
int myNum = 15; // myNurn is 15 myNum 10; // Now
rnyNum is 10
Output Variables
You learned from the output chapter that you can output values/print text with
the printf() function: Example
printf("Hello World!
{jtrYoürSeJf!j
In many other programming languages (like Python, Java, and C++), you would
normally use a print function to display the value of a variable. However, this is
not possible in C: Example
int myNum = 15; printf(myNum); //
Nothing happens
'ltYöü'rSéJfrj
To output variables in C, you must get familiar with something called "format
specifiers".
Format Specifiers
Format specifiers are used together with the print f ( ) [unction to tell the
compiler what type of data the variable is storing, It is basically a placeholder
for the variable value.
Example
int myNum 15; printf( , myNum) ; //
Outputs 15
To print other types, use for char and %f for float:
Example
// Create variables = 5.99
int myNum = 5; // Integer (whole number)
float myF10atNum // Floating point number char myLetter -
// Character
// Print variables
printf("%d\n", myNum);
myF10atNum);
printf( myLetter);
ivyouisélf+;
To combine both text and a variable, separate them with a comma inside
the printf() function:
Example
int myNum 5; printf("My favorite number is : %d",
myNum) ;
.itYoutself,3)
To print different types in a single printf() function, you can use the following:
Example
int myNum = 5; char myLetter printf('I My number is %d and my
letter is %c", myNum, myLetter);
iityouiself<»
You will learn more about Data Types in the next chapter.
Example
int x = - 50; printf( "%d"
,
it Yourself+)
You can also assign the same value to multiple variables of the same type:
Example
int x, y, z;
= 50;
printf( " ,
C Variable Names
All C variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
Example
// Good int
minutesPerHour
// 0K, but not so easy to understand what m actually is int m
C Data Types
Data Types
As explained in the Variables chapter, a variable in C must be a specified data
type, and you must use a format specifier inside the printf() function to display it:
Example
// Create variables
int myNum = 5; // Integer (whole number)
float myF10atNum — 5.99 // Floating point
number
char myLetter // Character
// Print variables printf(
, myNum) ; printf( " ,
myF10atNum); printf(
myLetter);
iit&YoütSéIf4$
4 bytes
float
Stores fractional numbers, containing one or more decimals. Sufficient for
storing 7 decimal digits
double 8 bytes
%d or %i int
%f float
double
char
Used for strings, which you will learn more about in a later
chapter
A memory is just like a human brain. It is used to store data and instructions. Computer
memory is the storage space in the computer, where data is to be processed and
instructions required for processing are stored.
A processor is an integrated electronic circuit that performs the calculations that run a
computer. A processor performs arithmetical, logical, input/output (I/O) and other
basic instructions that are passed from an operating system (OS). Most other processes
are dependent on the operations of a processor.
Whenever you save your program(anything) into a file (any kind of file, say •add.c'), it
automatically gets stored in the secondary storage i.e. the harddisk. The Operating
System's kernel (kernel's File management system) does it for you.
When you run pro o raln, it is loaded into the main/primary menwry of the computer
called RAM (the entire pro o ratn is transferred to the RAM, by a Sinall prouram called the
loader (which often comes with the compiler i.e. is a part of the compiler).
The progratn instructions are executed in the ALU (At•itlunetic-l.ogic Unit) of the CPU (in its
registers like the Accutnulator). (say. int a I In order int b to execute in the the progral)l
instructions the . the RAVI. CPU and fetche< stores thethe
values of the variables results also in the RAM (int sutu 3();), which is then sent to the output
buffer stream (stdout) xvhich prints the results (3()) on the cotnputet• console/tertninal. here
again the Windoxvs kernel (kernel's 1/() tuanagctncnt systctn) does the printing for you.
Algoritlun in C Language
Algorithm is a step-by-step procedure, which defines a set of instructions to be
executed in a certain order to get the desired output. Algorithms are generally
created independent of underlying languages, i.e. an algorithm can be
implemented in more than one programming language.
As we know that all programming languages share basic code constructs like loops
(do, for, while), flow-control (if-else), etc. These common constructs can be used to
write an algorithm.
Example
Problem — Design an algorithm to add two numbers and display the result.
Step 1 - START
Step 2 - declare three integers a, b & c
Step 3 - define values of a & b
Step 4 - add values of a & b
Step 5 - store output of step 4 to c
Step 6- print c
Step 7 - STOP
FLOWCHART
Flowchart symbols:
The different flowchart symbols have different conventional meanings.
Terminal Symbol: In the flowchart, it is represented with the help of a circle for denoting
the start and stop symbol. The symbol given below is used to represent the terminal
symbol.
o Input/output Symbol: The input symbol is used to represent the input data, and the
output symbol is used to display the output operation. The symbol given below is used
Input/output symbol.
o Processing Symbol:lt is represented in a flowchart with the help of a rectangle box used
to represent the arithmetic and data movement instructions The symboi given below is
used to represent the processing Symbol,
Decision Symbol: Diamond symbol is used for represents decision-making staternents.
The symbol given below is used to represent the decision symbol.
o Connector Symbol:The connector symbol is used if flows discontinued at some point and
continued again at another place. The following symbol is the representation of the
connector symbol.
Flow lines: It represents the exact sequence in which instructions are executed. Arrows are
used to represent the flow lines in a flowchart, The symbol given below is used for
representing the flow lines:
Hexagon symbol (Flat): It is used to create a preparation box containing the loop setting
statement. The symbol given below is used for representing the Hexagon symbol.
Example 1
Design a flowchart for adding two numbers entered by the user.
Types of Errors in C
C language broadly classified errors into 5 types. They are
7. Syntax Errors
Errors occur when you violate the rules of writing C syntax is said to be
"Syntax errors". This compiler error indicates that this must be fixed before
the code will be connpiled. These ertots ate identified by the compiler so
a. void main ( )
b. void main ( )
int a;
2. Run-Time Errors
Errors which are occurred after a successful compilation of program is said to
st!ing index out of bounds, etc. are most frequent ' A_jn time et r ors. These
Syntax:
a. void main ( )
int a=10; int c=a/O; // Here number divisible zero
error . occurs
b. void main ( )
int a
occurs
3. Linker Errors
These errors are generated after compilation we link the different object files
with the main's object using the Ctrl+F9 short cut key. These errors occurred
when the executable program cannot be generated. This may be due occurred
becauy;e of func ( leclatati01), files, etc
instead of main ( )
t hod
4. Logical Errors
If our expectation is one thing and result output is
other thing then that kind of error we said it as
"Logical errors". Let suppose if we want sum of the
2 numbers but given output is the multiplication of
2 numbers then this said to be Logical error. It can
be detected by line by line clebugging.
Syntax:
void Main ()
the numbers
5. Sematic Errors
This error generated if and only if written code is not understandable format
to the C compiler.
Syntax:
void main()
int
z; // semantic error }
OPERA'I'ORS IN C
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language
Assume variable A holds 10 and variable B holds 20 then — Show Examples
Operator Description Example
Checks if the values of two operands are equal or not If yes, then
the condition becomes true is not
true
Checks if the values of two operands are equal or not. If the values
are not equal, then the condition becomes true is true
Checks if the value of left operand is greater than the value of right
operand. If yes, then the condition becomes true. is not
true
Checks if the value of left operand is less than the value of right
operand. If yes, then the condition becomes true. is true
Checks if the value of left operand is less than or equal to the value
of right operand. If yes, then the condition becomes true. is true
operators supported by C Assume
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable
A holds 1 and variable B holds 0, then — Show Examples
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation.
The truth tables for &, l, and 'A is as follows —
P q p I q
0
1 1 1
Operator Description
Example
Binary AND Operator copies a bit to the result if it exists in both
0000
1100
49,
Binary XOR Operator copies the bit if it is set in one operand but
not i.e.
12, i.e.
0011
0001
-(60),
Binary One's Complement Operator is unary and has the effect of
'flipping' bits.
Binary Left Shift Operator. The left operands value is moved left by
240 i.e.
the number of bits specified by the right operand.
0000
Assignment Operators
The Binary Right Shift Operator. The left operands value is moved right 15 i.e.
following by the number of bits specified by the right operand. 0000
table lists
the assignment operators supported by the C language — Show Examples
Operator Description Example
from the left operand and assigns the result to the left operand.
is same
Divide AND assignment operator. It divides the left operand with the
right operand and assigns the result to the left operand.
Right
shift AND
Modulus AND assignment operator. It takes modulus using twoassignment
operator
operands and assigns the result to the left operand.
Bitwise AND
assignment
operator.
Bitwise
inclusive
OR and
equivalent assignmen
t
operator.
C %= A is equivalent
Misc Operators sizeof & ternary C 2 is
same as
is same as C = C
Operators Precedence in C
operator precedence determines the grouping of terms in an expression and decides how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has a higher precedence than the addition operator.
Category Operator Associativity
Left to right
Additive
Left to right
Shift
Left to right
Relational
Left to right
Equality
Left to right
Bitwise AND
Left to right
Bitwise XOR
Left to right
Bitwise OR
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a
higher precedence than + , so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will
be evaluated first.
Show Examples
Logical AND
Left to right
Logical OR
Left to right
Conditional
Right to left
UNIT 2
Loops IN c
A loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement in most of the programming
languages —
C programming language provides the following types of loops to handle looping
loop
...while
loops
statements
all
following
Loop Type & Description
loop
It is more like a while statement, except that it tests the condition at the end of
loop body.
You can use one or more loops inside any other while, for, or do..while loop.
Control Statements
change execution from its normal sequence. When execution
automatic objects that were created in that scope are destroyed.
control statements.
break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
continue statement
Causes the loop to skip the remainder of its body and immediately retest it condition
prior to reiterating.
oto statement
C Arrays
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To create an array, define the data type (like int) and specify the name of the
array followed by square brackets [l .
To insert values to it, use a comma-separated list, inside curly braces:
int myNumbers[] {25, 50, 75, 100);
Array indexes start with O: [01 is the first element. ( 1| is the second element, etc.
Example
{25, 50, 75, 100); int myNumbers[l
myNumbers[Øl) •,
// Outputs 25
Example
33; myNumbers
Example
{25, 50, 75, 100); int
myNumbers[]
myNumbers [0] 33;
printf("%d", myNumbers[Øl);
// Now outputs 33 instead of 2
Example
int myNumbers[] {25, 50, 75, 100); int i;
for (i printf(
myNumbers[i]);
Example
// Declare an array of four integers: int
myNumbers[4];
// Add elements myNumbers[0]25;
myNumbers [1] myNumbers
[2] = 75; myNumbers [3] = 100;
Using this method, you have to know the size of the array, in order for the
program to store enough memory.
You are not able to change the size of the array after creation.
one Dimensional Array in C:
one dimensional array is an array that has only one subscript specification that is needed to
specify a particular element of an array. A one-dimensional array is a structured collection of
components (often called array elements) that can be accessed individually by specifying the
position of a component with a single index value. syntax: data-type arr_name[array_size];
A two-dimensional array in C can be thought of as a matrix and
columns.
C Strings
Strings
Strings are used for storing text/characters.
For example, "Hello World" is a string of characters.
Unlike many other programming languages, C does not have a String type to easily
create string variables. However, you can use the char type and create an array of
characters to make a string in C:
We will write the first C program for bubble sort using a for loop. In this example, we will a
use nested for loop in C to sort the elements of a one-dimensional array. To begin with, we
wili ask for the total number of elements and then the values from the user. Once we get the
elements, we will use the for loop to iterate through the elements and sort them in ascending
order.
estdio.h>
&num)
Enter the Value of Elementst for(x =
temp = arrlyl•,
arrly + 11 = temp•,
arrlxl)•,
return 0
Selection sort in C
{include < std io . h>
int tmp
tmp ;
int n)
void selectionSort (int arra
for (int j
i n t min
for (in U i n ;
if (a r r ( i ) arr [rninl ) rn i n i;
print f
int main ( )
int arr [ ] { 20 , 12 , 10 , 15 ,
12 10 15 20
2 12 10 15 20
program to Find Roots of a Quadratic Equation
printf(
dÅFcramin nt.*
root2 =
Rün• ode?
Output
Notion of order of complexity in C Language
AsymptoticNotation
Asymptotic complexity is a way of expressing the cost of an algorithm using idealized
units of computational work.
In order to choose the best algorithm for a task many factors, lil<e how long will it take for
an algorithm to run or how much memory will be taken by the algorithm! during
running, has to be considered.
The Bigo not@tion noeasutes efficiency based on the timo it takes for the algorithrcj to
run as the function of the input size I.e. the pajametet«qutrecl by the upper bounci
functiom
Bi -O Notation O ma be denoted by the positive constants c and no such that 0 < f(n) <
{ f(n) : there exist ctg(n) fog al! n > no l.
Notation
The Big-Omega notation is similar to Big-O notation except that it is a lower function.
It describes the size.
Theta Notation
The Theta notation denotes that the function f(n) is bounded by the function from both
the top and bottom.
Little o Notation
The Little o Notation represents a loose bounding version of Big-O. The functiongln) bounds
from the top of function f(n) but not the bottom.
Little oh Notation (o) may be denoted by the following expression:
o(g(n)) = { f(n) : for any positive constant c >0 there exists a constant nØ_such that C (n)
< c x g(n) for all n > no )
Little omega Notation
The Little omega Notatiomrepresents a loose bounding version of T he function g(n) bounds
from the bottom of the function f(n) the tQ?.
The utility of Big-O np&ation may be best explained by considerfino two cliff?!
algorithms performing the same task. The task to be performed is to finci the !argest
element in the arra rovided b the user.
UNIT 3
FUNCTIONS IN C
A function is a group of statements that together perform a task. Every C program has
at least one function, which is main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division is such that each
function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call.
For example, strcat() to concatenate two strings, memcpy() to copy one memory
location to another location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
Defining a Function
The general form of a function definition in C programming language is as follows —
A function definition in C programming consists of a function header and a function body. Here
are all the parts of a function —
Return Type — A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name — This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters — A parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. This value is referred to as actual parameter or argument.
The parameter list refers to the type, order, and number of the parameters of a
function. Parameters are optional; that is, a function may contain no parameters.
Function Body — The function body contains a collection of statements that define
what the function does.
Example
Given below is the source code for a function called max(). This function takes two parameters
num 1 and num2 and returns the maximum value between the two —
Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts —
return_type pat•atneter list );
For the above defined function max(), the function declaration is as follows —
int Ina.x(int num l . int nunü)•,
Parameter names are not important in function declaration only their type is required,
so the following is also a valid declaration — int max(int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top
of the file calling the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.
For example —
We have kept max() along with main() and compiled the source code. While running
the final executable, it would produce the following result — 'Max xalue is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function
Formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a
function —
1 Call by value
This method copies the actual value of an argument into the formal parameter
of the function. In this case, changes made to the parameter inside the function
have no effect on the argument.
2 Call by reference
This method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in
the call. This means that changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function.
RECURSION
Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function, then it IS
called a recursive call of the function
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating
the factorial of a number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a given number using a recursive
When the above code is compiled and executed, it produces the following result — Factorial
of 12 is 479001600
Fibonacci Series
The following example generates the Fibonacci series for a given number using a
recursive function
{include •stdio.h
When the above code is compiled and executed, it produces the following result -
13
21
34
Factorial of a Number Using Recursion
ine n;
lonöin€måitåp1yNumbers(int: n)}
s9canf$Xd%Qq
FintfCEnterÜa„ pp9åtivéAntegen:
'Fagtqr'
•.élsea€
Output
Enteräa$.pös •
6.
20
UNIT 4
STRUCTURE
Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine
data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books
in a library. You might want to track the following attributes about each book —
Title
Author
Subject
Book ID
Defining a Structure
define a structure, you must use the struct statement. The struct staternent defines
new data type, with more than one member. The format of the struct statement is as
follows -
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it is
optional. Here is the way you would declare the Book structure —
return 0;
When the above code is compiled and executed, it produces the following result
— Book I title : C Programmino
Book I author : Nuha Ali
Book I subject : C Programming Tutorial
Book I book_id : 6495407
Book 2 title : Teleconl Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book id : 6495700
* function declaration */
Oid printBook( struct Books book
)
pointers to Structures
can define pointers to structures in the same way as you define pointer to any other
variable -
Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the '&'; operator before the
structure's name as follows -
To access operator the members as follows of - a structure using a pointer to that structure, you
int main( ) {
/* book I specification */
Bookauthor :Nuha Al
Booksubject :C Programming Tutorial
Book book id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book id : 6495700
Bit Fields
Bit Fields allow the packing of data in a structure. This is especially useful when memory
or data storage is at a premium. Typical examples include —
Packing several objects into a machine word. e.g. 1 bit flags can be compacted.
Reading external file formats -- non-standard file formats could be read in, e.g., 9bit
integers.
C allows us to do this in a structure definition by putting :bit length after the variable. For
example —
struct packed_struct {
Here, the packed_struct contains 6 members: Four 1 bit flags fl ..f3, a 4-bit type and a 9-
bit my_int.
C automatically packs the above bit fields as compactly as possible, provided that the
maximum length Of the field is less than or equal to the integer word length of the
computer. If this is not the case, then some compilers may allow memory overlap for the
fields while others would store the next field in the next word.
POINTERS
pointers in C are easy and fun to learn. Some C programming tasks are performed more easily
with pointers, and other tasks, such as dynamic memory allocation, cannot be performed
without using pointers. So it becomes necessary to learn pointers to become a perfect C
programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its
address defined which can be accessed using ampersand (&) operator, which denotes
an address in memory. Consider the following example, which prints the address of the
variables defined —
When the above code is compiled and executed, it produces the following result —
Address of varl variable: bff5a400
Address of var2 variable: bff5a3f6
WInat are Pointers?
o inter is a variable whose value is the address of another variable, direct ddress
of the memory location. Like any variable or constant, you must declare a ointer
before using it to store any variable address. The general form of a pointer variable
declaration is —
*vac-
natne; pc
Here, type is the pointer's base type; it must be a valid C data type and var-name
is the name of the pointer variable. The asterisk * used to declare a pointer is the sarne asterisk
used for multiplication. However, in this statement the asterisk is being used to designate a
variable as a pointer. Take a look at some of the valid pointer declarations int *Il): / * pointer
to an integer */ double *dp: / * pointer to a double */ float *fp; /* pointer to a float */ char
*ch / * pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise,
is the same, a long hexadecimal number that represents a memory address. The only
difference between pointers of different data types is the data type of the variable or constant
that the pointer points to. How to Use Pointers?
There are a few important operations, which we will do with the help of pointers very
int var 20: /* actual variable declaration */ int frequently. (a) We define a pointer variable,
*ip; / * pointer variable declaration */ (b) assign the address of a variable to a
pointer and (c) finally access the value at the
address available in the pointer variable. This
ip &var; / * store address of var in pointer is done by using unary operator * that returns
the value of the variable located at the
printf("Address of var variable: &var address specified by its operand. The
following example makes use of these
/ * address stored in pointer variable */
printf("Address stored in ip variable:
ip variable*/
j:
\ Ollie oi *Il) ariable•
the above code is compiled and executed, it produces the following result -
\ddtcss of vat variable: btTd8b3e
\ddltss stored in ip variable: bf1118b3c
*ip aloe
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you
do not have an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider
the following program -
When the above code is compiled and executed, it produces the following result —
In most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the
memory address 0 has special significance; it signals that the pointer is not intended to
point to an accessible memory location. But by convention, if a pointer contains the null
(zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an lift statement as follows —
/* succeeds if p is null */
pointers in Detail
pointers following have important many but pointer easy concepts concepts and should they
be are clear very to important any C programmer to C programming.-
Array of pointers
2
You can define arrays to hold a number of pointers.
Pointer to pointer
3
C allows a function to return a pointer to the local variable, static variable, and
dynamically allocated memory as well.
NOTE :-
➢ AS I AM PROVIDING YOU THIS NOTES BY AIMED YOU JUST HAVE TO BE PREPARED FOR YOUR
UNIVERSITY EXAMINATION
➢ IF YOU NEED ANY EXTRA MATERIAL FOR STUDY ND EXAM REFERANCE THEN ALSO YOU CAN
MSG MI PERSONALLY HERE :- FYNOTESPROVIDER
➢ WE’VE ALSO CREATED A GROUP IN THAT YOU CAN DISCUSS YOUR DOUBTS WITH YOUR FRIENDS
FROM DIFFERENT COLLEGES STUDENTS OF SAME UNIVERSITY :- rtmnuFYfriendcircle
➢ THE LAST REQUEST FROM MY SIDE IS THAT GUYS YOU JUST HAVE TO SHARE THIS NOTES WITH
YOUR COLLEGE FRIENDS ND DO CONTINUOUSLY SUPPORT TO THIS PLATFORM.