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

DS Unit I

The document provides an introduction to C programming, outlining its history, importance, and applications in software development. It covers fundamental concepts such as variables, constants, data types, operators, decision-making statements, and loops, along with examples and explanations. Additionally, it discusses arrays and multidimensional arrays, emphasizing their role in storing multiple values efficiently.

Uploaded by

thechilledguy08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DS Unit I

The document provides an introduction to C programming, outlining its history, importance, and applications in software development. It covers fundamental concepts such as variables, constants, data types, operators, decision-making statements, and loops, along with examples and explanations. Additionally, it discusses arrays and multidimensional arrays, emphasizing their role in storing multiple values efficiently.

Uploaded by

thechilledguy08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 190

204184 DATA STRUCTURES

Dept. of E&TC
PICT Pune

Prepared By:

Dr. S. S. Vasekar
Introduction to C Programming

C programming is a general-purpose, procedural, imperative computer

programming language developed in 1972 by Dennis M. Ritchie at the Bell

Laboratories to develop the UNIX operating system. C is the most widely

used computer language. It keeps fluctuating at number one scale of

popularity along with Java programming language, which is also equally

popular and most widely used among modern software programmers.


Why to Learn C Programming?

C programming language is a MUST for students and working


professionals to become a great Software Engineer specially when they
are working in Software Development Domain. some of the key
advantages of learning C Programming:
 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms
Applications of C Programming

C was initially used for system development work, particularly the


programs that make-up the operating system. C was adopted as a
system development language because it produces code that runs nearly
as fast as the code written in assembly language. Some examples of the
use of C are -
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities
VARIABLE
⚫A variable is nothing but a name given to a
storage area that our programs can manipulate.
Each variable in C has a specific type, which
determines the size and layout of the variable's
memory; the range of values that can be stored
int a; within that memory; and the set of operations
that can be applied to the variable.
2bytes

⚫ The name of a variable can be composed of


letters, digits, and the underscore character. It
must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because
C is case-sensitive.
CONSTANTS
⚫Constants refer to fixed values that the
program may not alter during its
execution. These fixed values are also
called literals.
⚫Constants can be of any of the basic data
types like an integer constant, a floating
constant, a character constant, or a string
literal. There are enumeration constants
as well.
⚫Tokens in C
⚫A C program consists of various tokens
int a; and a token is either a keyword, an
int b,b1,b123;
interger a identifier, a constant, a string literal, or a
Intgr a
symbol. For example, the following C
statement consists of five tokens −

Data Types

In C programming, data types are used to specify the type of a variable, which determines
the amount of memory the variable takes up and the range of values that can be stored in
that memory. The data types in C can be classified into the following categories:
Data Types
⚫ The data type specifies the size and type of information
the variable will store.
Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647


int 2 or 4 bytes

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 8 bytes or (4bytes -9223372036854775808 to 9223372036854775807


for 32 bit OS)

unsigned long 8 bytes


Basic Format Specifiers
⚫ There are different format specifiers for each data
type. Here are some of them:
Format specifier for integer

Output:
Format specifier for float

Output:
Format specifier for Double

Output:
Format specifier for Char

Output:
Format specifier for String

Output:
Set Decimal Precision

Output:
Output:
OPERATORS
o An operator is a symbol that tells the compiler
to perform specific mathematical or logical
functions.
o C language is rich in built-in operators and
provides the following types of operators:

• Arithmetic Operators
• Assignment Operators
• Logical Operators
• Relational Operators
• Bitwise Operators
Arithmetic Operators
⚫ Arithmetic operators are used to perform common mathematical
operations.
+ Operator
(Adds two values together)

#include <stdio.h> Output:


int main()
{
int x = 5;
int y = 3;
printf("%d", x + y);
return 0;
}
- Operator
(Subtracts one value from another)

Output:
* Operator
(Multiplies two values)

Output:
/ Operator
(Divides one value by another)

Output:
% Modulus Operator
(Returns the division remainder)

Output:
++ Increment Operator
(Increases the value of a variable by one)

Output:
-- Increment Operator
(Decreases the value of a variable by one)

Output:
Assignment Operators
Assignment operators are used to assign values to variables.
(Example: int x=5)
Relational/Comparison Operators
 Comparison operators are used to compare two values (or variables).

 This is important in programming, because it helps us to find answers and make


decisions.

 The return value of a comparison is either 1 or 0, which means true (1) or false (0).
Relational/Comparison Operators

Output:
Relational/Comparison Operators

Output:
Logical Operators
Logical operators are used to determine the logic between variables or values:
Logical && (and) Operator

Output:
Logical II (or) Operator

Output:
Logical ! (not)Operator

Output:
Sizeof Operator
The memory size (in bytes) of a data type or a variable can be found
with the sizeof operator:

• Note that we use the %lu format specifier to print the result, instead of %d.

• It is because the compiler expects the sizeof operator to return a long


unsigned int (%lu), instead of int (%d).

• On some computers it might work with %d, but it is safer to use %lu
Sizeof Operator

Output:
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The
truth tables for &, |, and ^ is as follows :

Assume A = 60 and B = 13 in binary format, they will be as follows −


A = 0011 1100 , B = 0000 1101

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

A&B = 0000 1100


A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
Operator Description Example

& Binary AND Operator copies a bit to the result (A & B) = 12, i.e., 0000 1100
if it exists in both operands.

| Binary OR Operator copies a bit if it exists in (A | B) = 61, i.e., 0011 1101


either operand.

^ Binary XOR Operator copies the bit if it is set (A ^ B) = 49, i.e., 0011 0001
in one operand but not both.

~ (~A ) = ~(60), i.e,. -0111101


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 the number of bits
specified by the right operand. A << 2 = 240 i.e., 1111 0000

>> Binary Right Shift Operator. The left operands


value is moved right by the number of bits
specified by the right operand. A >> 2 = 15 i.e., 0000 111
Operato Description Example
r
= Simple assignment operator. Assigns values C = A + B will assign the value of
from right side operands to left side operand A + B to C
+= Add AND assignment operator. It adds the
C += A is equivalent to C = C +
right operand to the left operand and assign the
A
result to the left operand.
-= Subtract AND assignment operator. It subtracts
the right operand from the left operand and C -= A is equivalent to C = C - A
assigns the result to the left operand.
*= Multiply AND assignment operator. It multiplies
the right operand with the left operand and C *= A is equivalent to C = C * A
assigns the result to the left operand.
/= Divide AND assignment operator. It divides the
left operand with the right operand and assigns C /= A is equivalent to C = C / A
the result to the left operand.
%= Modulus AND assignment operator. It takes
C %= A is equivalent to C = C %
modulus using two operands and assigns the
A
result to the left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
Operators Precedence in C
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

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 | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


Decision Making Statements
⚫ Decision making structures require that the
programmer specifies one or more conditions to
be evaluated or tested by the program, along
with a statement or statements to be executed if
the condition is determined to be true, and
optionally, other statements to be executed if the
condition is determined to be false.
⚫ Figure shown below is the general form of a
typical decision making structure found in most of
the programming languages:
Flow chart for decision making
statements
If ... Else
Conditions and If Statements
C supports the usual logical conditions from mathematics:

o Less than: a < b


o Less than or equal to: a <= b
o Greater than: a > b
o Greater than or equal to: a >= b
o Equal to a == b
o Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.
C has the following conditional statements:

o Use if to specify a block of code to be executed, if a specified condition is true


o Use else to specify a block of code to be executed, if the same condition is false
o Use else if to specify a new condition to test, if the first condition is false
o Use switch to specify many alternative blocks of code to be executed
The if Statement
The else Statement
The else Statement
The else if Statement
The else if Statement
The else if Statement
Short Hand If...Else (Ternary Operator)

o There is also a short-hand if else, which is known as the ternary


operator because it consists of three operands.

o It can be used to replace multiple lines of code with a single line.

o It is often used to replace simple if else statements:


you can use the traditional if...else statement or the ternary operator.
Switch Statement
Switch Statement
Example
int day = 4;

switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}

// Outputs "Thursday" (day 4)


While Loop
Loops

While Loop
The Do/While Loop
For Loop
For Loop

o Statement 1 sets a variable before the loop starts (int i = 0).


o Statement 2 defines the condition for the loop to run (i must
be less than 5). If the condition is true, the loop will start
over again, if it is false, the loop will end.
o Statement 3 increases a value (i++) each time the code
block in the loop has been executed.
For Loop

Nested Loops

o It is also possible to place a loop inside another loop. This is


called a nested loop.
o The "inner loop" will be executed one time for each iteration
of the "outer loop":
Nested Loops
Break and Continue
Break
Continue
Break and Continue in While Loop
C Arrays
o Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.

o To create an array, define the data type (like int) and specify the name of the
array followed by square brackets [ ].

o To insert values to it, use a comma-separated list, inside curly braces:

o We have now created a variable that holds an array of four integers.


Access the Elements of an Array
Change an Array Element
Loop Through an Array
Set Array Size

Note: Using this method, you should 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.
C Multidimensional Arrays
o If you want to store data as a tabular form, like a table with rows and
columns, you need to get familiar with multidimensional arrays.

o A multidimensional array is basically an array of arrays.

o Arrays can have any number of dimensions. We will introduce the


most common; two-dimensional arrays (2D).
C Multidimensional Arrays

The first dimension represents the number of rows [2], while the second
dimension represents the number of columns [3]. The values are placed
in row-order, and can be visualized like this:
Access the Elements of a 2D Array
 To access an element of a two-dimensional array, you must
specify the index number of both the row and column.

 This statement accesses the value of the element in the first


row (0) and third column (2) of the matrix array.
Change Elements in a 2D Array
 To change the value of an element, refer to the index number of the
element in each of the dimensions:

 The following example will change the value of the element in the
first row (0) and first column (0):
Loop Through a 2D Array
 To loop through a multi-dimensional array, you need one loop for each of the
array's dimensions.

 The following example outputs all elements in the matrix array:


C Programming: Array
EXAMPLE 1: Array Initialization

Objective: Create an integer array of size 5 and initialize it with values 10, 20,
30, 40, and 50. Print the elements of the array.

#include <stdio .h>

int main ()
{
int arr [5] = {10 , 20 , 30 , 40 , 50};

// Print array elements

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


{
printf ("% d ", arr [ i]);
}

return 0;
}
Output: 10 20 30 40 50
C Programming: Array
E XAMPLE 2: Array Sum
Objective: Create an integer array of size 6 and initialize it with some values.
Calculate and print the sum of all elements in the array.

# include <stdio .h>

int main ()
{
int arr [] = {10 , 20 , 30 , 40 , 50 , 60};
int sum = 0;

// Calculate sum of array elements


for ( int i = 0; i < 6; i ++)
{
sum + = arr [ i];
}
printf (" Sum : % d\ n", sum );
return 0;
}

Output: ??
C Programming: Array
E XAMPLE 3: Largest Element
Objective: Create an integer array of size 7 and initialize it with values. Find and
print the largest element in the array.

# include <stdio .h>

int main()
{
int arr [ ] = { 35, 12, 78, 95, 42, 17, 8 };
int largest = arr[0];

// Find the largest element


for (int i = 1; i < 7; i++)
{
if (arr[i] > largest)
{ largest = arr[i];
}
}
printf("Largest element: %d\n", largest);
return 0;
}
C Strings
 Strings are used for storing text/characters.

 For example, "Hello World" is a string of characters.

o Unlike many other programming languages, C does not have a String


type to easily create string variables.
o Instead, you must use the char type and create an array of characters
to make a string in C:
Strings

 To output the string, you can use the printf() function together with
the format specifier %s to tell C that we are now working with strings:

Output:
Access Strings
 Since strings are actually arrays in C, you can access a string by
referring to its index number inside square brackets [ ].
 This example prints the first character (0) in greetings:

Output:
Modify Strings
 To change the value of a specific character in a string, refer to the
index number, and use single quotes:

Output:
Loop Through a String
 You can also loop through the characters of a string, using a for loop:

Output:
Another Way of Creating Strings

 In the examples above, we used a "string literal" to create a string variable.


This is the easiest way to create a string in C.

 You should also note that you can create a string with a set of characters.
This example will produce the same result as the previous example :
Output:
Differences

 The difference between the two ways of creating strings, is that the first
method is easier to write, and you do not have to include the \0
character, as C will do it for you.

 You should note that the size of both arrays is the same:
They both have 13 characters (space also counts as a character by the
way), including the \0 character:
Output:
C Special Characters

Strings - Special Characters

 Because strings must be written within quotes, C will misunderstand


this string, and generate an error:
Output:
C String Functions

 C also has many useful string functions, which can be used to perform
certain operations on strings.

 To use them, you must include the <string.h> header file in your program:
String Length

 For example, to get the length of a string, you can use the strlen() function:

Output:
 In the Strings, we used sizeof to get the size of a string/array.

Note that sizeof and strlen behaves differently, as sizeof also includes
the \0 character when counting:

Output:
 It is also important that you know that sizeof will always return the
memory size (in bytes), and not the actual string length:

Output:
Concatenate Strings
 To concatenate (combine) two strings, you can use the strcat() function:

Output:
Copy Strings
 To copy the value of one string to another, you can use the strcpy() function:
Compare Strings
 To compare two strings, you can use the strcmp() function.

 It returns 0 if the two strings are equal, otherwise a value that is not 0:
C Functions
 A function is a block of code which only runs when it is called.

 You can pass data, known as parameters, into a function.

 Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
Predefined Functions
o For example, main() is a function, which is used to execute code, and printf() is
a function; used to output/print text to the screen:
Create a Function
 To create (often referred to as declare) your own function,
specify the name of the function, followed by parentheses ( ) and curly brackets { }:

 myFunction() is the name of the function.


 void means that the function does not have a return value.
 Inside the function (the body), add code that defines what the function should do.
Call a Function
 To call a function, write the function's name followed by two
parentheses () and a semicolon ;

 In the following example, myFunction() is used to print a text (the action),


when it is called:
 A function can be called multiple times:
C Function Parameters

Parameters and Arguments:


 Information can be passed to functions as a parameter. Parameters act
as variables inside the function.

 Parameters are specified after the function name, inside the


parentheses.

 You can add as many parameters as you want, just separate them
with a comma:
C Function Parameters
 The following function that takes a string of characters with name as
parameter.
 When the function is called, we pass along a name, which is used inside
the function to print "Hello" and the name of each person.
C Function Parameters
Multiple Parameters
 Inside the function, you can add as many parameters as you want:
Pass Arrays as Function Parameters
 You can also pass arrays to a function:
Pass Arrays as Function Parameters
Return Values
 The void keyword, used in the previous examples, indicates that the function
should not return a value.

 If you want the function to return a value, you can use a data type
(such as int or float, etc.) instead of void, and use the return keyword inside the
function:
Function Declaration and Definition
 You can create and call a function in the following way:
 A function consist of two parts:
 Declaration: the function's name, return type, and parameters
(if any)
 Definition: the body of the function (code to be executed)

 For code optimization, it is recommended to separate the


declaration and the definition of the function.
 C programs that have function declaration above main(), and
function definition below main().

 This will make the code better organized and easier to read:
Example
Another Example
 If we use the example regarding function parameters and return
values:
C Recursion
 Recursion is the technique of making a function call itself.

 This technique provides a way to break complicated problems down into


simple problems which are easier to solve.

Example

 Adding two numbers together is easy to do, but adding a range of


numbers is more complicated.

 In following example, recursion is used to add a range of numbers


together by breaking it down into the simple task of adding two
numbers:
 When the sum() function is called, it adds parameter k to the sum
of all numbers smaller than k and returns the result.

 When k becomes 0, the function just returns 0. When running,


the program follows these steps:

 Since the function does not call itself when k is 0, the program stops there
and returns the result.
C Memory Address
 When a variable is created in C, a memory address is assigned to the variable.

 The memory address is the location of where the variable is stored on the
computer.

 When we assign a value to the variable, it is stored in this memory address.

 To access it, use the reference operator (&), and the result represents where the
variable is stored:
Note: The memory address is in hexadecimal form (0x..). You will probably not
get the same result in your program, as this depends on where the variable is
stored on your computer.

 You should also note that &myAge is often called a "pointer".


 A pointer basically stores the memory address of a variable as its value.
 To print pointer values, we use the %p format specifier.
C Structures (structs)
 Structures (also called structs) are a way to group several related variables into
one place.

 Each variable in the structure is known as a member of the structure.

 Unlike an array, a structure can contain many different data types (int, float,
char, etc.).

Create a Structure
 You can create a structure by using the struct keyword and declare each of its
members inside curly braces:

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon
 To access the structure, you must create a variable of it.

 Use the struct keyword inside the main() method, followed by the name of the
structure and then the name of the structure variable:
Access Structure Members
 To access members of a structure, use the dot syntax (.):
 Now you can easily create multiple structure variables with different values,
using just one structure:

Output:
What About Strings in Structures?
 Remember that strings in C are actually an array of characters, and unfortunately, you can't
assign a value to an array like this:
 However, there is a solution for this! You can use the strcpy() function
and assign the value to s1.myString, like this:
Simpler Syntax
 You can also assign values to members of a structure variable at declaration time,
in a single line. Just insert the values in a comma-separated list inside curly braces { }.

 Note : You don't have to use the strcpy() function for string values with this
technique:
 You can also assign one structure to another. In the following example, the
values of s1 are copied to s2:
Modify Values
If you want to change/modify a value, you can use the dot syntax (.).
And to modify a string value, the strcpy() function is useful again:
Modifying values are especially useful when you copy structure values:

strcpy(s2.myString, "Something else");

// Print values
printf("%d %c %s\n", s1.myNum, s1.myLetter, s1.myString);
printf("%d %c %s\n", s2.myNum, s2.myLetter, s2.myString);
return 0;
 Real Life Example
Use a structure to store different information about Cars:
C Pointers
 Creating Pointers
 we can get the memory address of a variable with the reference operator & :
 A pointer is a variable that stores the memory address of another variable
as its value.
 A pointer variable points to a data type (like int) of the same type, and is created
with the * operator.
 The address of the variable you are working with is assigned to the pointer:
Explanation:

 Create a pointer variable with the name ptr, that points to an int variable (myAge).
 Note that the type of the pointer has to match the type of the variable you're working
with (int in our example).
 Use the & operator to store the memory address of the myAge variable, and assign
it to the pointer.
 Now, ptr holds the value of myAge's memory address.
Dereference
 In the example above, we used the pointer variable to get the memory address of a
variable (used together with the & reference operator).
 You can also get the value of the variable the pointer points to, by using the * operator
(the dereference operator):
C Pointers and Arrays
 You can also use pointers to access arrays.
 Consider the following array of integers:

 You learned from the arrays that you can loop through the array elements with
a for loop:
 Instead of printing the value of each array element, let's print the memory address of
each array element:
 Note that the last number of each of the elements' memory address is different,
with an addition of 4.
 It is because the size of an int type is typically 4 bytes, remember:
 So from the "memory address example" above, you can see that the compiler
reserves 4 bytes of memory for each array element, which means that the entire
array takes up 16 bytes (4 * 4) of memory storage:
How Are Pointers Related to Arrays
 The memory address of the first element is the same as the name of the
array:
 This basically means that we can work with arrays through pointers!
 How? Since myNumbers is a pointer to the first element in myNumbers,
you can use the * operator to access it:
 To access the rest of the elements in myNumbers, you can increment
the pointer/array (+1, +2, etc):
Or loop through it:
 It is also possible to change the value of array elements with pointers:

 pointers must be handled with care, since it is possible to overwrite other


data stored in memory.
File Handling
Additional
information @
Arrays, pointer,
functions, structure,
union…etc from this
slide. Please note it.
Sr.No. Call Type & Description
1 Call by valueThis 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 referenceThis 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.
C-ARRAYS
Arrays a kind of data structure that can store a fixed-size sequential
collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ...,


and number99, you declare one array variable such as numbers and
use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an
index.

All arrays consist of contiguous memory locations. The lowest address


corresponds to the first element and the highest address to the last
element.

Arrays in C
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows −

type arrayName [ arraySize ];


This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and
type can be any valid C data type. For example, to declare a 10-element array called balance of type
double, use this statement −

double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};


The number of values between braces { } cannot be larger than the number of elements that we declare for
the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if
you write −

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};


You will create exactly the same array as you did in the previous example. Following is an example to
assign a single element of the array −

balance[4] = 50.0;
Example
⚫ #include <stdio.h>
⚫ Int n[10];
⚫ int main () { n[0]= first element in array
N[1]=
⚫ int n[ 10 ]; /* n is an array of 10 integers */
N[2]
⚫ int i,j;

⚫ /* initialize elements of array n to 0 */ N[9]= last element in the array :


⚫ for ( i = 0; i < 10; i++ ) { size=1
⚫ n[ i ] = i + 100; /* set element at location i to i + 100 */
⚫ }

⚫ /* output each array element's value */


⚫ for (j = 0; j < 10; j++ ) {
⚫ printf("Element[%d] = %d\n", j, n[j] );
⚫ }

⚫ return 0;
⚫ } Element[0] = 100
⚫ Element[1] = 101
⚫ Element[2] = 102
⚫ Element[3] = 103
Reference:
⚫ Element[4] = 104 https://www.tutorialspoint.com/cprogrammi
⚫ Element[5] = 105 ng/c_arrays.htm
Write a C program to input and display
roll no , name of 5 students
C-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
Text mesg memory allocation, cannot be performed without
Destination using pointers. So it becomes necessary to learn
address
pointers to become a perfect C programmer.
Int a; Let's start learning them in simple and easy steps.
2bytes ⚫ As you know, every variable is a memory location
and every memory location has its address
Int *p;
defined which can be accessed using ampersand
(&) operator, which denotes an address in
Declaration
syntax for
pointers memory. Consider the following example, which
P=&a; prints the address of the variables defined −
&-address
of variable
a.
#include <stdio.h>

int main () {

int var1;
char var2[10];

printf("Address of var1 variable: %x\n", &var1 );


printf("Address of var2 variable: %x\n", &var2 );

return 0;
}
Address of var1 variable: bff5a400 Address of var2 variable: bff5a3f6

Addresses are unsigned integer numbers,


%u
⚫What are Pointers?
⚫A pointer is a variable whose value is the
address of another variable, i.e., direct
address of the memory location. Like any
variable or constant, you must declare a
pointer before using it to store any
variable address. The general form of a
pointer variable declaration is −
⚫type *var-name;
⚫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.
Int *ptr=NULL;
Pointers in Detail
Pointers have many but easy concepts and they are very important to C programming. The following important
pointer concepts should be clear to any C programmer −

Sr.No. Concept & Description


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

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

3 Pointer to pointerC allows you to have pointer on a pointer and so on.

4 Passing pointers to functions in CPassing 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 CC allows a function to return a pointer to the local variable, static
variable, and dynamically allocated memory as well.
Call by value method
WACP to swap program

Function declarartion
Void swap(int,int);

Int main(){
Int a=10;
Int b=20;
Function calling
Swap(a,b);
Printf(%d%d”,a,b);
}

Function definition
Void swap(int x, int y)
{//=10,y=20
Int t;
t=x;
X=y;
Y=t;
Printf(“%d%d”,x,y);
}

Output=20,10 10 20
Call by Reference method
WACP to swap program

Function declarartion
Void swap(int *,int*); A=10 B=20
Int main(){
Int a=10;
Int b=20; 100 200
Function calling
Swap(&a,&b);
Printf(%d%d”,a,b);
}

Function definition
Void swap(int*x, int*y)
{//x= the value of the address 100=10
// y= the value t the address 200 =20
Int t;
t=*x;
*X=*y;
*y=t;
Printf(“%d%d”,*x,*y);
}

Output=20,10 20 10
The automatic storage class

⚫The variables declared within the body of variables are


automatic
⚫Even if we do not include the keyword in function while
declaring variables they are implicitly defined as automatic
⚫The auto is used to explicitly define a variable as
automatic.
⚫These variables are stored in primary memory.
⚫This keyword is rarely used
External storage class
⚫The keyword extern is used.
⚫It used to declare global variables which are
accessible within different files and
functions.
⚫The default value of such variable is zero.
⚫It is stored in primary memory.
//pgm1.c
#include<stdio.h>]
#include ”pgm2.c”
Int I;
Void show();
Int main()
{
i=10;
Show();
Printf(“%d”,i);
Return 0;
}
//pgm2.c
Extern int I;
Show()
{
Printf(“%d”,i);

}
The Register Storage Class
⚫The variables stored in register of CPU
are accessed in much lesser time.
⚫The keyword register is used.
⚫The default value is not known
⚫It is applicable to int and char only.
⚫The scope is limited upto the region or
block or function in which it is defined.
Static Storage class
⚫The static storage class variable makes
the variable permanent.
⚫Their can be local i.e. internal static
variables and global i.e. external static
variables.
⚫The default value is zero.
⚫They are stored in primary memory.
⚫The external static variables in a
program are declared like global variables
with the keyword static.
⚫The static var are accessible by all
functions in the program file where these
variables exist and are declared. These
variables are not accessible in the other
files.
⚫These variables exist thrugout the main
program execution.
#include<stdio.h>
Main()
{
Void show();
Printf(“\n first call”)
Show();
Printf(“\n 2nd call”)
Show();
Printf(“\n third call”)
Show();
}
Void show()
{
Static int i;
Printf(“%d”,i);
i++;
}
Op:
First call i=0; 2nd call i=1 3rd call i=2
Recursive Functions
⚫Recursion in programming is a technique
for defining a problem in terms of one
or more smaller versions of the
problem.

⚫A recursive function is one that calls


itself directly or indirectly to solve a
smaller version of its task until a final call
which does not require a self call.
#include<stdio.h>
Void print_backward();
Main()
{
Printf(“Enter a character (‘.’) to end”);
Print_backward();
}
Void print_backward()
{
Char ch;
Scanf(“%c”,&ch);
If(ch != ‘.’)
{
Print_backward();
Printf(“%c”, ch);
}
}
i/p : hi o/p: ih
The mechanics of recursive call
⚫Start main program
⚫…..
⚫1 call to print backward
st

⚫ enter a char : H
● 2nd call to print_backward
● enter a char: i.
● 3rd call to print_backward
● enter a char: .
● //now it will not call againcoz its ‘.’

● 3rd call finish


● print i.
● 2nd call finish
● Print H.
First call Finish…

End of main program………
How recursion is implemented
⚫ The storage mechanism in most modern
languages is stack storage mgmt.
⚫ In this mechanism the program’s data area is
allocated at load time.
⚫ While storage for functions data is allocated
when function is invoked.
⚫ On exit from function this storage is de-
allocated.
⚫ This results in a runtime stack.
⚫ In recursive cases one call does not overlap with
the other.
What is need for implementing
recursion

⚫Decomposition into smaller problems of


same size.
⚫Recursive call must diminish problem
size.
⚫Necessity of base case.
⚫Base case must be reached.
What is a base case.
⚫An instance of a problem solution of
which requires no further recursive
calls is known as base case.
⚫It is special case whose solution is
known.
⚫Every recursive algo requires at least
one base case in order to be valid.
The purpose of base case
⚫Itterminates the condition. Without an
explicitly defined base case, a recursive
function would call itself indefinitely.
Program to find factorial of a
number using recursive function.

#include<stdio.h>
long int factorial(int no);
int main()
{
int i;
printf(“enter number”);
scanf(“%d”,&i);
printf(“factorial of %d is %ld”, I, factorial(i));
}
Long int factorial(int n)
{ Factorial=5
5*4*3*2*1
if(n==0) 5*factorial(4)
Return 1; 5*4*fact(3)
5*4*3*…..
else
Return (n * factorial(n-1));
}

I/P: 3
o/p: 6
⚫ N->3
⚫ 3==0 false
⚫ Ans = 3* factorial (3-1)//2
⚫ n=2;
⚫ 2==0 false
⚫ Ans=2*factorial(2-1)//1
⚫ n=1
⚫ 1==0 false
⚫ Ans =1 * factorial (1-1)//0
⚫ n=0;
⚫ 0==0 true…
⚫ return 1;
⚫ Ans=1*1
⚫ Return 1;
⚫ Ans=2*1;
⚫ Return 2;
⚫ Ans=3*2;
⚫ Return 6.
Comparing recursion and iteration

⚫Recursion is like top-down approach to


problem solving.
⚫Iteration is more bottom up approach
⚫Recursion can require substantial
amount of overhead.
Structure
⚫Collection of different type data
⚫User defined data type
Syntax:
Struct student
{
Int roll;
Char name[20];
Char address[20];
Float avg;
Struct student:array of stucture
Struct student
{
Int roll;
Char name[20];
Char address[20];
Float avg;
}s[10];// s[0]=memory allocation:2+20+20+4=46bytes for one array element
//total 460 bytes for 10 elements
Int main()
{
Int I;
For(i=0;i<10;i++){
Scanf(“%d%s%s%f”,&s[i].roll,s[i].name,s[i].address,&s[i].avg);
}
For(i=0;i<10;i++){
printf(“%d%s%s%f”,s[i].roll,[i]s.name,s[i].address,s[i].avg);}
// structure variable.(dot operator)structure element name;

}
Union student:
union student
{
Int roll;
Char name[20];
Char address[20];
Float avg;
}s; // structure memory for s= 2+20+20+4
//union memory for s=memory allocated by the variable which takes maximum size
//s=20bytes
Int main()
{
Scanf(“%d%s%s%f”,&s.roll,s.name,s.address,&s.avg);
}
printf(“%d%s%s%f”,s.roll,.name,s.address,s.avg);
// structure variable.(dot operator)structure element name;
}
⚫WACP to input student name, roll no,
subject names of SE sem I and display.
Thank You

You might also like