We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31
EE171: Introduction to
Computers & Programming for Engineers
Lecture 8: Computer Programming
with C… DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM Structures
DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 2
Structures A structure is a convenient tool form handling a group of logically related data items. These fields are called structure elements or members. Declaring A Structure The general form of a structure declaration statement is given below: struct <structure name> { Example structure element1; struct book{ structure element2; char name[20]; structure element3; char author[15]; ………. int pages; ………. } float price; }
DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 3
Structures … Important points while declaring a structure type: The closing brace in the structure type declaration must be followed by a semicolon. It is important to understand that a structure type declaration does not tell the compiler to reserve any space in memory. • All a structure declaration does is, it defines the ‘form’ of the structure. Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined. DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 4 Structures … Accessing Structure Elements: The members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. Declaring a variable of a Structure: struct struct_name var_name; The link between a member and a variable is established using the member operator “.” which is also known as “dot operator”. The general form is structure-variable.structure- member; DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 5 Structures … 1. # include <stdio.h> 2. struct StudentData { char stu_name; int stu_id; Output }; Student Name is: Steve 3. void main( ) { 4. struct StudentData student; Student Id is: 1234 5. student.stu_name = "Steve"; 6. student.stu_id = 1234; 7. printf("Student Name is: %s", student.stu_name); 8. printf("\nStudent Id is: %d", student.stu_id); 9. } DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 6 Arrays of Structures We may declare an array of structures, each element of the array representing a structure variable. E. g.: struct class student[100]; This defines an array student, that consists of 100 elements. Each element is defined to be of the type struct class. Consider the following declaration: struct marks { int sub1; int sub2; int sub3; } students[20]; DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 7 Arrays within Structures C permits the use of arrays as structure members. We have already used arrays of characters inside a structure. Similarly, we can use single-or multidimensional arrays of type int or float. For example, the following structure declaration is valid: struct marks { int number; float sub[3]; } students[2]; DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 8 Structures within Structures within a structure means Nested Structures. Nesting Structures of structures is permitted in C. Let us consider the following structure definition: struct salary { The salary structure contains a member char name[20];named allowance which itself is a structure char dept[10]; with three members. struct { The members contained in the inner structure int house_rent; int city; namely dearness, house_rent, and city can be }allowance; referred to as: }employee; employee.allowance.dearness employee.allowance.house_rent employee.allowance.city DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 9 Unions vs Structures Unions are a concept borrowed from structures and therefore follow the same syntax as structures. However, there is major distinction between them in terms of storage - In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structures, a union can be declared using the keyword union as follows: union item { int m; float x; char c; }code; DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 10 Size of Structures We normally use structures, unions, and arrays to create variables of large sizes. The actual size of these variables in terms of bytes may change from machine to machine. We may use the unary operator sizeof to tell us the size of a structure (or any variable). The expression “sizeof(struct x);” will evaluate the number of bytes required to hold all the members of the structure x. If y is a simple structure variable of type struct x, then the expression “sizeof(y)” would also give the same answer. DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 11 Pointers
DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 12
Pointers Pointers are another important feature of C language. They are a powerful tool and handy to use once they are mastered. There are a number of reasons for using pointers. A pointer enables us to access a variable that is defined outside the function. Pointers are more efficient in handling the data tables. Pointers reduce the length and complexity of a program. They increase the execution speed. The use of a pointer array to character strings results in saving of data storage space in memory. DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 13 Accessing the Address of a The actual location of a variable in the memory is system Variable dependent and therefore, the address of a variable is not known to us immediately. We can determine the address of the variable with the help of the operator ‘&’ in C, which can be remembered as “address of” We have already seen the use of this address operator in the scanf function. The operator & immediately preceding a variable returns the address of the variable associated with it. E.g.: p = &q; would assign the address of variable14 q to DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM Declaring Pointers Since pointer variables contain addresses that belong to a separate data type, they must be declared as pointers before we use them. The declaration of a pointer variable: datatype *pt_name; This tells the compiler three things about the variable pt_name. The asterisk (*) tells the variable pt_name is a pointer variable. pt_name needs a memory location. pt_name points to a variable of type datatype. E.g.: int *p; declares the variable p as a pointer variable that points to an integer data type. DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 15 Pointers Initialization Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement such as p = &q; which causes p to point to the address of q. This is known as pointer initialization. Before a pointer is initialized, it should not be used. A pointer variable can be initialized in its declaration itself: E.g.: int x, *p=&x; It declares x as an integer variable and p as a pointer variable and then initializes p to the address of x. Note: This is an initialization of p, not *p; and also remember that the target variable x is declared first. The statement DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 16 int Accessing a Variable through A variable can be accessed through a pointer by using Pointer another unary operator * (asterisk), usually known as the indirection operator. When statements: Consider the following the operator * is placed before a int q, *p, n; pointer variable in an expression, the pointer q = 179; returns the value of the variable of which the pointer value is the address. p = &q; In this case, *p returns the value of the n = *p; variable quantity, because p is the address of quantity. Thus the value of n would be 179. The * can be remembered as “value of address”. DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 17 Pointers and Arrays When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element (index 0) of the array. The compiler also defines the array name as a constant pointer to the first element. If we declare p as an integer pointer, then we can make the pointer p to point to the array x by the following assignment: p = &x; or p = &x[0]; When handling arrays, instead of using array indexing, we can use pointers to access array elements. Note that *(p+3) gives the value of x[3]. The pointer accessing DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 18 Pointers and Character A string is an array of characters, terminated with a null character. LikeStrings in one-dimensional arrays, we can use a pointer to access the individual characters in a string. 1. # include <stdio.h> 2. void main( ) { Output 3. int i = 0; char str = “EE171”; *str; The length is: 5 4. while (*str!=‘\o’){ 5. i++; 6. str++; } 7. printf(“\nThe length is: %d”, i); 8. } DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 19 Pointers and Functions When we pass addresses to a function, the parameters receiving the addresses should be pointers. The process of calling a function using pointers to pass the addresses of variable is known as call by address. 1. # include <stdio.h> 2. void main( ) { 3. int a=3;b=4; 4. swap(&a, &b); 5. } 6. void swap(int *x, int *y){ swap function swaps the values 7. int z; z = *x; *x = *y; *y = z; of variables by pointing to their 8. } addresses DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 20 Pointers and Structures We use the arrow operator also known as member selection operator -> to access the members of a structure via pointer variable. 1. # include <stdio.h> 2. void main( ) { 3. struct student { char id[15]; char Output firstname[64]; }; Enter ID: EE171 4. struct student std; 5. struct student *ptr = NULL; ID via std: EE171 6. ptr = &std; ID via ptr: EE171 7. printf("Enter ID: "); scanf("%s", ptr- >id); 8. printf("ID via std: %s\n", std.id); 9. DEPARTMENT printf("ID via- COET, OF ELECTRICAL ENGINEERING ptr : %s\n", ptr->id); UDSM } 21 File Management
DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 22
File Management in C A file is a place on the disk where a group of related data is stored. FILE is a structure that is defined in the I/O library. Like most other languages, C supports a number of functions that have the ability to perform basic file operations, which include: Naming a file, Opening a file, Reading data from a file, Writing data to a file, and 23 DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM File Management Functions
DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 24
Defining and Opening a File If we want to store data in a file in the secondary memory, we must specify certain things about the file, to the operating system. They include: Filename, Data Structure. Purpose. Following is the general format for declaring and opening a file: FILE *fp; [declares the variable fp as a “pointer to the data type FILE”] fp = fopen(filename”, “mode”); [opens the file named filename and assigns as identifier to the FILE the pointer fp] Mode can be one of the following: • r open the file for reading only. • w open the file for writing only. • a open the file for appending (or adding) data to it.
DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 25
Defining and Opening a File When trying to open a file, one of the following things may happen: Mode… is “writing” - a file with the specified name is created if the file does not exist but the contents are deleted, if the file already exists. Purpose is “appending” – the file is opened with the current contents safe. A file with the specified name is created if the file does not exist. Purpose is “reading” – if file exists, then the file is opened with the current contents safe; otherwise an error occurs. Many recent compilers include additional modes of operation: “r+” - The existing file is opened to the beginning for both reading and writing. “w+” - Same as “w” except both for reading and writing. “a+” Same as “a” except both for reading and writing. DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 26 Input/Output Operations on Once a file is opened, reading out of or writing to it is Files using the standard I/O routines that are listed. accomplished The getc and putc Functions - analogous to getchar and putchar functions and handle one character at a time. Assume that a file is opened with mode w and file pointer fp. • putc(c, fp); writes the character contained in the character variable c to the file associated with FILE pointer fp. Similarly, getc is used to read a character from a file that has been DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 27 Input/Output Operations on Assume that a file opened in read mode. Files … would read a character from the file whose • c = getc(fp2); file pointer is fp. The file pointer moves by one character position for every operation of getc or putc. The getc will return an end-of-file marker EOF, when end of the file has been reached. Therefore, the reading should be terminated when EOF is encountered.
DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 28
The fprintf & fscanf The functions fprintf and fscanf perform I/O operations that Functions are identical to the familiar printf and scanf functions, except of course that they work on files. The first argument of these functions is a file pointer which specifies the file to be used. The general form of fprintf: fprintf(fp, “control string”, list); fp is a file pointer associated with a file that has been opened for writing. control string contains output specifications for the items in the list. DEPARTMENT list may include OF ELECTRICAL ENGINEERING - COET,variables, UDSM constants and strings. 29 The fprintf & fscanf The general format of fscanf: fscanf(fp, “control string”, list); ThisFunctions … statement would cause the reading of the items in the list from the file specified by fp, according to the specifications contained in the control string. E.g.: fscanf(f, “%s %d”, item, &quantity); Like scanf, fscanf also returns the number of items that are successfully read. When the end of file is reached, it returns the value of EOF.
DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 30
Closing a File A file must be closed as soon as all operations on it have been completed. The general form is: fclose(file_pointer);
Assignment 8.1: Write a simple C program that reads
from one file and writes to another file. DEPARTMENT OF ELECTRICAL ENGINEERING - COET, UDSM 31