Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 10: Functions/Structure and Unions 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein is subject to change without notice. C3: Protected
About the Author Created By: Jeyshankar Perumal (125623) Credential Information: Version and Date: Technical Skills: UNIX/C/C++/Oracle Experience: 8.5 Years PSC/PPT/1107/1.0 2
Icons Used Questions Tools Hands on Exercise Coding Standards Test Your Understanding Reference Try it Out A Welcome Break Contacts 3
Problem Solving and 'C' Programming Session 10: Overview Introduction: This session discusses about the storage classes, the command line arguments and the structures and it s operation. 4
Problem Solving and 'C' Programming Session 10: Objective Objective: After completing this session you will be able to:» Work with different storage classes in a program» Work with command line arguments» Explain the concept of structures and unions» Declare structure» Initialise structure» Perform operations on structures» Perform operation on structures and arrays» Perform operation on structures and functions 5
Storage Classes Variables in C can be characterized by their data type and storage classes. Data type refers to the type of information represented by a variable and storage classes define its life time and scope. Different storages classes available are:» auto» static» register» extern 6
Storage Classes (Contd.) The scope of the variable (where it can be used), is determined by where it is defined. If it is defined outside of all the blocks, then it has file scope. If a variable is defined in a block (encapsulated with and }), then its scope begins when the variable is defined and ends when it hits the terminating }. This is called block scope. 7
Storage Classes (Contd.) Life time refers to the permanence of a variable, that is, how long the variable will retain its value in memory. Syntax: stor-cls-specifier datatype vble-name,... 8
Automatic Variables: Auto Storage Class Automatic variables are local to the block in which they are declared. Local variables of different functions/blocks may have the same name. It retains its value till the control remains in that block. If not initialized, their initial value will be unpredictable. Stored in Memory. If no storage class is specified, by default it is an auto variable. 9
Automatic Variables: Auto Storage Class (Contd.) Example: main() } int a = 5 ; int a =6 ; printf ( %d, a); /*prints 6*/ } printf( %d, a); /*prints 5*/ 10
Static Variables: Static Storage Class Static variables are also local (visible) to the block in which the variable is declared. They retain the values throughout the life of the program. If not initialized in the declaration, it is automatically initialized to zero. Static variable values are stored in Memory. 11
Static Variables: Static Storage Class (Contd.) Example: main() int i; for (i=1;i<=5;i++) incre(); } incre() static int x = 0; x = x +1; printf( x = %d\n,x); } Output: x = 1 x = 2 x = 3 x = 4 12
Register Variables: Register Storage Class Registers are faster than memory, keeping the frequently accessed variables like a loop control variable in a register will increase the execution speed. Register variables are local (visible) to the block in which they declared. It retains its value till the control remains in that block. If not initialized, the variable is initialized to zero. 13
External Variables: Extern Storage Class External variables are not confined to a single function. Their scope extends from the point of definition through the remainder of the program. They are referred to as global variables. Access to variables outside of their file scope can also be made by using linkage. Linkage is done by placing the keyword extern prior to a variable declaration. This allows a variable that is defined in another source code file to be accessed. 14
External Variables: Extern Storage Class (Contd.) Example: int a = 5 ; /*external variable defination (no need to use extern keyword)*/ void main() extern int b; /*external vble declaration (the vble is declared somewhere else)*/ void fun(); fun(); printf( %d, a); /*prints 10*/ printf( %d, b); /*prints 20*/ } void fun() a = 10 ; } int b = 20; 15
Command Line Arguments A C program is executed by calling its main() function. The main() function is called with one integer argument indicating how many words are in the command line and another argument that is a character array of pointers containing the command line words. 16
Command Line Arguments (Contd.) main ( int argc, char *argv[]) : } argc provides a count of the number of command line arguments. argv is an array of character pointer of undefined size that can be thought of as an array of pointer to strings, which are command line strings. 17
Command Line Arguments (Contd.) Example: main( int argc, char* argv[]) } int i; printf( \n Total No. of Arguments =%d,argc); for( i = 0; i < argc; i++) printf( \narg. No. %d = %s,i, argv[i]); 18
Command Line Arguments (Contd.) When the following command is given in the command prompt, for the above program: C:\tc\bin> CMLPGM c cpp java» Where: CMLPGM is program name c cpp java arguments The following result is displayed: Total No. of Arguments = 4 Arg. No. 0 = CMLPGM Arg. No. 1 = c Arg. No. 2 = cpp Arg. No. 3 = java 19
Introduction to Structures and Unions Structures and Unions are the main constructs available in C through which programmers can define new data type. Structures and unions provide a way to group logically related data items together. 20
Structure The structure is a derived data type used to represent heterogeneous data. A structure is an aggregation of components that can be treated as a single variable. The components are called members. For example, an employee is represented with the following attributes:» employee code (alphanumeric)» employee name (string)» department code (integer)» salary (float) 21
Structure: Declaration Structures are defined via a template and declared with a tag which helps to avoid repeating the definition. struct keyword is used to define structures. struct tag_name type variable-name, variable-name,...; type variable-name, variable-name,...; type variable-name, variable-name,...; : : type variable-name, variable-name,...; }; 22
Structure: Declaration (Contd.) Structure-variables can be declared anywhere in the program. Syntax: struct tag_name new-structure-variable; Example: struct employee int code; char name[20]; int dept_code; float salary; }; struct employee emp1, emp2; 23
Structure: Declaration (Contd.) Structure definition and declaration of structure variables can be combined together. Example: struct employee int code; char name[20]; int dept_code; float salary; } emp1, emp2; Note: Tag name is optional in this case. 24
Structure: Initialization Structure variables can be initialized at the time of declaration If the structure variable is declared before the main function, the member variables are automatically initialized to zero or Null. If it is partially initialized, then uninitialized members will be assigned zero or Null character. 25
Accessing the Members Members of the structure can be accessed by using the member access operator. (dot) Syntax: struct_vble.member-field-name Example: emp1.code emp1.name emp1.dept_code emp1.salary emp2.code emp2.name 26
Operations on Structures Each member of a structure can be assigned to the corresponding member of another structure. Structure can also be assigned to another Structure provided they have the same composition. sizeof() operator can be used to find the size of the structure. 27
Operations on Structures (Contd.) Two structure variables cannot be compared for equality, even though the values stored in the member variables are the same. This is because slack bytes are added in between two member variables and these slack bytes have some garbage value. 28
Nested Structures Structures can contain members that themselves are structures. struct date int day; int month; int year; }; struct employee int code; char name [20]; struct date doj ; int dept_code; float salary; }emp1,emp2; 29
Structures and Arrays The members of structures can be arrays and the structure can also be an array Example: The following example is a array of structures: struct stud int rollnum; char name[20]; int semester; int avg; }; struct stud student[50]; Accessing values: student[1].rollnum, student[1].name, student[1].semester, student[1].avg 30
Arrays Within Structures Example: struct student-mark int rollnumber; char name[15]; int sub_marks[5]; } student; Accessing values: student.sub_marks[0], student.sub_mark[1], student.name 31
Self-Referential Structures A structure containing a member which is a pointer to the same structure type is called self-referential structures. It is used to build various kinds of linked data structures. Example: struct employee char name[20]; char gender; float salary; struct employee *empptr; }; 32
Structures and Functions Structures can be passed to a function using call by value and call by reference methods. By default the structure is passed using call by value approach to a function. For calling by reference, structure should be a array of structures or structure variable should be pointer variable. 33
Structures and Functions (Contd.) Example: Passing structures to a function (call by value): struct emp int empno; char empname[10]; }; void main( ) void display(struct emp); struct emp emp1 = 101, AAAA } ; display(emp1); } void display(struct emp emp2) printf( %d, emp2.empno); printf( %s, emp2.empname); } 34
Structures and Functions (Contd.) Example: Passing structures to a function (call by reference): struct emp int empno; char empname[10]; }; void main( ) void change(struct emp *); struct emp emp1 = 101, AAAA } ; change(&emp1); printf( %d, emp1->empno); /*prints 102*/ } void change (struct emp *emp2) emp2->empno =102; } 35
Q & A Allow time for questions from participants 36
Try it Out: 1 Problem Statement: Write a program to convert given weight in pounds to Imperial and international units 37
Try it Out: 1 (Contd.) Code: #include <stdio.h> void print_converted(int pounds) /* Convert U.S. Weight to Imperial and International Units. Print the results */ int stones = pounds / 14; int uklbs = pounds % 14; float kilos_per_pound = 0.45359; float kilos = pounds * kilos_per_pound; } printf(" %3d %2d %2d pounds, stones, uklbs, kilos); %6.2f\n", main(int argc,char *argv[]) int pounds; Refer File Name : <ses10_1.c> for soft copy of the code 38
Try it Out: 1 (Contd.) Code: if(argc!= 2) printf("usage: convert weight_in_pounds\n"); exit(1); } } sscanf(argv[1], "%d", £s); /* Convert String to int */ printf(" US lbs UK st. lbs INT Kg\n"); print_converted(pounds); getchar(); Refer File Name : <ses10_1.c> for soft copy of the code 39
Try it Out: 1 (Contd.) How it Works: This program explains how to use command line arguments. While running the program pass the weight which needs to be converted in to different units as input argument Read the command line argument, convert the pound in to different units by applying formula. Print the values on the screen 40
Try it Out: 2 Problem Statement: Write a program to store values in a structure and pass the structure to a function and print the values on the screen 41
Try it Out: 2 (Contd.) Code: #include <stdio.h> struct s_type int i; double d; } var1; void f(struct s_type temp); void main(void) var1.i=99; var1.d = 98.6; f(var1); getchar(); } void f(struct s_type temp) printf("%d %1f", temp.i, temp.d); } Refer File Name : <ses10_2.c> for soft copy of the code 42
Try it Out: 2 (Contd.) How it Works: In this program, declare a structure comprising of two different data type members Assign values to each member of a structure. Pass the structure in a function, where it access each member of structure and print it on the screen 43
Q & A Allow time for questions from participants 44
Test Your Understanding 1. State whether the following statements are True or False: a) The tag name of a structure is optional. b) Structures may contain members of only one data type. c) Structure members will share the memory locations. 2. Write a Program to perform basic banking operations using array of structures. 45
Problem Solving and 'C' Programming Session 10: Summary C supports four storage class specifiers (auto, static, extern, and register) to define scope and life time for the variable. The command line arguments argc, argv are used to pass arguments to main() function. Structure is a derived data type which is used to store heterogeneous data items under a single unit. Structure members can be accessed by structure variables using dot operator. Structures can be nested and can have self reference also. Structure can be passed to a function by both call by value approach and call by reference approach. 46
Problem Solving and 'C' Programming Session 10: Source C Reference Card (ANSI) C Reference Manual by Dennis Ritchie Programming in C: A Tutorial by Brian W. Kernighan, Bell Laboratories Byron Gottfried, Programming in C, Tata McGraw Hill Deitel & Deitel, C How to Program, Third Edition, Prentice Hall Disclaimer: Parts of the content of this course is based on the materials available from the Web sites and books listed above. The materials that can be accessed from linked sites are not maintained by Cognizant Academy and we are not responsible for the contents thereof. All trademarks, service marks, and trade names in this course are the marks of the respective owner(s). 47
You have completed the Session 10 of Problem Solving and 'C' Programming 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein is subject to change without notice.