0% found this document useful (0 votes)
63 views62 pages

Computational Skills Theory Notes All Units

Uploaded by

sshreyakam365.0
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)
63 views62 pages

Computational Skills Theory Notes All Units

Uploaded by

sshreyakam365.0
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
You are on page 1/ 62

COMPUTATIONAL SKILL

RTMNU ENGINEERING THEORY NOTES


COMPUTATIONAL SKILL

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.

➢ Click here for Joining official FY 2023 Notes


Group @RTMNUNOTESFY2023
➢ Click here for Joining Discussion Notes Group
➢ @RTMNUFYFRIENDCIRCLE
➢ Click here for Joining official ALL YEAR Notes
Group
➢ @Rtmnupdates2023
UNlT -1
•CO PROGRAMMING

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

Difference between C and C++


C++ was developed as an extension of C, and both languages have almost
the same syntax
The main diffference between C and C++ is that C++ support classes and
objects, while C does not
Get Started
This tutorial will teach you the very basics of C.
It is not necessary to have any prior programming experience.

Get Started With C


To start using C, you need two things:
A text editor, like Notepad, to write C code
A compiler, like GCC, to translate the C code into a language that the computer
will understand

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>

int main() { printf( "Hello


World ! return 0;

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>

int main() { printf( "Hello


World! " ) ; return 0;

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.

Line 5: return ends the main() function.


Line 6: Do not forget to add the closing curly bracket } to actually end the main
function.

Output (Print Text)


The printf() function is used to output values/print text:

Example
#include < stdio.h>

int main() { printf( 'I He110


World!
return 0;

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.

int main() { printf( "Hello


World! " ) ; printf("l am
learning C. " return 0;
New Lines
To insert a new line, you can use the character:

Example
#include < stdio.h>

int main() { printf( "Hello


World! \n"); printf("l am
learning C.
return 0;

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>

int main() { printf("He110 World! am learning C. \nAnd it is awesome


! " ) ; return 0;

Tip: Two characters after each other will create a blank line:
Example
#include < stdio.h>

int main() {

printf("l am learning C. "


return 0;
itYourselfi»

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:

\t Creates a horizontal tab


Inserts a backslash character ( \) Inserts a
double quote character

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.

Comments can be singled-lined or multi-lined.

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 * /.

Any text between / * and * / will be ignored by the compiler:

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

Declaring (Creating) Variables


To create a variable, specify the type and assign it a value:

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.

A format specifier starts with a percentage sign followed by a character.


For example, to output the value of an int variable, you must use the format
specifier or surrounded by double quotes, inside the prjntf() function:

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.

Add Variables Together


To add a variable to another variable, you can use the + operator:
Example
int x int y
int sum = x
+ y; printf(
"%d" , sum);

Declare Multiple Variables


To declare more than one variable of the same type, use a commaseparated
list:

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

The general rules for naming variables are:


Names can contain letters, digits and underscores
Names must begin with a letter or an underscore (_ )
Names are case sensitive (myVar and myvar are different variables)
Names cannot contain whitespaces or special characters like ! , # , 0/0, etc.
Reserved words (such as int) cannot be used as names

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$

Basic Data Types


The data type specifies the size and type of information the variable will store.

In this tutorial, we will focus on the most basic ones:

Data Type Size Description


int 2 or a bytes Stores whole numbers, without decimals

4 bytes
float
Stores fractional numbers, containing one or more decimals. Sufficient for
storing 7 decimal digits

double 8 bytes

Stores fractional numbers, containing one or more decimals. Sufficient for


storing 15 decimal digits

char 1 byte Stores a single character/letter/number, or ASCII values

Basic Format Specifiers


There are different format specifiers for each data type. Here are some of them:

Format Specifier Data Type Try it

%d or %i int
%f float

double
char

Used for strings, which you will learn more about in a later
chapter

INTRODUCTION TO COMPONENTS OF COMPUTER SYSTEM

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.

here is a program stored and executed in computers'?

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.

An operating system is a software programme required to manage and operate a computing


device like smartphones, tablets, computers, supercomputers, web servers, cars, network
towers, smartwatches, etc. It is the operating system that eliminates the need to know coding
language to interact with computing devices. It is a layer of graphical user interface (GUI), which
acts as a platform between the user and the computer hardware. Moreover, the operating
system manages the software side of a computer and controls programs execution

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.

How to Write an Algorithm?


There are no well-defined standards for writing algorithms. Rather, it is problem and
resource dependent. Algorithms are never written to support a particular programming

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 in C is a diagrammatic representation Of SOtlUOtiCO Of logical Steps Of a


program. Flowcharts use simpjegeometric Shapes to depict processes arid arrows io
show relationships and flow:A in C Ian ua e isa ra hidäl
re resentation of an aj process/dätä flowchart
orithm.

Flowchart symbols:
The different flowchart symbols have different conventional meanings.

The various symbols used in Flowchart Designs are given below.

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

these errors are called "connpile-time errors".


Syntax:

a. void main ( )

int a // here semi colon ( ; ) missed

b. void main ( )

int a;

// here parenthesis ( } ) missed

2. Run-Time Errors
Errors which are occurred after a successful compilation of program is said to

be "run-time errors". Number divisible by zero, array index out of bounds,

st!ing index out of bounds, etc. are most frequent ' A_jn time et r ors. These

errors can't be very hard to detect at the compile time.

Syntax:

a. void main ( )
int a=10; int c=a/O; // Here number divisible zero

error . occurs

b. void main ( )

int a

int out=a [4] ; // Here array out of bounds error

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

Most flequent linketetoc')t is VA'!itinq Main() insteacl of a noain() trjethocJ

Syntax: void Main ( ) // Here Main () method used

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 ()

print f ( "*d", sum (10, 20) ) •

int sum (int a, int b)

return x* y; // expectation is sum but we are multiplying

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

An operator is a symbol that tells the compiler to perform specific mathematical or


logical functions. C language is rich in built-in operators and provides the following types
of operators —
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works.

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

Adds two operands. A + B = 30

Subtracts second operand from the first. A - B = -10


Multiplies both operands. B = 200

Divides numerator by de-numerator.

Modulus Operator and remainder of after an integer division

Increment operator increases the integer value by one.


Decrement operator decreases the integer value by one.
Relational Operators
The following table shows all the relational
variable A holds 10 and variable B holds 20 then
— Show Exannples
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 greater than or equal to 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 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

Operator Description Example


Called Logical AND operator. If both the is
operands are non-zero, then the condition false
becomes true
(A Il
Called Logical OR Operator. If any of the two B)
operands is non-zero, is
Il
then the condition becomes true.
true
.
Called Logical NOT Operator. It is used to
reverse the logical state of its operand. If a
condition is true, then Logical NOT operator B) is
will make it false true

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

Assume A = 60 and B = 13 in binary format, they


will be as follows — A = 0011 1100
B = 0000 1101
= 0000 1100
AIB = 0011 1101
AA B = 0011 0001

The following table lists the bitwise operators supported by


C. Assume variable 'A' holds 60 and variable 'B' holds 13,
then
Show Examples

Operator Description
Example
Binary AND Operator copies a bit to the result if it exists in both

0000
1100

Binary OR Operator copies a bit if it exists in either operand. 61, i.e.


0011
1101

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

Simple assignment operator. Assigns values from right side C=A+ B


will
assign
the value
Of A + B
Add AND assignment operator. It adds the right operand to the left
operand and assign the result to the left operand.
C A is equivalent
0/0
Subtract AND assignment operator. It subtracts the right operand A

from the left operand and assigns the result to the left operand.

is same

Multiply AND assignment operator. It multiplies the right operand


with the left operand and assigns the result to the left operand.

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.

Left shift AND assignment operator.


Bitwise
equivalent
exclusive
OR and
assignment
operator.
equivalent

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

Besides the operators discussed above, there are a few other


important operators including sizeof and ? : supported by
the C Language.
C 2 is same as same as
C = C 1
2
Show Examples Conditional Expression.
Example
Operator Description
sizeof(a), where a is
integer, will return 4.
sizeof()Returns the size of a
variable.
&a; returns the actual
address of the variable.
Returns the address of a
variable. *a;

If Condition is true ? then


Pointer to a variable. value X otherwise value Y

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

Postfix Left to right

+_ ++ - - (type)* & sizeof Right to left


Unary
Left to right
Multiplicative

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

Assignment Right to left


Comma
Left to right

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

Repeats a statement or group of statements while a given condition is true. It tests


the condition before executing the loop body.

Executes a sequence of statements multiple times and abbreviates the code


manages the loop variable.

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.

Control Statement & Description

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

Transfers control to the labeled statement


When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the
for(;•,) construct to signify an infinite loop.

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);

now created a variable holds an array of four


Access the Elements of an Array
access an array element, refer to its index number

Array indexes start with O: [01 is the first element. ( 1| is the second element, etc.

This statement accesses the value of the first element [O) in


myNumUere»

Example
{25, 50, 75, 100); int myNumbers[l
myNumbers[Øl) •,

// Outputs 25

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
33; myNumbers

Example
{25, 50, 75, 100); int
myNumbers[]
myNumbers [0] 33;

printf("%d", myNumbers[Øl);
// Now outputs 33 instead of 2

Loop Through an Array


You can loop through the array elements with the for loop.

The following example outputs all elements in the myNurnbers array:

Example
int myNumbers[] {25, 50, 75, 100); int i;

for (i printf(
myNumbers[i]);

Set Array Size


Another common way to create arrays, is to specify the size of the array, and add
elements later:

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:

char greetings[] - "Hello World! "

C Program for Bubble Sort Using for Loop

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>

int avv1501, num, x, y, temp,

Enter the Numbev of Elements you want lhe array'

&num)
Enter the Value of Elementst for(x =

0', x < num•, x++)


&avrlxl)•,

for(x = O', x < num - 1 •,


for(y = y < num - x - y++)k
If(arrlyl > arrly +

temp = arrlyl•,

arrly + 11 = temp•,

after implementing bubb\e sorti

for(x = 0', x < num•,

arrlxl)•,
return 0

lease Enter*théNÜmber, please Enter theÄ/a1ue of


Elements: 9 5r"-2W3 Array after
implementirWbubb1ex sort: 3éY5

Selection sort in C
{include < std io . h>

void swap (int int {

int tmp

tmp ;

// selection sort function

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;

swap (&arr [min) ,


void display (int arr [l , int for (int i

print f ( " arr [il ) ;

print f

int main ( )

int arr [ ] { 20 , 12 , 10 , 15 ,

int n sizeof (arr) / sizeof (arr 101 ) ,


("Elements before sorting : \ n" )

selection Sort (arr, n) after

sorting : \ n" ) display (arr, n)

output of the program:

Elements before sorting:

12 10 15 20

Elements after sorting:

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.

Asymptotic nota_tCQJ) is_ a asymptotic notations is to remove easy e;-taiÄs of


the algouithna.
Big-O Notation

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.

Omega Natation may be denoted by the following expression:


omega (g (n)) { f(n) : there exist positive constants c and no such that 0 < c A f(n)
for all n >

Theta Notation

The Theta notation denotes that the function f(n) is bounded by the function from both
the top and bottom.

Theta Notation may be denoted by the following expression• theta(g(n)) - { f(n) :


there exist positive constants cl and c2 and no such that 0 < c] g(n) < f(n) < c2 •k g(n)
for all n > no }

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?.

Little o_nnega Notation (w) nna.y be denote(.l by the


foliovving .„for any-positive c thew g .(n)
f(n) fot all n no )
Big-O No_tatjon

Anyptoblenn associated with computer than one solution


These solutions come in the form of algorithms. It is necessary to find the efficiency uf
the algorithms so that the best algorithm may be adapted as the solution. The PeigzC)
notatiotumt.vicie_s a basis for measuring_the efficiency of the
The notation measures efficiency based on the time It takes for
as the function the algorithm ce uired b the
functiorv
Big-O Notation (O) may be denoted by the following expressiorv
{ f(n)_: there exjsvpositive such tha&O < < c e g(n) for a!!

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 —

Sr.No. Call Type & Description

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 —

Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use the keyword struct to define variables of
structure type. The following example shows how to use a structure in a program —

/ * Declare Book I of type Book */


1300ks Book I
Declare Book2 Book Books
Book2:
book I specificationk I .title. "C Proeramnlinu"):
strcpy( Book Boo I .author, "Nuha Ali"):
strcpy Book I .subject, "C Proertlll)llling I utorial")
book id

* 1900k 2 specification strcpy(


Book2.title, 'UI elec011) Billing"):
strcpy( Book2.author. "Zara relecom Ali"):Billing "l
utorial"): strcpy( Book2.subject. Book2.b00k_id
6495700:

* print Bookl infl) printf( "Book I title :


Bookl .title):
Book I .author):
printf( printf( "Book "Book I I sut2iect author •
0'6.s n". Bookl .subject):

printf( "Book I book id : Ood\n". Book I .book id):

* print Book2 info */ printf( "Book 2


title n". Book2.title):
printf( "Book 2 author O os n", Book2.author)•.
printf( "Book 2 subject : 0 Os\n". Book2.subject):
printf( "Book 2 book id : Book2.book id):

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

Structures as Function Arguments


You can pass a structure as a function argument in the same way as you pass any other variable
or pointer.
struct Books { char title15()]: char char subject! 1001: book_id,

* function declaration */
Oid printBook( struct Books book
)

struct Books Bookl : type Book */ /* Declare Bookl


of'
/* Declare Book2 of type Book */
struct Books Book2:

* book I specification */ strcpy( Book I .title, "C


Programnling"); strcpy( Book I .author. "Nuha Ali"):
strcpy( Book I .subject, "C Progralüliling Tutorial"):
Book I .book_id 6495407:
/* book 2 specification */ strcpy( Book2.title. "Teleconn
Billing")• strcpy( Book2.author. "Zara Ali"):
strcpy( Book2.subject. I eleeonn Billing I utorial "
Book2.b00k_id 6495700:

/* print Bookl info printBook( Bookl ):


/* Print Book2 info */ printBook( Book'2 return

void printBook( struct Books book )

printf( "Book title . book.title): printf( "Book author : 0


os\n't book.author)•, printf( "Book sulliect :
book'.subject):

When the above code is compiled and executed,


it produces the following result Book title : C
Programmin o
Nuha Ali author sllhject :
C Progranuning "I'tltorial id
: 6495407
'l'elec0111 Billing
: Zara Al i
: Bill ing "l (Ito rial id :
6495700

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

must use the -4

Let us re-write the above example using structure pointer.

int main( ) {

struct Books Bookl ; /* Declare Bookl oftype Book */


struct Books Book2; /* Declare Book2 of type Book */

/* 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*/

/ * access the value using the pointer */


operations —

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 —

The value of ptr is 0

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 —

if(ptr) /* succeeds if p is not null */

/* 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.-

No. Concept & Description


Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, -

Array of pointers
2
You can define arrays to hold a number of pointers.

Pointer to pointer
3

C allows you to have pointer on a pointer and so on.


4 Passinq pointers to functions in C
Passing an argument by reference or by address enable the passed argument to
be changed in the calling function by the called function.

5 Return pointer from functions in C

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.

You might also like