Programming. Structures, enums and unions

Size: px
Start display at page:

Download "Programming. Structures, enums and unions"

Transcription

1 Programming Structures, enums and unions

2 Summary } Structures } Declaration } Member access } Function arguments } Memory layout } Array of structures } Typedef } Enums } Unions 2

3 Idea! } I want to describe a box. I need variables for the width, length, and height } I can use three variables, but wouldn t it be better if I had a single variable to describe a box? Box width length height } That variable can have three parts, the width, length, and height 3

4 C Structures: Short Introduction } A struct (short for structure) in C is a grouping of variables together into a single type struct nameofstruct type member; type member; }; Note the semicolon at the end! To declare a variable: struct nameofstruct variable_name; 4

5 C Structures Provide Data Aggregation } Aggregate since they hold multiple data items at one time } Holds data items of various types: named members } C treats each structure as a unit } As opposed to the array approach: a pointer to a collection of members in memory } Entire structures (not just pointers to structures) may be passed as function arguments, assigned to variables, etc. } Note that they cannot be compared using == 5

6 Structure Declarations } Combined variable and type declaration struct tag member-list} variable-list; } Any one of the three portions can be omitted struct int a, b; char *p;} x, y; /* omit tag */ } variables x, y declared with: } integer members a, b and char pointer p } x and y have same type, but differ from all others: } Even if there is another declaration like this: struct int a, b; char *p;} z; /* z has different type from x, y */ 6

7 Structure Declarations struct S int a, b; char *p;}; /* omit variables */ } No variables are declared, but there is now a type struct S that can be later used struct S z; /* omit members */ } Given an earlier declaration of struct S, this declares a variable of that type typedef struct int a, b; char *p;} S; /* omits both tag and variables */ } This creates a simple type name S } More convenient than struct S 7

8 Examples #include <stdio.h> struct Box int width; int length; int height; }; struct Circle double radius; }; int main() struct Box b; struct Circle c; } Data structure definition You can declare variables Box width length height Circle radius 8

9 Recursively Defined Structures } Within a structure you can refer to structures of the same type, via pointers struct TREENODE char *label; struct TREENODE *leftchild, *rightchild; } } Naturally, a structure cannot contain an instance of itself as a member 9

10 Recursively Defined Structures } When two structures refer to each other, one must be declared in incomplete (prototype) fashion struct HUMAN; struct PET char name[name_limit]; char species[name_limit]; struct HUMAN *owner; } fido = ʺFidoʺ, ʺCanis lupus familiarisʺ}; struct HUMAN char name[name_limit]; struct PET pets[pet_limit]; } sam = ʺSamʺ, fido}}; We can t initialize the owner member at this point, since it was not declared yet 10

11 Member Access } Direct access operator s.m } Subscript ([]) and dot (.) operators have same precedence and associate left-to-right } Parentheses for sam.pets[0].species are not needed } Indirect access s->m: equivalent to (*s).m } Dereference a pointer to a structure, then return a member of that structure } Dot operator has higher precedence than indirection operator, so parentheses are needed in (*s).m (*fido.owner).name or fido.owner->name. evaluated first: access owner member * evaluated next: dereference pointer to HUMAN. and -> have equal precedence and associate left-to-right 11

12 Member Access: Example #include <stdio.h> struct Box int width; int length; int height; }; int main() struct Box b; A period. is used to get to the elements of a struct If x is a struct, x.width is an element in a struct. You can use mixed data types within the struct (int, float, char []) } b.width = 10; b.length = 30; b.height = 10; You can assign values to each member 12

13 Pointers to Structures: Example } To access the members of a struct it must be used: }. for a variable of the struct s type } -> for a pointer to a struct Box b; /* A variable of type Box */ Box *c; /* A pointer to a Box */ double w; b.width = 5; b.height = 7; b.length = 3; c = &b; /* Same as before */ w = c->width; 13

14 More Examples struct bankrecordstruct char name[50]; float balance; }; Access values in a struct using a period:. int main() struct BankRecord newacc; /* create new bank record */ printf( Enter account name: ); scanf( %50s, newacc.name); printf( Enter account balance: ); scanf( %d, &newacc.balance); printf( My balance is: %f\n, newacc.balance); } float bal = newacc.balance; 14

15 Copy via = } You can set two struct type variables equal to each other and each element will be copied int main() struct Box b, c; b.width = 5; b.length = 1; b.height = 2; c = b; // copies all elements of b to c } printf( %d %d %d\n, c.width, c.length, c.height); 15

16 Nested Structures } If structure is nested, multiple. are required struct point int x; int y; }; struct rectangle struct point tl; /* top left */ struct point br; /* bot right */ }; struct rectangle rect; int tlx=rect.tl.x; /*nested*/ int tly=rect.tl.y; 16

17 Structures as Function Arguments } Structures are scalars, so they can be returned and passed as arguments just like ints, chars struct BIG changestruct(struct BIG s); } Call by value: temporary copy of structure is created } Caution: passing large structures is inefficient } Involves a lot of copying! } Avoid by passing a pointer to the structure instead: void changestruct(struct BIG *s); } What if the struct argument is read-only? } Safe approach: use const void changestruct(struct BIG const *s); 17

18 Passing Structures to a Function } Example: passing a struct to a function } All the elements are copied } If an element is a pointer, the pointer is copied but not what it points to! #include <stdio.h> struct card int face; }; void passbyreference(card *c) c->face = 4; } int main(void) Card c; c.face = 1 ; Card *cptr = &c ; // pointer to Card c passbyreference(cptr); #include <stdio.h> struct card int face; }; void passbyvalue(card c) c->face = 4; } int main(void) Card c ; c.face = 1 ; Card *cptr = &c ; // pointer to Card c passbyvalue(*cptr); // no change in c } return EXIT_SUCCESS; } return EXIT_SUCCESS;

19 Typedef } typedef allows to give a name to a custom type } typedef type newname; } Some typedef examples: } typedef int dollars; } typedef unsigned char Byte; } typedef char Names[40]; // special syntax for vectors } typedef double Mat4x4[4][4]; // and arrays } Then it is possible to declare variables as: } dollars d; // same as } Byte b, c; // same as } Mat4x4 mat; // same as double mat[4][4]; 19

20 Using Structs with Typedef typedef struct [NameOfStruct] type member; type member; } TypeName; } NameOfStruct is optional } To declare a variable it is only needed to: } TypeName variable_name; 20

21 Array of Structs } You can declare an array of a structure and manipulate each element typedef struct double radius; int x; int y; char name[10]; } Circle; Circle circles[5]; 21

22 Size of a Structure: SizeOf typedef struct double radius; /* 8 bytes */ int x; /* 4 bytes */ int y; /* 4 bytes */ char name[10]; /* 10 bytes */ } Circle; printf( Size of Circle struct is %d\n, sizeof(circle)); } But sizeof() reports 28 bytes!!! } Most machines require alignment on 4-byte boundary (a word) 22

23 Memory Layout struct COST int amount; char currency_type[2]; } struct PART char id[2]; struct COST cost; int num_avail; } layout of struct PART: currency_type id amount num_avail cost Here, the system uses 4-byte alignment of integers, so amount and num_avail must be aligned Four bytes wasted for each structure! 23

24 Memory Layout A better alternative (from a space perspective): struct COST int amount; char currency_type; } struct PART struct COST cost; char id[2]; int num_avail; } currency_type amount cost id num_avail 24

25 Complex Types: Review } Structures (user-defined combinations of other types) } Enumerations } Unions (same data, multiple interpretations) } Function pointers } Arrays and Pointers of the above 25

26 Enumerations } Basically integers } Can use in expressions like ints } Makes code easier to read } Cannot get string equivalence } Carefully using increment/decrement operators if values are not contiguous 26

27 Enums enum days mon, tue, wed, thu, fri, sat, sun}; // Same as: // #define mon 0 // #define tue 1 //... // #define sun 6 enum days mon=3, tue=8, wed, thu, fri, sat, sun}; // Same as: // #define mon 3 // #define tue 8 //... // #define sun 13 enum days day; // Same as: int day; for(day = mon; day <= sun; day++) if (day == sun) printf("sun\n"); } else printf("day = %d\n", day); } } 27

28 Unions } Like structures, but every member occupies the same region of memory! } Structures: members are and ed together: name and species and owner } Unions: members are xor ed together union VALUE float f; int i; char *s; }; /* either a float xor an int xor a string */ 28

29 Unions } Up to programmer to determine how to interpret a union (i.e. which member to access) } Often used in conjunction with a type variable that indicates how to interpret the union value enum TYPE INT, FLOAT, STRING }; struct VARIABLE }; enum TYPE type; union VALUE value; Access type to determine how to interpret value 29

30 Unions } Storage } Size of union is the size of its largest member } Avoid unions with widely varying member sizes; for the larger data types, consider using pointers instead } Initialization } Union may only be initialized to a value appropriate for the type of its first member 30

31 Unions: Example #include <stdio.h> #include <string.h> union Data int i; float f; char str[20]; }; int main() union Data data; data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str); } return 0; 31

32 To Review } Marques de Sá } Capítulo 8 } Damas } Capítulo 11 } Kernighan and Ritchie } Chapter 6 32

Computer System and programming in C

Computer System and programming in C Computer System and programming in C 1 C structures: aggregate, yet scalar aggregate in that they hold multiple data items at one time named members hold data items of various types like the notion of

More information

Introduction to Programming. Structures

Introduction to Programming. Structures Introduction to Programming Structures Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg We need to compute the volume of a box = height * width * length What is the Problem? What if you need to compute the volume

More information

12 CREATING NEW TYPES

12 CREATING NEW TYPES Lecture 12 CREATING NEW TYPES of DATA Typedef declaration Enumeration Structure Bit fields Uninon Creating New Types Is difficult to solve complex problems by using programs written with only fundamental

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

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

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation

More information

High Performance Computing in C and C++

High Performance Computing in C and C++ High Performance Computing in C and C++ Rita Borgo Computer Science Department, Swansea University Summary Introduction to C Writing a simple C program Compiling a simple C program Running a simple C program

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

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 STRUCTURES STRUCTS Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available

More information

Programming. Elementary Concepts

Programming. Elementary Concepts Programming Elementary Concepts Summary } C Language Basic Concepts } Comments, Preprocessor, Main } Key Definitions } Datatypes } Variables } Constants } Operators } Conditional expressions } Type conversions

More information

Programming in C. What is C?... What is C?

Programming in C. What is C?... What is C? C Programming in C UVic SEng 265 Developed by Brian Kernighan and Dennis Ritchie of Bell Labs Earlier, in 1969, Ritchie and Thompson developed the Unix operating system We will be focusing on a version

More information

Prof. Carl Schultheiss MS, PE. CLASS NOTES Lecture 12

Prof. Carl Schultheiss MS, PE. CLASS NOTES Lecture 12 Prof. Carl Schultheiss MS, PE CLASS NOTES Lecture 12 In addition to the basic data types C supports user-defined data types. Userdefined data types allow the development of programs using data types that

More information

Programming in C UVic SEng 265

Programming in C UVic SEng 265 Programming in C UVic SEng 265 Daniel M. German Department of Computer Science University of Victoria 1 SEng 265 dmgerman@uvic.ca C Developed by Brian Kernighan and Dennis Ritchie of Bell Labs Earlier,

More information

Programming in C. What is C?... What is C?

Programming in C. What is C?... What is C? Programming in C UVic SEng 265 C Developed by Brian Kernighan and Dennis Ritchie of Bell Labs Earlier, in 1969, Ritchie and Thompson developed the Unix operating system We will be focusing on a version

More information

BSM540 Basics of C Language

BSM540 Basics of C Language BSM540 Basics of C Language Chapter 4: Character strings & formatted I/O Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture To explain the input/output functions printf()

More information

Chapter 7: Structuring the Data. Lecture7 1

Chapter 7: Structuring the Data. Lecture7 1 Chapter 7: Structuring the Data Lecture7 1 Topics Introduction to Structures Operations on Structures Using Structures with Arrays Using Structures with Pointers Passing Structures to and from Functions

More information

Lecture10: Structures, Unions and Enumerations 11/26/2012

Lecture10: Structures, Unions and Enumerations 11/26/2012 Lecture10: Structures, Unions and Enumerations 11/26/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Administrative Items Assignment #10 on the course webpage r, long double, etc.

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

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah Lecturer Department of Computer Science & IT University of Balochistan 1 Outline p Introduction p Program development p C language and beginning with

More information

In this session we will cover the following sub-topics: 1.Identifiers 2.Variables 3.Keywords 4.Statements 5.Comments 6.Whitespaces 7.Syntax 8.

In this session we will cover the following sub-topics: 1.Identifiers 2.Variables 3.Keywords 4.Statements 5.Comments 6.Whitespaces 7.Syntax 8. In this session we will cover the following sub-topics: 1.Identifiers 2.Variables 3.Keywords 4.Statements 5.Comments 6.Whitespaces 7.Syntax 8.Semantic www.tenouk.com, 1/16 C IDENTIFIERS 1. Is a unique

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

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

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 10: Review - Structures and Memory Allocation Unions Recap: Structures Holds multiple items as a unit Treated as scalar in C: can be returned from functions, passed to functions

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

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations Fundamentals of Programming Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department

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

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Principles of C and Memory Management

Principles of C and Memory Management COMP281 Lecture 9 Principles of C and Memory Management Dr Lei Shi Last Lecture Today Pointer to Array Pointer Arithmetic Pointer with Functions struct Storage classes typedef union String struct struct

More information

DECLARAING AND INITIALIZING POINTERS

DECLARAING AND INITIALIZING POINTERS DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 11: Bit fields, unions, pointers to functions Cristina Nita-Rotaru Lecture 11/ Fall 2013 1 Structures recap Holds multiple items as a unit Treated as scalar in C: can be

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

ARRAYS(II Unit Part II)

ARRAYS(II Unit Part II) ARRAYS(II Unit Part II) Array: An array is a collection of two or more adjacent cells of similar type. Each cell in an array is called as array element. Each array should be identified with a meaningful

More information

Data Storage. August 9, Indiana University. Geoffrey Brown, Bryce Himebaugh 2015 August 9, / 19

Data Storage. August 9, Indiana University. Geoffrey Brown, Bryce Himebaugh 2015 August 9, / 19 Data Storage Geoffrey Brown Bryce Himebaugh Indiana University August 9, 2016 Geoffrey Brown, Bryce Himebaugh 2015 August 9, 2016 1 / 19 Outline Bits, Bytes, Words Word Size Byte Addressable Memory Byte

More information

C Programming Review CSC 4320/6320

C Programming Review CSC 4320/6320 C Programming Review CSC 4320/6320 Overview Introduction C program Structure Keywords & C Types Input & Output Arrays Functions Pointers Structures LinkedList Dynamic Memory Allocation Macro Compile &

More information

ET156 Introduction to C Programming

ET156 Introduction to C Programming ET156 Introduction to C Programming Unit 1 INTRODUCTION TO C PROGRAMMING: THE C COMPILER, VARIABLES, MEMORY, INPUT, AND OUTPUT Instructor : Stan Kong Email : skong@itt tech.edutech.edu Figure 1.3 Components

More information

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ. C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 10 Structures, Unions, Bit Manipulations and Enumerations Department of Computer Engineering

More information

For each of the following variables named x, specify whether they are static, stack-dynamic, or heapdynamic:

For each of the following variables named x, specify whether they are static, stack-dynamic, or heapdynamic: For each of the following variables named x, specify whether they are static, stack-dynamic, or heapdynamic: a) in C++: int* x = new(int); b) in Java: class book { protected string title; book(string x)

More information

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -STRUCTURE- SPRING 2015 SEON-JU AHN, CNU EE

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -STRUCTURE- SPRING 2015 SEON-JU AHN, CNU EE 공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -STRUCTURE- SPRING 2015 SEON-JU AHN, CNU EE STRUCTURE Structures are collections of related variables under one name. Structures may contain variables of

More information

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Fundamental of C Programming Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Q2. Write down the C statement to calculate percentage where three subjects English, hindi, maths

More information

Structures, Unions Alignment, Padding, Bit Fields Access, Initialization Compound Literals Opaque Structures Summary. Structures

Structures, Unions Alignment, Padding, Bit Fields Access, Initialization Compound Literals Opaque Structures Summary. Structures Structures Proseminar C Grundlagen und Konzepte Michael Kuhn Research Group Scientific Computing Department of Informatics Faculty of Mathematics, Informatics und Natural Sciences University of Hamburg

More information

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE M4.1-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

Lab 3. Pointers Programming Lab (Using C) XU Silei

Lab 3. Pointers Programming Lab (Using C) XU Silei Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions

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

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

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park Variables in C CMSC 104, Fall 2012 John Y. Park 1 Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement 2 What Are Variables in C? Variables in C have the

More information

Procedures, Parameters, Values and Variables. Steven R. Bagley

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

COMPSCI 210 Part II Data Structure

COMPSCI 210 Part II Data Structure Agenda & Reading COMPSCI 210 Part II Data Structure Based on slides @ McGraw-Hill Agenda: Enum structs Nested structs Array of structs structs Parameters & Returning structs structs Pointers Exercises:

More information

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types Chapter 6 Topics WEEK E FOUR Data Types Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference

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

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays EE105: Software Engineering II Part 6 Pointers page 1 of 19 Part VI Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and Arrays 6) Pointers and

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

Structures. Dr. Donald Davendra Ph.D. (Department of Computing Science, Structures FEI VSB-TU Ostrava)

Structures. Dr. Donald Davendra Ph.D. (Department of Computing Science, Structures FEI VSB-TU Ostrava) Structures Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava 1/18 Derived and Structured Data Types basic data type - part of the standard language, preprocessor - without parameters,

More information

EM108 Software Development for Engineers

EM108 Software Development for Engineers EE108 Section 6 Pointers page 1 of 20 EM108 Software Development for Engineers Section 6 - Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and

More information

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan Operating Systems 2INC0 C course Pointer Advanced Dr. Ir. Ion Barosan (i.barosan@tue.nl) Containt Pointers Definition and Initilization Ponter Operators Pointer Arithmetic and Array Calling Functions by

More information

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; }; Structures EECS 2031 25 September 2017 1 Basics of Structures (6.1) struct point { int x; int y; keyword struct introduces a structure declaration. point: structure tag x, y: members The same member names

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

CMPE-013/L. Introduction to C Programming

CMPE-013/L. Introduction to C Programming CMPE-013/L Introduction to C Programming Bryant Wenborg Mairs Spring 2014 Advanced Language Concepts Unions Function pointers Void pointers Variable-length arguments Program arguments Unions Unions Definition

More information

Chapter 21: Introduction to C Programming Language

Chapter 21: Introduction to C Programming Language Ref. Page Slide 1/65 Learning Objectives In this chapter you will learn about: Features of C Various constructs and their syntax Data types and operators in C Control and Loop Structures in C Functions

More information

ESC101N Fundamentals of Computing

ESC101N Fundamentals of Computing ESC101N Fundamentals of Computing Arnab Bhattacharya arnabb@iitk.ac.in Indian Institute of Technology, Kanpur http://www.iitk.ac.in/esc101/ 1 st semester, 2010-11 Tue, Wed, Fri 0800-0900 at L7 Arnab Bhattacharya

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

Structures and Union. Fall Jinkyu Jeong GEBD029: Basis and Practice in Programming Fall 2014 Jinkyu Jeong

Structures and Union. Fall Jinkyu Jeong GEBD029: Basis and Practice in Programming Fall 2014 Jinkyu Jeong Structures and Union Fall 2014 Jinkyu Jeong (jinkyu@skku.edu) 1 Review Bitwise operations You need them for performance in terms of space and time Shifts are equivalent to arithmetics Enumeration you can

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

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER: Page 1 of 8 School of Computer Science 60-141-01 Introduction to Algorithms and Programming Winter 2015 Midterm Examination # 2 Wednesday, March 18, 2015 ANSWERS Duration of examination: 75 minutes STUDENT

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

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

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

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

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

Programming and Data Structures

Programming and Data Structures Programming and Data Structures Teacher: Sudeshna Sarkar sudeshna@cse.iitkgp.ernet.in Department of Computer Science and Engineering Indian Institute of Technology Kharagpur #include int main()

More information

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach C Fundamentals & Formatted Input/Output adopted from KNK C Programming : A Modern Approach C Fundamentals 2 Program: Printing a Pun The file name doesn t matter, but the.c extension is often required.

More information

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types

More information

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables. When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called

More information

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam Multimedia Programming 2004 Lecture 2 Erwin M. Bakker Joachim Rijsdam Recap Learning C++ by example No groups: everybody should experience developing and programming in C++! Assignments will determine

More information

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable

More information

ANSI C Programming Simple Programs

ANSI C Programming Simple Programs ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double

More information

Bit Manipulation in C

Bit Manipulation in C Bit Manipulation in C Bit Manipulation in C C provides six bitwise operators for bit manipulation. These operators act on integral operands (char, short, int and long) represented as a string of binary

More information

Lecture 2: C Programming Basic

Lecture 2: C Programming Basic ECE342 Introduction to Embedded Systems Lecture 2: C Programming Basic Ying Tang Electrical and Computer Engineering Rowan University 1 Facts about C C was developed in 1972 in order to write the UNIX

More information

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS Manish Dronacharya College Of Engineering, Maharishi Dayanand University, Gurgaon, Haryana, India III. Abstract- C Language History: The C programming language

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

Structures, Operators

Structures, Operators Structures Typedef Operators Type conversion Structures, Operators Basics of Programming 1 G. Horváth, A.B. Nagy, Z. Zsóka, P. Fiala, A. Vitéz 10 October, 2018 c based on slides by Zsóka, Fiala, Vitéz

More information

Data Type. structure. C Programming Lecture 11 : Structuret. struct union. typedef. A collection of one or more variables

Data Type. structure. C Programming Lecture 11 : Structuret. struct union. typedef. A collection of one or more variables Data Type C Programming Lecture 11 : Structuret struct union enum typedef structure t A collection of one or more variables possibly of different types, grouped together under a single name. ex) employee

More information

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other

More information

C Language, Token, Keywords, Constant, variable

C Language, Token, Keywords, Constant, variable C Language, Token, Keywords, Constant, variable A language written by Brian Kernighan and Dennis Ritchie. This was to be the language that UNIX was written in to become the first "portable" language. C

More information

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary Pointers 1 2 Outline Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary 3 Computer Memory Revisited Computers store data in memory slots Each slot has an

More information

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CprE 288 Introduction to Embedded Systems Exam 1 Review.  1 CprE 288 Introduction to Embedded Systems Exam 1 Review http://class.ece.iastate.edu/cpre288 1 Overview of Today s Lecture Announcements Exam 1 Review http://class.ece.iastate.edu/cpre288 2 Announcements

More information

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:

More information

COP 3275: Chapter 02. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

COP 3275: Chapter 02. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA COP 3275: Chapter 02 Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA Program: Printing a Pun #include int main(void) { printf("to C, or not to C: that is the question.\n");

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

Compiling and Running a C Program in Unix

Compiling and Running a C Program in Unix CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name

More information

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

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

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng Slide Set 6 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary October 2017 ENCM 339 Fall 2017 Section 01 Slide

More information

Lesson 7. Reading and Writing a.k.a. Input and Output

Lesson 7. Reading and Writing a.k.a. Input and Output Lesson 7 Reading and Writing a.k.a. Input and Output Escape sequences for printf strings Source: http://en.wikipedia.org/wiki/escape_sequences_in_c Escape sequences for printf strings Why do we need escape

More information

Arrays. Systems Programming Concepts

Arrays. Systems Programming Concepts Arrays Systems Programming Concepts Arrays Arrays Defining and Initializing Arrays Array Example Subscript Out-of-Range Example Passing Arrays to Functions Call by Reference Multiple-Subscripted Arrays

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

ECE264 Fall 2013 Exam 3, November 20, 2013

ECE264 Fall 2013 Exam 3, November 20, 2013 ECE264 Fall 2013 Exam 3, November 20, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.

More information