Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Module4-Notes

Uploaded by

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

Module4-Notes

Uploaded by

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

cProgramming|Mumbai

University -Sem 1
Arrays, Strings and Structures
W4.3 STRUCTURES

concept of Structures
A:structure is a collection of
1.
data of different
2. The main difference between a structure and andatatypesis
datatype. array, that in an array, all the data has to be of the same
3. Many a times, we need to
combine
attributes may not be of the same dataseveral attributes of an obiect. together into a data
type. structure. These
A Eg: Let us look at the
attributes of a student
student
1. Name
character array
2. Age ... integer
3. Percentage ... float

As seen above, this is a collection of data of different data types. Here we use a
structure.
1. We can also combine a set of structures into an array.

For example, the above structure is for a student. We can make an array containing 100 such structures.
This is now representing data for a whole class of students.

2. Structures provide flexibility and upgradability to our program.


just has three data members:
Consider the above example of a class of students. As of now, each student
mobile number for each student, we just need to
Name, Age, Percentage. But in future, if we want to add
student. It will automatically be includedas a property for
add a fourth attribute in the main structure of a upgradability to our
This provides great flexibility and
each student, without disturbing the existing code.
program.

a Structure
Declaration and Initializations of instances of this
have 3 members: ame, age, percentage. Make 3
structure. It must table.
Let us create a "student" values and display them in a
structure by the names s1, s2, and s3. Read inputs for all
ArrayS, Strings an
CProgramming| Mumbai University- Sem 1
structure in the manner below
1) First, we create a
struct
This is the keyword that creates a structure
struct student
student
This is the name of the structure
It is one ofthe mermbers of this structure
name
char name[100]; Data type: character array
int age, tis one of the menmbersof this structure
age
float percentage, Data type: int
It isone of the members of this structurs
percentage
Data type: float

instances of this structure in the manner beiow


2) We creste three

S1, s2, s3 Three instances of the structure "student"


struct student s1,s2,s3 Simply speaking three students

structures just like variabies, as shown


3) We can now access the membersof these

s1.nane nameof student s1


s2.age (ageof student s2
s3.percentage ipercentage of student s3... and so on.

biock:
Aternate method of declaringthis same structure and its 3 instances s1, s2, s3 in the same

struct student Notice, how s1, s2, s3 are defined just as the structure
"student" is being created.
char namef100]; Everything else is the same.
meth.
int age; Although not very popular, some programmers use this
fioat percentage;
}s1,82, 83;

Page:
4-28

Tech-Neo Publications | Bharat Acharya


PrOgramming
| Mumbai University
-Sem1
Arrays, Strings and Structures
program to
. Write a store informnation of 10
student. students usina a Structure,
RollNo, Name and Marks of the
Information should incluae
A solution:

tinclude<stdio.h>
struct student
C{ Bharat Acharya
int rollno,; Dec 22- Structures
char name [100]:
float marks; Roll No
Name Bharat
int main (void) Marks 94

Ro11 No
int i, count=i0; Name Tim
struct student list[101: Marks 97
printf("C | Bharat Acharya\n"}:
printf {" Roll No |3
-\n"): Nane
printf (" Dec 22 - Structures\n\n") Vinita
for (i = 0; i < count; it+) Marks 56

print£ ("Roll No The abOve inputs ae rereatec for


scanf (" %d", $list[i] .rollno): all 10 studentS in a looo...
print£("Name "):
scanf ("s", list [i].name)
printf ("Marks
scanf("£", &1istil.marks) Roll No 10
printf ("\n"); Name Sukhmeet
Marks
printf{"\n);
printf {"-
print£{"Roll No Name Marks\n"): Rotl No Nane Marks
-\n"}
printf (" 94.00
Eor (i = 0; i < count; it+)
Bharat
97.00
Vìnita S6.00
printf ("$4d ", list[i].rollno) ; Sumangalà 98.00
Print£("%-15s", list [i). name); Daisy 78.00
print£ ("$6.2£\n", list [i] .marks) ; Prerna 89.0
Deepak 3.00
printf ("-- Bhaskar 78.00
Sonali 86.00
printf ("\n\n"); 10 Sukhmeet 75.00
return 0;

C| Bharat Acharya

Page: 4-31

Tech-Neo Publications | Bharat Acharya


CProgramming| Mumbai University-Sem1
Arrays,
>Q: Write a program to store and display the name, roll no and fees of 100
students
V Solution: Same as above, just change marks to fees!
usSIng2
>Q: Write a programto read Title, Author and Price of 5books using an array of
records in ascendinggorder of price.
V Solution: structures.
1. Wewill create astructure "book" and make an array "list[b]" to
store 5 records
2. We will then sort them using a function "sort".
3. We will use bubble sort algorithmto sort the records on the basis of
price in
4. The screens are
shown here
5. The program is on the next
page
ascendingor
C Bharat Acharya
Jun 22- Structùres
Tìtle 8086
Author Bharat
Price 560
Title 8086
Author
Price Acharya
620

Title COA
Author
Price BharatAcharya
499
Title CG
Author Bnarat
Price 528
Title DSA
Author
Price Acharya
555

Title
Author
COA Price
CG
DSA BharatAcharya
Bharat 499.00
520.09
8986 Acharya
Bharat 555.00
8086 560.00
Acharya 620.00

Bharat Acharya:

Tech-Neo Publications | Bharat


Acharya Page: 4-32
ngraming
| Mumbai University- Sem 1
Arrays, Strings and Structures
ciude<stodio.
h>
seruCt
boot

1/ book is a structure
char title[100]:
chat author[100]; | | title - char array
ioatprice; | a0thor - char aray

:ntmain(void)

count$:
int i, jr
struct book list[5]:
struct book tep; 1 array of 5 books
printf(C Bharat Acharya\n"); I| tor svapping
printf(nm -n"):
printf("Jun 22 - Structures\n\n"):
for i
(i0 ; i < count; i++}
1/ input the data
printf{Titie |");
scanf ("$s", list [i]. title) ;
printf ("Author | "}:
scanf ("s", list [ii. author):
printf {"Price "
scanf ("$f", &list{il.price);
printf {"\n"):

0; i < count-l; it+) I bubble sort


for (i

for (j = 0; j < count-1 j++)


if (list[j]price>listIj+1] price) 1 copare prices

# ten
temp list[jJ
list ij list[j+1l
list(+1] temp

printf{"\n")
printf {"-m Price\n")
Author --\n")
printf{"Títle
printf (" #display the books
Lor (1 0; i < count; i++}
[i).title) i
Printf {"$-15s", 11st
list [i).author) i
Printf("%-15g",
list [il-price) i
PIintf ("%8.2£n", \n"):

printf (
printf ("\n\n")
return 0; I/cI Bharat Acharya
CProgramming | Mumbai University-Sem 1 Arrays,, Strings

members Employee No.


> Q: Write a program to design a structure Employee withemployees and display 10
Experience and salary. Read the information of 100 Ernpi y
that is having 5 years or more experience and
salary less than Rs. 10,000. employee inltr
V Solution :

G| Bharat Acharya
For the sake of showing
the output here, I have Jun 23.- Structures
run the program with a
count of 4. No
Name Bharat
In the exam the count Experience 7.
Salary. 8000
would be 10 as per the
question
No | 2
Name Acharya
Experience 8
Salary 8500

No 3
Name Tim
Experience 9
Salary 12000

No 4
Name John
Experience
Salary 6000

No Name Experiehce

Bharat 8800.00
2 Acharya 8500.00

Page:4-34

Tech-Neo Publications | Bharat Acharya


nclude<sttalo.h>
ptructemp loyee Arrays, Strings and
Structures
int no:
Ahar name [1001:
int experience:
E1oat salary;

int main(void)

nt i, Count=4;
struct employee listI1001:
printfE("C
printf("
Bharat Acharya\n");
print f (("Jun 23-
for (i Structures\n\n")
0; i < count i )

printf "NO
Scanf("%d &list [il no)
printf ("Nane
Scanf S ist l name)
print(EXperience
scanf "a&iist lil experience)
printfSalary
scanf f &list I salary);
print £ ("\n")

printf\n)
printf l
Experience Salary\n")i
printf # NO Name
-\n"):
printf (
for (i 0 i count it +)
[il.salary<10000))
((1ist [il experiences=5) &&(1ist
if

Print£("83d " 1ist [i].no):


print£ ("%-15s, list[1].name)
1ist [i].experience):
printf£ ("54
list [i] .salary):
Printf ("%8.2£\n",
\n")

print f( - -
printf ("\n\n")
return 0 Page: 4-35

Bharat Acharya
Tech-Neo Publications |
Module 5

sem , Mumbaj Pointers


Syllabus
5.1
Pointers: Introduction, Definition, Uses of Pointers, Address
Dereferencing a pointer, Void Pointer, Pointer operator, Pointer variables.
Arithmetic, Pointers to Pointers, Pointers and Array.

5.1 POINTERS

>Note from Bharat Acharya


Pointers are one of the MosT POWERFUL tools of Cprogramming, Fun fact..Ironicaly Mumbai University has
not asked a SINGLE question in the past FOUR theory exams (Jun 22, Dec 22,Jun 23, Dec 23) from this topic
although it is a whole MODULE in our syllabus. Maybe they believe that students are just not capable of
understanding pointers so why even include this in the exam. It's not surprising that every year during
lacements, the IT industry says 70% engineering students are UN-EMPLOYABLE'". They have adegree but
have little knowledge. If universities over-simplify exams and exclude some of the most fascinating topics, just
students for the current scenario. Let's
to maintain ahigh passing percentage, then it isn't right to blame
instead, for the sake of KNOWLEDGE. There
prove them wrong anddo this one topic, not just for the exam, governed by
are no exam questions in this chapter! Yet we will
learn it because our scope of knowledge isn't
aspects of pointers and enjoy learning them with real wortd
just what comes in the exam. Let's explore the key don't know
EVERYWHERE. You are not a complete programmer if you
examples because pointers are used
how to use pointers... honestly!
pointers, Declaration and Initialization and Dereferencing of
à 5.1.1 Fundamentals of
pointers
Apointer is avariable.
data.
" A normal variablesimply holds pointer.
holds the address of another variable.Hence the name
Apointer
Consider this example:
int,with value "25"
"a" is a variable of type
variable "ptra.
We create apointer
toa" by writing ptra =&a
We make "ptra" point
pointer
This iscalled referencing the mean &a that means
address of a.
write "ptra" we a" that is 25",
ATter this, whenever
we
pointed by ptra,means data of
address
write *ptra we mean the data of the
ITwe
dereferencing a polnter.
This is called
Unlve/s
| Mumbai
C Programming
address say 2000, with
memory at some
int a- 25:// create a
VATiable a in the
Creates of a
Decl arati on pointer
value |
int ptra: now ptra - 2000 (addresg of
Ini tinlisation thakes ptra Doint to "a".
D t r a - &A
accaseing the da ta (25) pointed by
a
DIintf "* *ptra
/ Dereferencing this pointer
#includeestaio. hs
int main (void)
CI Bharat Acharya
int a 5:
Pointers
int *ptra;
ptra a;
25
print f ("C Bharat Acharya\n");
printf (" --\n"):
Bharat Acharya:
printf ("Pointers\n\n") ;
printi ("$" *ptra):
printf ("\n\n");
return 0;

The same initialisation could be also done as:

int a = 25;
int *ptra &a; I/ Declare and Initialise the pointer in the same
statement

Similarly, int *ptra


can alsO vewritten as int* ptra
can alsO ve written as int * ptra

One very important point to note is that the


data type of the pointer must be exactly
of the variable to which this
pointer is pointing. This is essential for the same as the data ype
understanding pointer arithmetic.
int a = 25;
int "ptre= &a;

float b =2.5;
float "ptrb =&b;

char c='z';
char *ptrc =&c;

Allthe above are valid


examples.
Tech-Neo Publlcations | Bharat
Acharya Page:5-2
AOTOmmlng
|Mumbai UhIversitySem 1
Pointers

clude<Stdio,b
main
(void)

int a 25g

int *pptra
float b 25 CI Bharat Ácharya
s108t *ptrb &b;
char c z Pointers
char *ptrc &C
printf("C Bharat Acharya\n")i 25
Drintf("
printf("Pointers\n\n"):
-\n"): 25.000000
print£( ngd\n", *ptra)
orint£("E\nn,*ptrb)
printf ("%c\n" *ptrc): Bharat Acharya:
printf ("\n");
return 0;

5.1.2 Void Pointer


can declare
object for which you wish to create a pointer, you
When you are not sure of thedata type of the afloat pointer
createdto point to an int data type variable, and
it as a void pointer. Just likean int pointer is without an
float variable, avoid pointer is created to point to a memory address
is created to point to a
inherent data type. pointer. However, before
hold the address of any data type, making it a generic
Avoid* pointer can
to the appropriate datatype.
dereferencing a void * pointer, youmust cast it
Example
clude<stdio.h> C Bharat Acharya
main (void) Pointers | Void Pointer
int a = 10;
Eloat b = 3.14; b: 3.14
char c =A; C: A
voiê *ptri Bharat Acharya:
printf ("C Bharat Acharya\n") --\n")i
printf("-- Void
Pointer\n\n");
int
print£E("Pointers
ptr = &ai
/ / Pointing to
//type casting:
print£ &bi %d\n", * (int *)ptr) i // Pointing to
float
ptr = (a: *)ptr)} // type castiQ: (tloat *)
char
%.2£\n", * (£loat / / Point ing to
print£("b:
ptr = &Ci / / type casting: (char *)
*)ptr) ;
print£( ("c: sc\n"
printf ("\n")i
* (char

Teturrn 0;
Page: 5-3
Acharya
University- Sem1
C Programming IMumbai

Arrays
using a Pointers and
a 5.1.3 Pointer
Arithmetic
array
method of accessing an
PointersS provide an efficient
powerful data structures like linkedlists, trees etc(We
vou cAn create Structures), pointers can
also be a
useful tool
Although using pointers Data
semester in thesubject called
Intensely next
llst"
arrays.
array of integers by the name
Suppose we create an
to this array by the name "ptrlist".
We create a pointer element of list.
have the address of the first
Now ptrlist will this list.
should point to the next element of
As we do ptrlist++, it
understand!
Now this is very important to
by 1 always.
ptrlist++ will not increment ptrlist
SIZE OF THE datatype
IT WILL INCREEMENT by the
That means 4 bytes.
An int is 32 bits (modern systems).
LOCATION HOLDS 1BYTE
Inthe memory 1 MEMORY
memory locations
That means an int is spread across 4
Assume our array begins at address2000
2000, 2001, 2003, 2003.
The first integer is stored in locations
The next integer is in 2004.
ptrlist originally is 2000
ptrlist++ will INCREMENT it by 4.
Nowptrlist will be 2004.
" That is how ptrlist willpoint to the next int inthe array.

Now suppose this was a char array


Then ptrlist++ will increment it by 1
That is because a char is of 1 byte
That is how ptrlist will point to the next char in the array.

Now suppose this was a double-float array


Then ptrlist++ willincrement itby 8
That is because a double is of8bytes
That is how ptrlist will point to the nextdouble in the array.

This iscalled POINTER ARITHMETIC.


Hence it is important to specify the correct data type of the pointer.

Page:b
Tech-Neo Publications | Bharat Acharya
cProgramming| Mumbai
University -Sem 1
Pointers
Integerarray {incrementtby 4}
intlist/5):
"ptrlist: list; // note that it
int is an array so "&° is not
needed
ptrlist++
2000Int[0]
2001
int|0]
ptrlist++
2002int|int(0]0]
2003
2004
int[]
2005 int(1)
2006 int[1]
2007 int[1]

Char array (increment by 1}


char list[5];
char *ptrlist = list: |/note that it is an
array so "&" is not needed
ptrlist++ 2000 char[0]
ptrlist++ 2001 char[]
ptrlist++ 2002 char[2]
ptrlist++ 2003 char[3]

Double array {increment by 8}


double list[5];
double *ptrlist = list; |/note that it is an arrayso "&" is not
needed
ptrlist++ 2000 double[o]
2001 double[0]
2002 double<0]
2003 double[0]
2004 double[0]
2005 double[0]
2006 double[0]
2007 double[0)
ptrlist++ 2008 double[1]
2009 double[1]

Tech-Neo Publications | Bharat Acharya Page: 5-5


CProgramming | Mumbai University - Sem1

A 5.1.4 Pointer to a Pointer (Double Pointer)


that points to another pointer. This allows
In Cprogramming, adouble pointer is simply a pointer
levels of indirection, which can be useful in various
such as
scenarios, dynamic memory allocation.
multi-dimensionalarrays etc.Yes, these topics are way
pointers within functions, and working with
understand the use of a double
SCOpe of your syllabus this semester, yet you can pointer
programming example given below.

#include <stdio.h>
int main()

int a = 10, b = 20;


int *ptr &a;
int **ptrptr &ptri
printf ("C | Bharat Acharya\n")
printf ("-- -\n")
printf("Pointe to a Pointer\n\n")
printE ("Given values of a and b \n")
printf ("a dn" al
printf ("b
print£ ("Accessing a using ptr and *ptrptr\n")7
printf("*ptr
printf ("**ptrptr
8dnptri
tdln n **ptrptr)
printf("Accessing b uging *ptr andptrptr \n")i
*ptrptr = &b;
printf ("*ptr dnptr
printf (u**ptrptran\n ptrptr)
return 0;
C| Bharat Acharya
Explanation
Originally ptr was pointing to a Pointer to a Pointer
and ptrptr was pointing to ptr and hernce indirectly to a Gìven values of a and b
We displayed the dereferenced values of 10
*ptr and **ptrptr and both gave the value of athat is 10. 20

Accessing a using *ptr and


Then we manipulated ptrptr to directly point to the *ptr
address of b. **ptrptr 10
This indirectly redirected ptr to also point to b,
Accessing b using *ptr and ptD
*ptr | 20
Finally, we displayed the dereferenced values of **ptrptr |20
*ptr and **ptrptr and both gave the value of b that is 20,
Bharat Acharya:
C| Bharat Acharya, Tech-Neo Publications

Tech-Neo Publications | Bharat Acharya Page:5-6


cPrograrmming|| Mumbai
University - Sem 1 Pointers

5.1.5 Uses of Pointers


Dainters are used incall by reference. Here
the address of the data. This is instead of passingthe actualdata as a
This has tremendous parameter, wo P
especially useful when the data is alarge data structure
real-world like an array.
printer queue etc. applications such as adding songs to a playlist, adding
iheso
Dointers are used to create dynamic data
to create dynamic data such as structures like linked lists, trees etc. inked lists are used
social media feed (Instagram reels,
threads etc. Facebook etc) or commei
Pointers are used for dynamic mnemory allocation. This is Useful to
composing a text message or clicking apicture on your phone etc.create mernory on dernand suGn a
anch in this semester you don't learn linked lists and trees, in
higher semesters, they will be themain-$tay
ofsubjects like Data Structures, Operating Systemsetc.

5.1.6 Concept of Dynamic Memory Allocation


Most modern operating Systems use dynamic memory allocation for all theirtasks. This means memory is not
nre-reserved for any specitic application. It is allottedON DEMAND. Whenever we do an operation that needs
memory from the OS,Our application (example canmera app)demands memory dynamically. This memory is
allocated using a pointer. This is where our picture that we have just taken, gets stored. Similarly, when we
delete a memory object like a picture or a song etc, the memory that was allocated is made freeand is given
hack tothe OS so that it can allocate it to any other task in the future. This isagain done using pointers. To
allocate memory, we use the function malloc (or calloc) and to release the memory we use the function free.
Both use pointers.

>Example :
void *ptr = malloc(1000);
address into ptr. All those memory locations will
This will allocate amemory of 1000 bytes and give its starting
Contain garbage values as of now.

void *ptr =calloc(1000, sizeof(int));


starting
memory of 1000 integer values (means 4000 byes as 1int is 4 bytes) and give its
Inis will allocate a
memory locations will be initialised to ZERO.
2ddress into ptr. Note that allthese

freelptr); earlier allocated using any ofthe above tow


methods. This memory is now
This will free the memory that was demand. This is what happens when you
any other application on As you
available to the 0S and can be given to
want to store somethung else uke more images.
phone just because you
Lesome app from your that it can be allotted to the camera
free" and is given back tothe OS so like Computer Organisation
delete the app, Its memory becomes We will learn this in detail in subjects
app as you CliCk more and more pictures.
and Microprocessors.
next one!
Module ends... See you in the

Page: 5-7

Acharya
Tech-Ne0 Publications | Bharat

You might also like