Procedural Programming & Fundamentals of Programming

Similar documents
Procedural Programming

Procedural Programming

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming

C-Refresher: Session 10 Disk IO

File IO and command line input CSE 2451

Procedural Programming & Fundamentals of Programming

Introduction to file management

Engineering program development 7. Edited by Péter Vass

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

File I/O. Arash Rafiey. November 7, 2017

Standard C Library Functions

Functions. Systems Programming Concepts

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

Standard File Pointers

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

C programming basics T3-1 -

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

PESIT Bangalore South Campus Hosur road, 1km before ElectronicCity, Bengaluru -100 Department of Basic Science and Humanities

M.CS201 Programming language

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Programming Fundamentals

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Assignment 6. Q1. Create a database of students using structures, where in each entry of the database will have the following fields:

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Input/Output and the Operating Systems

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Fundamentals of Programming. Lecture 10 Hamed Rasifard

CSCI 171 Chapter Outlines

int marks[10]; // fixed size and fixed address No change in Memory address.

What is recursion. WAP to find sum of n natural numbers using recursion (5)

CP2 Revision. theme: file access and unix programs

SAE1A Programming in C. Unit : I - V

Assoc. Prof. Dr. Tansu FİLİK

Laboratory: USING FILES I. THEORETICAL ASPECTS

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Lecture 9: File Processing. Quazi Rahman

C mini reference. 5 Binary numbers 12

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Bangalore South Campus

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Scheme of valuations-test 3 PART 1

ECE551 Midterm Version 1

C Functions. 5.2 Program Modules in C

BİL200 TUTORIAL-EXERCISES Objective:

PROGRAMMAZIONE I A.A. 2017/2018

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

CE Lecture 11

EM108 Software Development for Engineers

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Programming Language A

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Programming Language B

Computer Programming Unit v

ECE551 Midterm Version 2

Organization of a file

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

CS240: Programming in C

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Data Files. Computer Basics

System Software Experiment 1 Lecture 7

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

C Basics And Concepts Input And Output

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

Model Solution for QP CODE : ( 3 Hours )

MODULE V: POINTERS & PREPROCESSORS

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Computer programming

High Performance Programming Programming in C part 1

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

The University of Calgary. ENCM 339 Programming Fundamentals Fall 2016

Input / Output Functions

LAB 7 FUNCTION PART 2

Solution for Data Structure

File Handling. Reference:

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

HIGH LEVEL FILE PROCESSING

The fopen command can open an external file in C language. If the file is exist, the file pointer is not NULL. Otherwise, the file pointer is NULL.

ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees. Introduction to Linked Lists

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

PRINCIPLES OF OPERATING SYSTEMS

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator

ANSI C Programming Simple Programs

C Review. SWE2004: Principles in Programming Spring 2014 Euiseong Seo

Lab # 4. Files & Queues in C

JTSK Programming in C II C-Lab II. Lecture 3 & 4

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Transcription:

& Fundamentals of Programming Exercise 4 (SS 2018) 12.06.2018 What will I learn in the 5. exercise Files Math functions Dynamic data structures (linked Lists) Exercise(s) 1

Files A file can be seen as resource for storing information. Is used by programs to store data on durable storage. A program is therefore able to open files in order to read/write data. Open a file in C FILE * fopen( const char * name, const char * mode ); file open returns a so called file handle which is later used as reference (argument of other functions). name is the name of the file (including directory). mode describes the file operation mode like read, write. Example: FILE *fp: //file handle fp = fopen( myfile.txt, w ); //myfile.txt is open for writing 2

File modes r (read): w (write): a (append): open a file for input operations. The file must exist. Create an empty file for output operation. Open file for output operation. Data is appended at the end of file. File is created if it not exists. r+ (read/update): Open a file for input/output operations. The file must exist. w+ (write/update): Create an empty file for input/output operation. If the file exists it is treated as new empty file. a+ (append/update):open file for update operation. Data is always appended at the end of the file. Reposition for input operations is possible. Read a character from file int fgetc(file *fp); fgetc returns the character currently pointed by the internal file position indicator of the specified file where fp refers to. The internal file position indicator is then advanced to the next character. fp is the file handle (pointer) Returns EOF if the end of file is reached. 3

Read a string from file char *fgets(char *string, int n, FILE *fp); fgets reads characters from file into string until (n-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. string Pointer to an array of char n is the maximum number of character which should be copied into string fp is the file handle (pointer) On success, the function returns string or NULL if no character is read (end of file) Write a character to file int fputc(int c, FILE *fp); fputc writes the character c to the file and advances the position indicator. The internal file position indicator is then advanced to the next character. c The int promotion of the character to be written. The value is internally converted to an unsigned char when written. fp is the file handle (pointer) Returns the written character on success or EOF if writing fails 4

Write a string to file int fputs(const char * string, FILE *fp); fputs writes the string pointed to by string to file. The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream. string Pointer to an array of char fp is the file handle (pointer) EOF and Close File int fclose( FILE *fp); fclose closes the file where fp refers to. EOF EOF is a constant and marks the end of file. Example: fp = fopen("example.txt", "r ) if(fp!=null) c = fgetc(fp); while ( (c = fgetc(fp))!= EOF) printf("%c", c); fclose(fp); 5

Task 13 A program should be created which reads in a file. The file contains a list of <string>;<int> lines like: Joachim Zumbraegel;281063 - A string has a maximum length of 50 characters - The number has a maximum of 6 digits Every line should be read in and separated into a string part and an integer part. The read values should then printed out in the following way: String[n]=<string> Int[n]=<int> Hint: (n is the line counter, starts with 1) - Task 14 Write a program which writes n datasets to an empty file named output.txt. One data set consists of: x (integer), y (integer), z (integer), r (float) The number (n) of data sets and the data set values are entered via console. At first the user is asked how many data sets he wants to enter (input of n). Afterwards he is asked to enter the values for the n data sets. The data sets should be written (line by line) into the file in the form: x;y;z;r Example for an output.txt file (with n=3): 2;5;6;7.87 0;2;50;19.78 17;3;79;0.53 6

Mathematical functions In math.h a lot of useful mathematical functions are declared Trigonometric functions like sin, cos Hyperbolic functions like sinh, cosh Exponential and logarithmic functions like exp or log Power functions like pow, sqrt Rounding functions like ceil, floor Some hints regarding mathematical operations Take always care that you work with the right data types Never use implicit type conversion example: int a=1,b=4; float r; r=a/b; //the result of a/b is an int printf( r=%f,r) //prints 0 Take care if you compare floating point values 7

Task 15 A program should be created which determines the tangens of an entered degree. Dynamic data structures are useful if the amount of data is unkown can grow and shrink in dependency of our needs requires memory handling - allocation of new memory for new elements - release (free) memory of elements which are not longer used examples: binary trees, linked lists 8

Binary tree Hierachical data structure with a set of connected nodes with at most two children Node with no predecessor is root node Nodes with successors are internal nodes. Children of internal nodes are left and right and they are ordered Nodes without successors are so called leafs Used for searching, sorting Binary tree (Example) root 5 left right left 4 right Inner node left 7 right left 1 right leaf left 3 right left 6 right left 9 right NULL NULL NULL NULL NULL NULL NULL NULL 9

Decalaration of a Binary tree node Definition of a structure for binary tree. Stored data in an element is only one integer value i; typedef struct nodestruct int i; struct nodestruct *left; struct nodestruct *right; node; node *root;//root of tree Linked lists Linear search for simple linked list, Quick insert (at the beginning or at the end) Slow insert (for sorted lists, search necessary) Different types: - simple linked list - double linked list - skip lists - adaptive lists Example:Stack (LIFO), queue (FIFO) 10

Linked list (declaration of list element) Definition of a structure for a linked list. Stored data in an element is only one integer value data. typedef struct elementstruct int data; struct elementstruct *next; element; element *root=null; //Root of our list Example: list with 2 Elements root Points to the begin of the list 1 list element 4 next data pointer 2 list element 8 next data pointer NULL marks the end of the list Linked list (append) Append means that a new element should be added to the end of the list. Example: 10 is appended New element must be allocated (malloc) next of 2nd element refers now to the new 3rd element next of new (3rd) element refers to NULL new (3) list lement 1 list element 2 list element 10 next root Points to the begin of the list 4 next data pointer 8 next data pointer data pointer NULL marks the end of the list 11

Linked list (insert) Insert means that a new element should be added to the list at a special position. Example: insert 9 New element must be allocated (malloc) 2nd element next refers now to the new 3rd element New (3rd) element next refers to 4th element new (3) list element 9 next 1 list element 2 list element data pointer 4 list element root Points to the begin of the list 4 next data pointer 8 next data pointer 10 next data pointer NULL marks the end of the list Linked list (delete) Delete means that an element is removed. Remove 8 Element must be localised (typically by its content) run through list til element is found 1nd element next refers now to the 3rd element Memory for the 2nd element can be released (free) root 4 next 9 next Points to the begin of the list 1 list element data pointer 2 list element 8 next data pointer 3 list element data pointer 4 list element 10 next data pointer NULL marks the end of the list 12

Task 16 A program which manages a sorted linked list. The user is able to input integer values into the list and to delete elements of the list (by its number). The program should use functions to deal with the list: insert(int i); display(); size(); delete(int i); //Inserts a new element with value i //display all values of the list //shows the number of list elements //deletes the element with value i The user can choose the operation by a number 1 = insert, 2 = display, 3=size, 4=delete, 5=EXIT Information part is over Next week Dr. Petersen will continue the lecture for Fundamentals of Programming (FOP) at 16:00 Highly recommended to attend because Dr. Petersen will focus on memory management, mathematical problems, algorithms Don t forget FOP has an exam!!! 13

#include <stdio.h> //TASK 13 #include <malloc.h> #include <stdlib.h> #include <string.h> #define BUFFERLEN 1024 int main() char buffer[bufferlength], *nump; FILE *fp; unsigned int i=1; printf("\ninput filename:"); scanf("%s",buffer); fp = fopen(buffer,"r"); if (fp!= NULL) while((fgets(buffer,bufferlen,fp))!= NULL) nump = strchr(buffer, ';'); if (nump!= NULL) *nump='\0'; printf("\nstring[%d]=%s",i,buffer); printf("\nint[%d]=%s",i++,nump+1); nump = NULL; else printf("\ncan't open %s", buffer); 2

#include <stdio.h> //Task 14 #define BUFFERLEN 1024 int main() char buff[bufferlen], filename[bufferlen]; int i,n=0,x,y,z; double r; FILE *fp; printf("\nname of output file:"); scanf("%s",filename); fflush(stdin); printf("\nnumber of datasets:"); scanf("%d",&n); fp = fopen(filename,"w"); for(i=0; i<n;i++) printf("dataset[%d] x y z r:",i); fflush(stdin); if (scanf("%d %d %d %lf",&x,&y,&z,&r) == 4) sprintf(buff,"%d;%d;%d;%.2lf\n",x,y,z,r); fputs(buff,fp); else printf("input error, again\n"); i--; printf("%d lines written to %s",n,filename); fclose(fp); 4

#include <stdio.h>// Task 15 #include <math.h> #include <stdlib.h> #define PI 3.14159265 int main() double sina, cosa,tana, alphad, alphar; double tana2; printf("input alpha(degrees):"); scanf("%lf",&alphad); //Alpha in Radians 1Rad = 180 Degree/PI alphar = alphad * PI / 180.0; tana=tan(alphar); sina=sin(alphar); cosa=cos(alphar); tana2=sina/cosa; printf("\ntan(%.2lf)=%lf",alphad,tana); printf("\nsin(%.2lf)/cos(%.2lf)=%lf", alphad,alphad, tana2); if (tana == tana2) printf("\nresults are equal"); return EXIT_SUCCESS; 6

#include<stdio.h> //Task 16 #include<stdlib.h> // Define a new datatype node which // builds the structure for an node element typedef struct nodestruct int data; struct nodestruct *next; node; node *head = NULL; //function displays the values of nodes void display(node *n) for (; n!= NULL; n=n->next) printf("%d ", n->data); //function counts the number of nodes int size(node *n) int count = 0; for(count=0; n!=null; n=n->next) count++; return count; 9

// function creates a new node element, assigns the // values returns a pointer to the new node node *newelement(int num, node *next) node *newnode; newnode = (node *)malloc(sizeof(node)); newnode->data =num; newnode->next = next; return newnode; //Insert a node. num is used to find the insert position void insert(int num) node *currp = head; if (head == NULL) //list is empty, first element head = newelement(num, NULL); else if (num < head->data) //new first element head = newelement(num,head); else currp = head; while(currp->next!= NULL) if(currp->next->data < num) currp = currp->next; else break; //if currp->next = NULL then the new element is the //new last element of our list otherwise we insert //according to the right position for for num currp->next= newelement(num, currp->next); 10

//function deletes a node from our linked list int delete(int num) node *currp = head, *prev; while(currp!=null) if(currp->data == num if(currp == head) head = currp->next; else prev->next = currp->next; free(currp); return 1; else prev = currp; currp = currp->next; return 0; 11

int main() int choice,num; head = NULL; while(1) printf("\nlinked list Operations\n"); printf("---------------\n"); printf("1.insert\n"); printf("2.display\n"); printf("3.size\n"); printf("4.delete\n"); printf("5.exit\n"); printf("please enter your choice: "); if(scanf("%d",&choice)<=0) printf("enter only an Integer\n"); exit(0); else switch(choice) case 1: printf("enter data value to be inserted: "); scanf("%d", &num); insert(num); break; case 2: if(head == NULL) printf("the list is Empty\n"); else printf("the data values in the list are: "); display(head); 12

printf("\n"); break; case 3: printf("size of list is: %d\n", size(head)); break; case 4: if(head == NULL) printf("the list is Empty\n"); else printf("enter the value to be deleted: "); scanf("%d", &num); if(delete(num)) printf("%d deleted! successfully\n", num); else printf("%d not found in the list\n", num); break; case 5: return 0; break; default: printf("invalid option!\n"); return 0; 13