CS100 : Computer Programming

Size: px
Start display at page:

Download "CS100 : Computer Programming"

Transcription

1 CS100 : Computer Programming Chapter 6 - Structures, Unions and Enumerations Narasimhan T. 6.1 Structures Suppose you want to store the details of a book. You may have to store details like title, price and edition. What is the big deal? You just define three variables viz. title, price and edition. This seems perfectly fine until you think more on it. The three pieces of information : title, price and edition are related in the sense that they all pertain to a single book. But the corresponding variables are unrelated : they are three separate entities with no relation among them. You need a technique to relate the variables or wrap these o a single unit. You cannot use an array in the above situation as the three variables are of different types. You need a more powerful user defined data type in which the individual elements can differ in type. To solve this problem, C provides a special data type the ure. A ure is a collection of one or more variables (elements), possibly of different types, grouped together under a single name for convenient handling. The individual ure elements are referred to as members or fields. Structures help to organize complicated data, particularly in large programs, because they permit a group of related variables to be treated as a single unit instead of as separate entities Defining a ure A ure must be defined in terms of its individual members. In general terms, a ure may be defined as: ; tag member-1; member-2;.. member-m; In this declaration, is a required keyword; tag is a name that identifies the ure; and member-1, member-2,, member-m are the member declarations. Notice that the declaration is terminated by a semicolon. This is because a ure declaration is a statement. (There is no formal distinction between a ure definition and a ure declaration; the terms are used erchangeably.) 1

2 Example 6.1. For the book scenario discussed earlier, we could define a ure like this ; float book title[15]; price; edition; Once the new ure data type has been defined, one or more variables can be declared to be of that type. This is done as follows: tag variable-1, variable-2,..., variable-n; where is a required keyword, tag is the name that appeared in the ure declaration and variable-1, variable-2,..., variable-n are ure variables of type tag. Example 6.2. This example declares three variables b1, b2, b3 of the type book. book b1, b2, b3 ; To avoid the use of the keyword in variable declarations, we can use as illustrated below. Example 6.3. This is another way to declare ure variables. title[15]; float price; edition; book; book b1,b2; It is also possible to combine the ure definition and ure variable declaration in one statement. Example 6.4. This is yet another way to declare ure variables. book title[15]; float price; edition; b1,b2,b3; 6.2 Accessing ure elements Individual members of a ure are accessed through the use of the dot ( ) operator. For example, to pr the edition of book b1, we write for more log on to 2

3 prf("%d",b1.edition); Similarly to input the title of book b3, you write: gets(b3.title); or scanf("%s",b3.title); Example 6.5. This program inputs and displays the details of a book. #include<stdio.h> book title[15]; author[15]; edition; float price; ; main() book b; prf("enter the title of the book\n"); gets(b.title); prf("enter the author of the book\n"); gets(b.author); prf("enter the price of the book\n"); scanf("%f",&b.price); prf("enter the edition of the book\n"); scanf("%d",&b.edition); prf("book DETAILS\n"); prf("title : %s\n",b.title); prf("author : %s\n",b.author); prf("edition : %d\n",b.edition); prf("price : %f\n",b.price); 6.3 Initializing ure members The members of a ure variable can be assigned initial values in much the same manner as the elements of an array. The initial values must appear in the order in which they will be assigned to their corresponding ure members, enclosed in braces and separated by commas. Example 6.6. This example illustrates how a ure variable is initialized. float book title[15]; price; 3

4 ; edition; book b="c Programming", , 2; This statement assigns C Programming to title, to price and 2 to edition. It is also possible to initialize the ure variable in the ure definition. Example 6.7. This is another way to initialize ure variables. book title[15]; float price; edition; b="c Programming", , 2; There are few rules to keep in mind while initializing ure variables in the program. 1. You cannot initialize individual members inside the ure template. 2. The order of values enclosed in braces must match the order of members in the ure definition. 3. It is possible to initialize only the first few members and leave the remaining uninitialized. The uninitialized members should be only at the end of the list. 4. The uninitialized members will be assigned default values as follows: Zero for eger and floating po numbers \0 for acters and strings 6.4 Operations on ure members and on ure variables The individual members in a ure can be manipulated using any operation. Following are some examples: if(b.price>100) b.price-=10; b.price++ The precedence of the member operator (. ) is higher than all arithmetic and relational operators. So there is no need to put parenthesis like (b.price)++ You can assign one ure variable to another variable of same ure. You need not assign the value of each member separately. Example 6.8. This program illustrates ure assignments for more log on to 4

5 sample a, b; x, y; x.a = 10; x.b = 20; y = x; prf("%d %d", y.a, y.b); This will pr Comparison of two ure variables is not permitted. Following statements will result in errors. if(b1==b2) if(b1!=b2) However you can compare two ure members like if(b1.price>b2.price) b1.price-=50; 6.5 Array of ures Just as you have array of egers or of acters, you can also define an array of ure variables. Such an array is called array of ures an array in which each element is a ure variable. This is illustrated in the following example. Example 6.9. This program inputs and displays the details of several books. #include<stdio.h> book title[15]; author[15]; edition; float price; ; main() book b[10]; i,n; prf("enter how many books you want to process\n"); scanf("%d",&n); for(i=0;i<n;i++) prf("enter the title of book %d \n",i+1); scanf(" %s",b[i].title); 5

6 prf("enter the author of book %d \n",i+1); scanf(" %s",b[i].author); prf("enter the edition of book %d \n",i+1); scanf("%d",&b[i].edition); prf("enter the price of book %d \n",i+1); scanf("%f",&b[i].price); for(i=0;i<n;i++) prf("book %d DETAILS\n",i+1); prf("title : %s\n",b[i].title); prf("author : %s\n",b[i].author); prf("edition : %d\n",b[i].edition); prf("price : %f\n",b[i].price); 6.6 Nested ures Suppose we have a ure named employee with the following template: ; employee empname[15]; empid; housename[15]; streetname[15]; cityname[15]; pincode; state[15]; salary; Here the members housename to state collectively represent the address of the employee. Thus they could conveniently be combined to form a ure as follows: ; employee empname[15]; empid; address housename[15]; streetname[15]; cityname[15]; pincode; state[15]; addr; salary; for more log on to 6

7 ; The above template can also be written as: ; address housename[15]; streetname[15]; cityname[15]; pincode; state[15]; employee empname[15]; empid; address addr; salary; To access the housename we write emp.addr.housename where emp is the variable of type employee. It is also possible to nest more than one ure inside another ure. 6.7 Unions Union is another way to group together data whose types may differ from one another. However, all the members within a union share the same storage area within the computer s memory, whereas each member within a ure is assigned its own unique storage area. Thus, unions are used to conserve memory. They are useful for applications involving multiple members, where values need not be assigned to all of the members at any one time. However, since all the union members share the same location, only one member can be accessed at a time. Declaring a union is similar to declaring a ure. Its general form is: union ; tag member-1; member-2;.. member-m; where union is a required keyword and the other terms have the same meaning as in a ure definition. Once a union is defined, union variables can then be declared as: union tag variable-1, variable-2,..., variable-n; where union is a required keyword, tag is the name that appeared in the union definition and variable-1, variable-2,..., variable-n are variables of type tag. Example Consider the definition 7

8 union cp; result grade; marks; Here you have a union variable, cp, of type result. It can represent either a acter(grade) or an eger quantity (marks) at a time. To access a union member, you use the same syntax as that you did for ure members. For example, with the union definition as above, you could write cp.grade= S ; While accessing an union member, you should make sure that you are accessing the member whose value is currently stored. For example, the code cp.grade= S ; cp.marks=92; prf("you have obtained %c grade for end semester examination in Computer Programming",cp.grade); could yield unexpected results. This is because, with the union definition as earlier, you can store only one value, either grade or marks in the allocated space. Thus when you store grade and later try to store marks, it will overwrite grade. 6.8 Enumerations Enumeration is a user defined data type. It can be used to define new data types. An enumeration may be defined as enum identifier value-1, value-2,..., value-m; where enum is a required keyword; identifier is a name that identifies the enumeration, and value-1, value-2,..., value-m represent the possible values that any variable of the defined type can take. These possible values are known as enumerators or enumeration constants. Once the enumeration has been defined, corresponding enumeration variables can declared as enum identifier var-1, var-2,..., var-n; where identifier is the name that appeared in enumeration definition and var-1, var-2,..., var-n are variables of the defined type. Example A C program contains the following declarations. enum enum colours black, blue, cyan, green, magenta); colours foreground, background; The first line defines an enumeration named colours (i.e., we define a new data type colours). Any variable of colours type can take one of the possible values black, blue, cyan, green, magenta. for more log on to 8

9 The second line declares two variables foreground and background to be enumeration variables of type colours. Thus, each variable can be assigned any one of the values black through magenta. The two declarations can be combined if desired, resulting in enum colours black, blue, cyan, green, magentaforeground, background; Enumeration constants are automatically assigned equivalent eger values, beginning with 0 for the first enumerator, and for each successive enumerator, the assigned value being increased by 1. Example Consider the enumeration defined in Example The enumeration constants will represent the following eger values. black 0 blue 1 cyan 2 green 3 magenta 4 It is possibe for the user to specify values of his choice for enumerators. See the example below: Example Consider the enumeration defined as below: enum colours black=-1, blue, cyan, green=0, magenta); This results in the assignment of values as follows: black -1 blue 0 cyan 1 green 0 magenta 1 Note that blue and green both are assigned 0. Similarly both cyan and magenta have the value 1. Enumeration variables can be processed in the same manner as other eger variables. Thus, they can be assigned new values, compared, etc. With the definition as in Example 6.11, following statements are valid. foreground = magenta; if(background == blue) foreground = cyan; if(background == foreground) prf("background and forefround are of same colour"); 9

10 switch(background) case blue: foreground=black; break; default: prf("bye!"); The key po to understand about an enumeration is that each of the enumerators stands for an eger value. As such, the enumeration constants cannot be pred, only their eger values can be pred. Consider the code fragment: enum colours black, blue, cyan, green, magentaforeground, background; foreground = cyan; prf("%s",foreground); This will result in an error. This is because, the enumerators are not strings (although, they appear to be). They are just names for egers. Internally they are treated as egers only. Thus to pr the equivalent eger value, you could modify the last statement as prf("%d",foreground); and this will pr You can define new data type by using the keyword. You are not actually creating a new data type, but rather defining a new name for an existing type. In general terms, a new data type is defined as type new-type; where type refers to an existing data type (either a standard data type like, etc, or previous user-defined data type), and new-type refers to the new user defined data type. Example Here is a simple declaration involving the use of. float marks; In this declaration marks is an user-defined data type, which is equivalent to type float. This statement tells the compiler to recognize marks as another name for float. Once a new name has been defined for an existing type, then new variables, arrays, etc. can be declared in terms of this new name. For example, to store the marks you scored for Computer Programming, you could write marks cp; This is equivalent to writing float cp; for more log on to 10

11 If you want to store the marks of 74 students, you could just write marks cp[74]; Using can make your code easier to read and to understand. This feature is particularly convenient when defining ures, since it eliminates the need to repeatedly use the keyword whenever a ure is referenced. Hence, the ure can be referenced more concisely. See Example Programming examples Program 6.1. Input the details (name, roll number and marks in 6 subjects) of n students and pr the details along with the total marks scored. #include<stdio.h> main() name[15]; roll, marks[6], total; student; student s[10]; // You assume n is less than or equal to 10 n,i,j; prf("how many students?"); scanf("%d",&n); for(i=0;i<n;i++) prf("enter student name\n"); scanf("%s",s[i].name); prf("enter roll number\n"); scanf("%d",&s[i].roll); prf("enter marks in six subjects\n"); for(j=0;j<6;j++) scanf("%d",&s[i].marks[j]); s[i].total=0; for(j=0;j<6;j++) // You could find the total in the previous loop too. s[i].total+=s[i].marks[j]; for(i=0;i<n;i++) prf("student %d DETAILS\n",i+1); prf("name:%s\n",s[i].name); prf("roll:%d\n",s[i].roll); for(j=0;j<6;j++) prf("marks %d: %d\n",j+1,s[i].marks[j]); prf("total:%d\n",s[i].total); 11

12 Program 6.2. Input the details (name, employee ID and date of joining) of two employees. Represent the date of joining as a nested ure. Pr the details of the employee with more experience in the company. Assume the two employees have joined in different years. #include<stdio.h> doj; doj d; employee; date; month[15]; year; name[15]; empid; main() employee e[2]; i; for(i=0;i<2;i++) prf("enter employee name\n"); scanf("%s",e[i].name); prf("enter employee ID\n"); scanf("%d",&e[i].empid); prf("enter day of joining\n"); scanf("%d",&e[i].d.date); prf("enter month of joining\n"); scanf("%s",e[i].d.month); prf("enter year of joining\n"); scanf("%d",&e[i].d.year); prf("details OF THE SENIOR EMPLOYEE\n"); if(e[0].d.year<e[1].d.year) prf("name:%s\n",e[0].name); prf("employee ID:%d\n",e[0].empID); prf("date of joining:%d %s %d\n",e[0].d.date,e[0].d.month,e[0].d.year); else prf("name:%s\n",e[1].name); prf("employee ID:%d\n",e[1].empID); prf("date of joining:%s %d %d\n",e[1].d.month,e[1].d.date,e[1].d.year); for more log on to 12

13 Program 6.3. In a company there are two type of employees Type0 and Type1. Employees belonging to Type0 are paid on hourly basis at the rate of 750 per hour. Type1 employees are paid monthly, and their gross salary is calculated as the sum of basic pay, DA (125% of basic pay) and HRA ( 550). Input the number of hours for Type0 employees and basic pay of Type1 employees and pr the gross salary. #include<stdio.h> union hours; float basicpay; salary; float salary s; employee; name[15],dept[15]; type; gross; main() employee emp; prf("enter the name of employee"); scanf("%s",emp.name); prf("enter the department of employee"); scanf("%s",emp.dept); prf("enter the type of employee:0 or 1\n"); scanf("%d",&emp.type); if(emp.type==0) prf("enter the number of hours\n"); scanf("%d",&emp.s.hours); emp.gross=emp.s.hours*750; else prf("enter the basic pay\n"); scanf("%f",&emp.s.basicpay); emp.gross=emp.s.basicpay+emp.s.basicpay* ; prf("employee Details\n"); prf("name:%s\n",emp.name); prf("department:%s\n",emp.dept); prf("salary:%f\n",emp.gross); 13

CS561 Manju Muralidharan Priya Structures in C CS200 STRUCTURES. Manju Muralidharan Priya

CS561 Manju Muralidharan Priya Structures in C CS200 STRUCTURES. Manju Muralidharan Priya OBJECTIVES: CS200 STRUCTURES Manju Muralidharan Priya By the end of this class you will have understood: 1. Definition of a structure 2. Nested Structures 3. Arrays of structure 4. User defined data types

More information

3.3 Structures. Department of CSE

3.3 Structures. Department of CSE 3.3 Structures 1 Department of CSE Objectives To give an introduction to Structures To clearly distinguish between Structures from Arrays To explain the scenarios which require Structures To illustrate

More information

IV Unit Second Part STRUCTURES

IV Unit Second Part STRUCTURES STRUCTURES IV Unit Second Part Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure

More information

Chapter-14 STRUCTURES

Chapter-14 STRUCTURES Chapter-14 STRUCTURES Introduction: We have seen variables of simple data types, such as float, char, and int. Variables of such types represent one item of information: a height, an amount, a count, and

More information

UNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.

UNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together. UNIT-IV Unit 4 Command Argument line They are parameters/arguments supplied to the program when it is invoked. They are used to control program from outside instead of hard coding those values inside the

More information

Structures Unions and Enumerated Datatypes 224

Structures Unions and Enumerated Datatypes 224 STRUCTURES, UNIONS AND ENUMERATED DATA TYPES LEARNING OBJECTIVES After reading this chapter, the readers will be able to understand the purpose of the user defined data types Structures, Unions and Enumerated

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are

More information

UNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; };

UNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; }; UNIT-V Structures Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure is given

More information

ALQUDS University Department of Computer Engineering

ALQUDS University Department of Computer Engineering 2013/2014 Programming Fundamentals for Engineers Lab Lab Session # 8 Structures, and Enumeration ALQUDS University Department of Computer Engineering Objective: After completing this lab, the students

More information

Write a C program using arrays and structure

Write a C program using arrays and structure 03 Arrays and Structutes 3.1 Arrays Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements. (10M) 3.2 Declaration and initialization of string

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 12: Structures Readings: Chapter 11 Structures (1/2) A structure is a collection of one

More information

Structure, Union. Ashishprajapati29.wordpress.com. 1 What is structure? How to declare a Structure? Explain with Example

Structure, Union. Ashishprajapati29.wordpress.com. 1 What is structure? How to declare a Structure? Explain with Example Structure, Union 1 What is structure? How to declare a Structure? Explain with Example Structure s a collection of logically related data items of different data types grouped together under a single name.

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Unit 8. Structures and Unions. School of Science and Technology INTRODUCTION

Unit 8. Structures and Unions. School of Science and Technology INTRODUCTION INTRODUCTION Structures and Unions Unit 8 In the previous unit 7 we have studied about C functions and their declarations, definitions, initializations. Also we have learned importance of local and global

More information

Structures in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Structures in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan Structures in C DCS COMSATS Institute of Information Technology Rab Nawaz Jadoon Assistant Professor COMSATS IIT, Abbottabad Pakistan Introduction to Computer Programming (ICP) Structures in C Which mechanic

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

UNIT - V STRUCTURES AND UNIONS

UNIT - V STRUCTURES AND UNIONS UNIT - V STRUCTURES AND UNIONS STRUCTURE DEFINITION A structure definition creates a format that may be used to declare structure variables. Let us use an example to illustrate the process of structure

More information

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

2.2 Syntax Definition

2.2 Syntax Definition 42 CHAPTER 2. A SIMPLE SYNTAX-DIRECTED TRANSLATOR sequence of "three-address" instructions; a more complete example appears in Fig. 2.2. This form of intermediate code takes its name from instructions

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

More information

Chapter 2 THE STRUCTURE OF C LANGUAGE

Chapter 2 THE STRUCTURE OF C LANGUAGE Lecture # 5 Chapter 2 THE STRUCTURE OF C LANGUAGE 1 Compiled by SIA CHEE KIONG DEPARTMENT OF MATERIAL AND DESIGN ENGINEERING FACULTY OF MECHANICAL AND MANUFACTURING ENGINEERING Contents Introduction to

More information

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information Laboratory 2: Programming Basics and Variables Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information 3. Comment: a. name your program with extension.c b. use o option to specify

More information

POINTERS, STRUCTURES AND INTRODUCTION TO DATA STRUCTURES

POINTERS, STRUCTURES AND INTRODUCTION TO DATA STRUCTURES 1 POINTERS, STRUCTURES AND INTRODUCTION TO DATA STRUCTURES 2.1 POINTERS Pointer is a variable that holds the address of another variable. Pointers are used for the indirect manipulation of the variable.

More information

C Syntax Out: 15 September, 1995

C Syntax Out: 15 September, 1995 Burt Rosenberg Math 220/317: Programming II/Data Structures 1 C Syntax Out: 15 September, 1995 Constants. Integer such as 1, 0, 14, 0x0A. Characters such as A, B, \0. Strings such as "Hello World!\n",

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions 8/24/2012 Dept of CS&E 2 Arithmetic operators Relational operators Logical operators

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5 1 What is structure? How to declare a Structure? Explain with Example Structure is a collection of logically related data items of different data types grouped together under a single name. Structure is

More information

Computer System and programming in C

Computer System and programming in C 1 Basic Data Types Integral Types Integers are stored in various sizes. They can be signed or unsigned. Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign

More information

These are reserved words of the C language. For example int, float, if, else, for, while etc.

These are reserved words of the C language. For example int, float, if, else, for, while etc. Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.

More information

Chapter 3: Arrays and More C Functionality

Chapter 3: Arrays and More C Functionality Chapter 3: Arrays and More C Functionality Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. (c) Describe the implications of reading

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

Microsoft Excel Level 2

Microsoft Excel Level 2 Microsoft Excel Level 2 Table of Contents Chapter 1 Working with Excel Templates... 5 What is a Template?... 5 I. Opening a Template... 5 II. Using a Template... 5 III. Creating a Template... 6 Chapter

More information

UNIT 3 FUNCTIONS AND ARRAYS

UNIT 3 FUNCTIONS AND ARRAYS UNIT 3 FUNCTIONS AND ARRAYS Functions Function definitions and Prototypes Calling Functions Accessing functions Passing arguments to a function - Storage Classes Scope rules Arrays Defining an array processing

More information

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

Example: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( )

Example: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( ) Computer Programming and Utilization ( CPU) 110003 Structure, Union 1 What is structure? How to declare a Structure? Explain with Example Structure is a collection of logically related data items of different

More information

BCA-105 C Language What is C? History of C

BCA-105 C Language What is C? History of C C Language What is C? C is a programming language developed at AT & T s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. C seems so popular is because it is

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Other Loop Options EXAMPLE

Other Loop Options EXAMPLE C++ 14 By EXAMPLE Other Loop Options Now that you have mastered the looping constructs, you should learn some loop-related statements. This chapter teaches the concepts of timing loops, which enable you

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto CS 170 Java Programming 1 The Switch Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Menu-Style Code With ladder-style if-else else-if, you might sometimes find yourself writing menu-style

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate

More information

The syntax of structure declaration is. struct structure_name { type element 1; type element 2; type element n;

The syntax of structure declaration is. struct structure_name { type element 1; type element 2; type element n; Structure A structure is a user defined data type. We know that arrays can be used to represent a group of data items that belong to the same type, such as int or float. However we cannot use an array

More information

9/9/2017. If ( condition ) { statements ; ;

9/9/2017. If ( condition ) { statements ; ; C has three major decision making instruction, the if statement, the if- statement, & the switch statement. A fourth somewhat less important structure is the one which uses conditional operators In the

More information

Here is a C function that will print a selected block of bytes from such a memory block, using an array-based view of the necessary logic:

Here is a C function that will print a selected block of bytes from such a memory block, using an array-based view of the necessary logic: Pointer Manipulations Pointer Casts and Data Accesses Viewing Memory The contents of a block of memory may be viewed as a collection of hex nybbles indicating the contents of the byte in the memory region;

More information

by: Lizawati, Norhidayah & Muhammad Noorazlan Shah Computer Engineering, FKEKK, UTeM

by: Lizawati, Norhidayah & Muhammad Noorazlan Shah Computer Engineering, FKEKK, UTeM by: Lizawati, Norhidayah & Muhammad Noorazlan Shah Computer Engineering, FKEKK, UTeM At the end of this chapter, the students should be able to: understand and apply typedef understand and apply structure

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

Data about data is database Select correct option: True False Partially True None of the Above

Data about data is database Select correct option: True False Partially True None of the Above Within a table, each primary key value. is a minimal super key is always the first field in each table must be numeric must be unique Foreign Key is A field in a table that matches a key field in another

More information

Preview from Notesale.co.uk Page 6 of 52

Preview from Notesale.co.uk Page 6 of 52 Binary System: The information, which it is stored or manipulated by the computer memory it will be done in binary mode. RAM: This is also called as real memory, physical memory or simply memory. In order

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays 1 What are Arrays? Arrays are our first example of structured data. Think of a book with pages numbered 1,2,...,400.

More information

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

CSE 230 Intermediate Programming in C and C++

CSE 230 Intermediate Programming in C and C++ CSE 230 Intermediate Programming in C and C++ Unions and Bit Fields Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Union Like structures, unions are

More information

MCA Semester 1. MC0061 Computer Programming C Language 4 Credits Assignment: Set 1 (40 Marks)

MCA Semester 1. MC0061 Computer Programming C Language 4 Credits Assignment: Set 1 (40 Marks) Summer 2012 MCA Semester 1 4 Credits Assignment: Set 1 (40 Marks) Q1. Explain the following operators with an example for each: a. Conditional Operators b. Bitwise Operators c. gets() and puts() function

More information

CHAPTER 13 STRUCTURES

CHAPTER 13 STRUCTURES CHAPTER 13 STRUCTURES INTRODUCTION In C++ language, custom data types can be created to meet users requirements in 5 ways: class, structure, union, enumeration and typedef. Structures are one of the 2

More information

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered )   FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING ( Word to PDF Converter - Unregistered ) http://www.word-to-pdf-converter.net FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING INTRODUCTION TO C UNIT IV Overview of C Constants, Variables and Data Types

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 17 Switch Statement (Refer Slide Time: 00:23) In

More information

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times } Rolling a Six-Sided Die face = 1 + randomnumbers.nextint( 6 ); The argument 6 called the scaling factor represents the number of unique values that nextint should produce (0 5) This is called scaling

More information

M.EC201 Programming language

M.EC201 Programming language Power Engineering School M.EC201 Programming language Lecture 13 Lecturer: Prof. Dr. T.Uranchimeg Agenda The union Keyword typedef and Structures What Is Scope? External Variables 2 The union Keyword The

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

struct structure_name { //Statements };

struct structure_name { //Statements }; Introduction to Structure http://www.studytonight.com/c/structures-in-c.php Structure is a user-defined data type in C which allows you to combine different data types to store a particular type of record.

More information

Chapter 2.6: Testing and running a solution

Chapter 2.6: Testing and running a solution Chapter 2.6: Testing and running a solution 2.6 (a) Types of Programming Errors When programs are being written it is not surprising that mistakes are made, after all they are very complicated. There are

More information

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation. Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

More information

C - Basic Introduction

C - Basic Introduction C - Basic Introduction C is a general-purpose high level language that was originally developed by Dennis Ritchie for the UNIX operating system. It was first implemented on the Digital Equipment Corporation

More information

Learning to Program with Haiku

Learning to Program with Haiku Learning to Program with Haiku Lesson 4 Written by DarkWyrm All material 2010 DarkWyrm It would be incredibly hard to write anything useful if there weren't ways for our programs to make decisions or to

More information

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout

More information

Basic Elements of C. Staff Incharge: S.Sasirekha

Basic Elements of C. Staff Incharge: S.Sasirekha Basic Elements of C Staff Incharge: S.Sasirekha Basic Elements of C Character Set Identifiers & Keywords Constants Variables Data Types Declaration Expressions & Statements C Character Set Letters Uppercase

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

VPM s Joshi-Bedekar College of Arts and Commerce TYBCOM Practical Exam Practice Questions MYSQL

VPM s Joshi-Bedekar College of Arts and Commerce TYBCOM Practical Exam Practice Questions MYSQL STUDENT containing columns ROLLNO (roll number), NAME (Student s name), ADDR (Student s address) and PHONE (Phone number). Add five rows to this table. To Display roll number, name of all the students

More information

Chapter 14. Structures

Chapter 14. Structures Christian Jacob Chapter 14 Structures 14.1 Structures 14.1.1 Basic Definitions 14.1.2 Examples of Structures 14.1.3 Accessing Structure Members 14.1.4 Arrays of Structures 14.2 Structures and Pointers

More information

Lecture 3. The syntax for accessing a struct member is

Lecture 3. The syntax for accessing a struct member is Lecture 3 Structures: Structures are typically used to group several data items together to form a single entity. It is a collection of variables used to group variables into a single record. Thus a structure

More information

(Note: 1. Each Question Carries 5 marks. 2. Solve any two questions) SET-I

(Note: 1. Each Question Carries 5 marks. 2. Solve any two questions) SET-I name), ADDR (Student s address) and PHONE (Phone number). Add five rows to this table. To Display roll number, name of all the students EMPLOYEE containing columns EMP_ID( employee id primary key) EMP_NAME(

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #03 The Programming Cycle

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #03 The Programming Cycle Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #03 The Programming Cycle (Refer Slide Time: 00:22) Once we are understood what algorithms are, we will start

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

C-LANGUAGE CURRICULAM

C-LANGUAGE CURRICULAM C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals

More information

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 3 References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Introduction to C programming. By Avani M. Sakhapara Asst Professor, IT Dept, KJSCE

Introduction to C programming. By Avani M. Sakhapara Asst Professor, IT Dept, KJSCE Introduction to C programming By Avani M. Sakhapara Asst Professor, IT Dept, KJSCE Classification of Software Computer Software System Software Application Software Growth of Programming Languages History

More information

Multiple-Subscripted Arrays

Multiple-Subscripted Arrays Arrays in C can have multiple subscripts. A common use of multiple-subscripted arrays (also called multidimensional arrays) is to represent tables of values consisting of information arranged in rows and

More information

Operators and Expressions:

Operators and Expressions: Operators and Expressions: Operators and expression using numeric and relational operators, mixed operands, type conversion, logical operators, bit operations, assignment operator, operator precedence

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore Sir Syed University of Engineering and Technology. Computer ming & Problem Solving ( CPPS ) Functions Chapter No 1 Compiled By: Sir Syed University of Engineering & Technology Computer Engineering Department

More information

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be

More information

Input And Output of C++

Input And Output of C++ Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information