SlideShare a Scribd company logo
Pointers In Real Life
Peter Thedens and Landon Woerdeman
Problem
A professor has an unsorted text file containing student “netid”s and scores.
The professor wants the data to be ordered both alphabetically and by score.
Additionally, the professor wants to know the top scorer(s) and the mean and median
score.
Goal of program
● Read a file containing students’ grades
● Sort grades by username and score (and output)
● Find top scoring student(s) (and output)
● Compute mean and median (and output)
grades.txt
nportman, 83
thanks, 73
mdamon, 100
sstallone, 67
bpitt, 83
ajolie, 75
tcruise, 75
jfranco, 30
jdepp, 82
ldicaprio, 95
jlawrence, 97
sjohansson, 88
mkunis, 93
dwashington, 78
cbale, 47
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Read User input
● Command line arguments
○ Consists of an array of C-strings (argv) and a number (argc)
○ argc – Number of strings
○ argv – C-strings contain each command line argument
○ Note: argv[0] contains the name of the program
● fopen() for reading from file
○ Takes a file path and returns a file pointer
○ Returns NULL if file does not exist
○ “r” specifies read operation
Grades structure
● Using structs, we can create a grade
● More on structs here
○ Access members with ‘.’
○ grade1.score returns the user’s score
● Basically a holder containing:
○ int score - integer containing student’s score
○ char* netid - C-string containing netid
■ Character pointer
■ Holds the address of the first character in the string
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Read and parse data loop
while(not end of file)
Get line of input
Parse line of input
Add initial loop
● Initially don’t know number of entries
● Can’t allocate correct space
● To fix, iterate twice
○ Loop 1: Count entries
○ Allocate space using malloc()
○ Loop 2: Parse entries
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Counting lines of file
● We will use getLine() to read file
● This returns -1 when end of file is reached
● Increment counter until -1 is returned
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Memory allocation
● Use malloc() to reserve space for array of grades
● Discussed under advanced topics here
● Does 2 things
○ Reserves desired amount of memory
○ Returns pointer to that memory
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Read line of input
● Call getLine() (described here)
○ Pass file pointer, character pointer (for string), and size pointer
○ Updates passed character pointer to read string
○ Updates size pointer to size of string (disregarded)
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Parsing
● Parse string
● First part: netid
○ Use strsep() to separate the string based on the comma
○ Described here
○ Assign to grades[i].netid a character pointer to the string (returned by strsep())
○ For our use, the pointer must be set to NULL before getting the line
● Second part: score
○ Use atoi() (described here) to parse an integer from a string
○ Assign to grades[i].score the score of element of the array grades
Parsing code snippet
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Sort data
● We will use a selection sort (described here)
○ Search through the unsorted part of array
○ Find minimum element and swap with first element
■ Using pointers to swap is described here
○ Decrease size of unsorted part of array
● To sort netids, we will use strcmp() to identify smallest element
○ If the return value of strcmp() is negative, first parameter is smaller
○ If the return value of strcmp() is positive, second parameter is smaller
○ strcmp() is described here
● To sort scores, we will use ‘<’ to identify smallest element
Sorting code snippet
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Calculations
● Median
○ Use sorted-by-score array
○ If number of scores is odd, use middle element
○ If number of scores is even, use average of middle 2 elements
● Mean
○ Add up total of scores in array and divide by number of elements
● Top scorer(s)
○ Find highest score (end of sorted array)
○ Iterate backwards until score is less than highest
○ From this index to the end are the top scorers
Calculations code snippet
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Output file
● At each step, the output file is being created
○ After each sort and calculations print
○ fprintf() is described here
○ Is like printf to a file rather than the console
● File pointer is closed at termination of program
○ fclose() writes the file
Output code snippet
Example output
Why are pointers needed?
● File pointer
● Dynamic memory allocation
● Swap function
For more on pointers: http://cpointers.weebly.com

More Related Content

What's hot

Strongly Connected Components
Strongly Connected Components Strongly Connected Components
Strongly Connected Components
Md. Shafiuzzaman Hira
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing concepts
LJ Projects
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
Tech_MX
 
2.5 dfs & bfs
2.5 dfs & bfs2.5 dfs & bfs
2.5 dfs & bfs
Krish_ver2
 
Predicates and Quantifiers
Predicates and QuantifiersPredicates and Quantifiers
Predicates and Quantifiers
blaircomp2003
 
Channel coding
Channel codingChannel coding
Channel coding
Piyush Mittal
 
Np cooks theorem
Np cooks theoremNp cooks theorem
Np cooks theorem
Narayana Galla
 
NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar
Hemantha Kulathilake
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree
Divya Ks
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
Mohammed Hussein
 
4.4 hashing
4.4 hashing4.4 hashing
4.4 hashing
Krish_ver2
 
Shortest path algorithms
Shortest path algorithmsShortest path algorithms
Shortest path algorithms
Amit Kumar Rathi
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
ramya marichamy
 
PUBLIC KEY ENCRYPTION
PUBLIC KEY ENCRYPTIONPUBLIC KEY ENCRYPTION
PUBLIC KEY ENCRYPTION
raf_slide
 
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
Akshaya Arunan
 
Bottom - Up Parsing
Bottom - Up ParsingBottom - Up Parsing
Bottom - Up Parsing
kunj desai
 
Discrete-Chapter 10 Trees
Discrete-Chapter 10 TreesDiscrete-Chapter 10 Trees
Discrete-Chapter 10 Trees
Wongyos Keardsri
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
Krish_ver2
 
Graph Theory: Trees
Graph Theory: TreesGraph Theory: Trees
Graph Theory: Trees
Ashikur Rahman
 
Data Structure and Algorithms Hashing
Data Structure and Algorithms HashingData Structure and Algorithms Hashing
Data Structure and Algorithms Hashing
ManishPrajapati78
 

What's hot (20)

Strongly Connected Components
Strongly Connected Components Strongly Connected Components
Strongly Connected Components
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing concepts
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
2.5 dfs & bfs
2.5 dfs & bfs2.5 dfs & bfs
2.5 dfs & bfs
 
Predicates and Quantifiers
Predicates and QuantifiersPredicates and Quantifiers
Predicates and Quantifiers
 
Channel coding
Channel codingChannel coding
Channel coding
 
Np cooks theorem
Np cooks theoremNp cooks theorem
Np cooks theorem
 
NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
4.4 hashing
4.4 hashing4.4 hashing
4.4 hashing
 
Shortest path algorithms
Shortest path algorithmsShortest path algorithms
Shortest path algorithms
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
PUBLIC KEY ENCRYPTION
PUBLIC KEY ENCRYPTIONPUBLIC KEY ENCRYPTION
PUBLIC KEY ENCRYPTION
 
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
 
Bottom - Up Parsing
Bottom - Up ParsingBottom - Up Parsing
Bottom - Up Parsing
 
Discrete-Chapter 10 Trees
Discrete-Chapter 10 TreesDiscrete-Chapter 10 Trees
Discrete-Chapter 10 Trees
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
Graph Theory: Trees
Graph Theory: TreesGraph Theory: Trees
Graph Theory: Trees
 
Data Structure and Algorithms Hashing
Data Structure and Algorithms HashingData Structure and Algorithms Hashing
Data Structure and Algorithms Hashing
 

Similar to Pointers in real life

Algorithms.
Algorithms. Algorithms.
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Julie Iskander
 
Algorithm By AMT.pptx
Algorithm By AMT.pptxAlgorithm By AMT.pptx
Algorithm By AMT.pptx
AungMyintTun3
 
Tri Merge Sorting Algorithm
Tri Merge Sorting AlgorithmTri Merge Sorting Algorithm
Tri Merge Sorting Algorithm
Ashim Sikder
 
CS3114_09212011.ppt
CS3114_09212011.pptCS3114_09212011.ppt
CS3114_09212011.ppt
Arumugam90
 
Python bible
Python biblePython bible
Python bible
adarsh j
 
Cis435 week04
Cis435 week04Cis435 week04
Cis435 week04
ashish bansal
 
Cis435 week06
Cis435 week06Cis435 week06
Cis435 week06
ashish bansal
 
R programming slides
R  programming slidesR  programming slides
R programming slides
Pankaj Saini
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
ambikavenkatesh2
 
DSA
DSADSA
DSA
rrupa2
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
Dr.Umadevi V
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
Afaq Mansoor Khan
 
Unit7
Unit7Unit7
Unit7
chempa
 
Data structure
Data structureData structure
Data structure
Muhammad Farhan
 
ds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.pptds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.ppt
AlliVinay1
 
DAA Slides for Multiple topics such as different algorithms
DAA Slides for Multiple topics such as different algorithmsDAA Slides for Multiple topics such as different algorithms
DAA Slides for Multiple topics such as different algorithms
DEVARSHHIRENBHAIPARM
 
Data structure Unit-I Part A
Data structure Unit-I Part AData structure Unit-I Part A
Data structure Unit-I Part A
SSN College of Engineering, Kalavakkam
 
Iare ds ppt_3
Iare ds ppt_3Iare ds ppt_3
Iare ds ppt_3
AlugatiRajitha
 
jn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdfjn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdf
VinayNassa3
 

Similar to Pointers in real life (20)

Algorithms.
Algorithms. Algorithms.
Algorithms.
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Algorithm By AMT.pptx
Algorithm By AMT.pptxAlgorithm By AMT.pptx
Algorithm By AMT.pptx
 
Tri Merge Sorting Algorithm
Tri Merge Sorting AlgorithmTri Merge Sorting Algorithm
Tri Merge Sorting Algorithm
 
CS3114_09212011.ppt
CS3114_09212011.pptCS3114_09212011.ppt
CS3114_09212011.ppt
 
Python bible
Python biblePython bible
Python bible
 
Cis435 week04
Cis435 week04Cis435 week04
Cis435 week04
 
Cis435 week06
Cis435 week06Cis435 week06
Cis435 week06
 
R programming slides
R  programming slidesR  programming slides
R programming slides
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
DSA
DSADSA
DSA
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 
Unit7
Unit7Unit7
Unit7
 
Data structure
Data structureData structure
Data structure
 
ds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.pptds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.ppt
 
DAA Slides for Multiple topics such as different algorithms
DAA Slides for Multiple topics such as different algorithmsDAA Slides for Multiple topics such as different algorithms
DAA Slides for Multiple topics such as different algorithms
 
Data structure Unit-I Part A
Data structure Unit-I Part AData structure Unit-I Part A
Data structure Unit-I Part A
 
Iare ds ppt_3
Iare ds ppt_3Iare ds ppt_3
Iare ds ppt_3
 
jn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdfjn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdf
 

Recently uploaded

BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 

Recently uploaded (20)

BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 

Pointers in real life

  • 1. Pointers In Real Life Peter Thedens and Landon Woerdeman
  • 2. Problem A professor has an unsorted text file containing student “netid”s and scores. The professor wants the data to be ordered both alphabetically and by score. Additionally, the professor wants to know the top scorer(s) and the mean and median score.
  • 3. Goal of program ● Read a file containing students’ grades ● Sort grades by username and score (and output) ● Find top scoring student(s) (and output) ● Compute mean and median (and output)
  • 4. grades.txt nportman, 83 thanks, 73 mdamon, 100 sstallone, 67 bpitt, 83 ajolie, 75 tcruise, 75 jfranco, 30 jdepp, 82 ldicaprio, 95 jlawrence, 97 sjohansson, 88 mkunis, 93 dwashington, 78 cbale, 47
  • 5. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 6. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 7. Read User input ● Command line arguments ○ Consists of an array of C-strings (argv) and a number (argc) ○ argc – Number of strings ○ argv – C-strings contain each command line argument ○ Note: argv[0] contains the name of the program ● fopen() for reading from file ○ Takes a file path and returns a file pointer ○ Returns NULL if file does not exist ○ “r” specifies read operation
  • 8. Grades structure ● Using structs, we can create a grade ● More on structs here ○ Access members with ‘.’ ○ grade1.score returns the user’s score ● Basically a holder containing: ○ int score - integer containing student’s score ○ char* netid - C-string containing netid ■ Character pointer ■ Holds the address of the first character in the string
  • 9. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 10. Read and parse data loop while(not end of file) Get line of input Parse line of input
  • 11. Add initial loop ● Initially don’t know number of entries ● Can’t allocate correct space ● To fix, iterate twice ○ Loop 1: Count entries ○ Allocate space using malloc() ○ Loop 2: Parse entries
  • 12. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 13. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 14. Counting lines of file ● We will use getLine() to read file ● This returns -1 when end of file is reached ● Increment counter until -1 is returned
  • 15. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 16. Memory allocation ● Use malloc() to reserve space for array of grades ● Discussed under advanced topics here ● Does 2 things ○ Reserves desired amount of memory ○ Returns pointer to that memory
  • 17. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 18. Read line of input ● Call getLine() (described here) ○ Pass file pointer, character pointer (for string), and size pointer ○ Updates passed character pointer to read string ○ Updates size pointer to size of string (disregarded)
  • 19. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 20. Parsing ● Parse string ● First part: netid ○ Use strsep() to separate the string based on the comma ○ Described here ○ Assign to grades[i].netid a character pointer to the string (returned by strsep()) ○ For our use, the pointer must be set to NULL before getting the line ● Second part: score ○ Use atoi() (described here) to parse an integer from a string ○ Assign to grades[i].score the score of element of the array grades
  • 22. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 23. Sort data ● We will use a selection sort (described here) ○ Search through the unsorted part of array ○ Find minimum element and swap with first element ■ Using pointers to swap is described here ○ Decrease size of unsorted part of array ● To sort netids, we will use strcmp() to identify smallest element ○ If the return value of strcmp() is negative, first parameter is smaller ○ If the return value of strcmp() is positive, second parameter is smaller ○ strcmp() is described here ● To sort scores, we will use ‘<’ to identify smallest element
  • 25. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 26. Calculations ● Median ○ Use sorted-by-score array ○ If number of scores is odd, use middle element ○ If number of scores is even, use average of middle 2 elements ● Mean ○ Add up total of scores in array and divide by number of elements ● Top scorer(s) ○ Find highest score (end of sorted array) ○ Iterate backwards until score is less than highest ○ From this index to the end are the top scorers
  • 28. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 29. Output file ● At each step, the output file is being created ○ After each sort and calculations print ○ fprintf() is described here ○ Is like printf to a file rather than the console ● File pointer is closed at termination of program ○ fclose() writes the file
  • 32. Why are pointers needed? ● File pointer ● Dynamic memory allocation ● Swap function For more on pointers: http://cpointers.weebly.com