Problem Solving and 'C' Programming

Similar documents
Problem Solving and 'C' Programming

Problem Solving and 'C' Programming

ALQUDS University Department of Computer Engineering

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

Programming in C UVic SEng 265

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

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

IV Unit Second Part STRUCTURES

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Unit 7. Functions. Need of User Defined Functions

Unit IV & V Previous Papers 1 mark Answers

Subject: Fundamental of Computer Programming 2068

C: How to Program. Week /Mar/05

Storage class in C. Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables.

Course Code : MCS-011 Course Title : Problem Solving and Programming Assignment Number : MCA(1)/011/Assign/13 Maximum Marks : 100 Weightage : 25%

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

Fundamentals of Programming Session 12

3.3 Structures. Department of CSE

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

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

C Introduction. Comparison w/ Java, Memory Model, and Pointers

High Performance Computing MPI and C-Language Seminars 2009

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

Binghamton University. CS-211 Fall Variable Scope

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

UNIT - V STRUCTURES AND UNIONS

C Language, Token, Keywords, Constant, variable

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Array Initialization

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS

Programming and Data Structure

COMP 2355 Introduction to Systems Programming

C PROGRAMMING QUESTIONS AND

Syntax and Variables

Programming Language Basics

VARIABLES AND CONSTANTS

TDDB68 Concurrent Programming and Operating Systems. Lecture 2: Introduction to C programming

Basic Elements of C. Staff Incharge: S.Sasirekha

Chapter 1 & 2 Introduction to C Language

Chapter 2 - Introduction to C Programming

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

M1-R4: Programing and Problem Solving using C (JAN 2019)

CS10001: Programming & Data Structures. Dept. of Computer Science & Engineering

Storage class and Scope:

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Binghamton University. CS-211 Fall Variable Scope


Review of the C Programming Language for Principles of Operating Systems

Principles of C and Memory Management

Binghamton University. CS-211 Fall Variable Scope

Introduction to C Language

Structure of this course. C and C++ Past Exam Questions. Text books

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

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

Deccan Education Society s FERGUSSON COLLEGE, PUNE (AUTONOMOUS) SYLLABUS UNDER AUTONOMY. FIRST YEAR B.Sc. COMPUTER SCIENCE SEMESTER I

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

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

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

CSE 303 Lecture 8. Intro to C programming

Quiz 0 Answer Key. Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d. True or False.

PROGRAMMAZIONE I A.A. 2017/2018


C PROGRAMMING Lecture 4. 1st semester

Model Viva Questions for Programming in C lab

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

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Downloaded S. from Kiran, PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from

Structured Programming. Functions and Structured Programming. Functions. Variables

Programming in C and C++

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

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

CE221 Programming in C++ Part 1 Introduction

EL6483: Brief Overview of C Programming Language

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23

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

Course Title: C Programming Full Marks: Course no: CSC110 Pass Marks: Nature of course: Theory + Lab Credit hours: 3

Lecture 03 Bits, Bytes and Data Types

Contents. Custom data type struct data type Fixed length memory Alias data type

Algorithms, Data Structures, and Problem Solving

from Appendix B: Some C Essentials

BSM540 Basics of C Language

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Chapter-14 STRUCTURES

6.096 Introduction to C++ January (IAP) 2009

Tokens, Expressions and Control Structures

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Introduction to C An overview of the programming language C, syntax, data types and input/output

C-LANGUAGE CURRICULAM

Presented By : Gaurav Juneja

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

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

Final CSE 131B Spring 2004

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

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

Fundamentals of Programming Data Types & Methods

Organization of a file

Transcription:

Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 10: Functions/Structure and Unions 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein is subject to change without notice. C3: Protected

About the Author Created By: Jeyshankar Perumal (125623) Credential Information: Version and Date: Technical Skills: UNIX/C/C++/Oracle Experience: 8.5 Years PSC/PPT/1107/1.0 2

Icons Used Questions Tools Hands on Exercise Coding Standards Test Your Understanding Reference Try it Out A Welcome Break Contacts 3

Problem Solving and 'C' Programming Session 10: Overview Introduction: This session discusses about the storage classes, the command line arguments and the structures and it s operation. 4

Problem Solving and 'C' Programming Session 10: Objective Objective: After completing this session you will be able to:» Work with different storage classes in a program» Work with command line arguments» Explain the concept of structures and unions» Declare structure» Initialise structure» Perform operations on structures» Perform operation on structures and arrays» Perform operation on structures and functions 5

Storage Classes Variables in C can be characterized by their data type and storage classes. Data type refers to the type of information represented by a variable and storage classes define its life time and scope. Different storages classes available are:» auto» static» register» extern 6

Storage Classes (Contd.) The scope of the variable (where it can be used), is determined by where it is defined. If it is defined outside of all the blocks, then it has file scope. If a variable is defined in a block (encapsulated with and }), then its scope begins when the variable is defined and ends when it hits the terminating }. This is called block scope. 7

Storage Classes (Contd.) Life time refers to the permanence of a variable, that is, how long the variable will retain its value in memory. Syntax: stor-cls-specifier datatype vble-name,... 8

Automatic Variables: Auto Storage Class Automatic variables are local to the block in which they are declared. Local variables of different functions/blocks may have the same name. It retains its value till the control remains in that block. If not initialized, their initial value will be unpredictable. Stored in Memory. If no storage class is specified, by default it is an auto variable. 9

Automatic Variables: Auto Storage Class (Contd.) Example: main() } int a = 5 ; int a =6 ; printf ( %d, a); /*prints 6*/ } printf( %d, a); /*prints 5*/ 10

Static Variables: Static Storage Class Static variables are also local (visible) to the block in which the variable is declared. They retain the values throughout the life of the program. If not initialized in the declaration, it is automatically initialized to zero. Static variable values are stored in Memory. 11

Static Variables: Static Storage Class (Contd.) Example: main() int i; for (i=1;i<=5;i++) incre(); } incre() static int x = 0; x = x +1; printf( x = %d\n,x); } Output: x = 1 x = 2 x = 3 x = 4 12

Register Variables: Register Storage Class Registers are faster than memory, keeping the frequently accessed variables like a loop control variable in a register will increase the execution speed. Register variables are local (visible) to the block in which they declared. It retains its value till the control remains in that block. If not initialized, the variable is initialized to zero. 13

External Variables: Extern Storage Class External variables are not confined to a single function. Their scope extends from the point of definition through the remainder of the program. They are referred to as global variables. Access to variables outside of their file scope can also be made by using linkage. Linkage is done by placing the keyword extern prior to a variable declaration. This allows a variable that is defined in another source code file to be accessed. 14

External Variables: Extern Storage Class (Contd.) Example: int a = 5 ; /*external variable defination (no need to use extern keyword)*/ void main() extern int b; /*external vble declaration (the vble is declared somewhere else)*/ void fun(); fun(); printf( %d, a); /*prints 10*/ printf( %d, b); /*prints 20*/ } void fun() a = 10 ; } int b = 20; 15

Command Line Arguments A C program is executed by calling its main() function. The main() function is called with one integer argument indicating how many words are in the command line and another argument that is a character array of pointers containing the command line words. 16

Command Line Arguments (Contd.) main ( int argc, char *argv[]) : } argc provides a count of the number of command line arguments. argv is an array of character pointer of undefined size that can be thought of as an array of pointer to strings, which are command line strings. 17

Command Line Arguments (Contd.) Example: main( int argc, char* argv[]) } int i; printf( \n Total No. of Arguments =%d,argc); for( i = 0; i < argc; i++) printf( \narg. No. %d = %s,i, argv[i]); 18

Command Line Arguments (Contd.) When the following command is given in the command prompt, for the above program: C:\tc\bin> CMLPGM c cpp java» Where: CMLPGM is program name c cpp java arguments The following result is displayed: Total No. of Arguments = 4 Arg. No. 0 = CMLPGM Arg. No. 1 = c Arg. No. 2 = cpp Arg. No. 3 = java 19

Introduction to Structures and Unions Structures and Unions are the main constructs available in C through which programmers can define new data type. Structures and unions provide a way to group logically related data items together. 20

Structure The structure is a derived data type used to represent heterogeneous data. A structure is an aggregation of components that can be treated as a single variable. The components are called members. For example, an employee is represented with the following attributes:» employee code (alphanumeric)» employee name (string)» department code (integer)» salary (float) 21

Structure: Declaration Structures are defined via a template and declared with a tag which helps to avoid repeating the definition. struct keyword is used to define structures. struct tag_name type variable-name, variable-name,...; type variable-name, variable-name,...; type variable-name, variable-name,...; : : type variable-name, variable-name,...; }; 22

Structure: Declaration (Contd.) Structure-variables can be declared anywhere in the program. Syntax: struct tag_name new-structure-variable; Example: struct employee int code; char name[20]; int dept_code; float salary; }; struct employee emp1, emp2; 23

Structure: Declaration (Contd.) Structure definition and declaration of structure variables can be combined together. Example: struct employee int code; char name[20]; int dept_code; float salary; } emp1, emp2; Note: Tag name is optional in this case. 24

Structure: Initialization Structure variables can be initialized at the time of declaration If the structure variable is declared before the main function, the member variables are automatically initialized to zero or Null. If it is partially initialized, then uninitialized members will be assigned zero or Null character. 25

Accessing the Members Members of the structure can be accessed by using the member access operator. (dot) Syntax: struct_vble.member-field-name Example: emp1.code emp1.name emp1.dept_code emp1.salary emp2.code emp2.name 26

Operations on Structures Each member of a structure can be assigned to the corresponding member of another structure. Structure can also be assigned to another Structure provided they have the same composition. sizeof() operator can be used to find the size of the structure. 27

Operations on Structures (Contd.) Two structure variables cannot be compared for equality, even though the values stored in the member variables are the same. This is because slack bytes are added in between two member variables and these slack bytes have some garbage value. 28

Nested Structures Structures can contain members that themselves are structures. struct date int day; int month; int year; }; struct employee int code; char name [20]; struct date doj ; int dept_code; float salary; }emp1,emp2; 29

Structures and Arrays The members of structures can be arrays and the structure can also be an array Example: The following example is a array of structures: struct stud int rollnum; char name[20]; int semester; int avg; }; struct stud student[50]; Accessing values: student[1].rollnum, student[1].name, student[1].semester, student[1].avg 30

Arrays Within Structures Example: struct student-mark int rollnumber; char name[15]; int sub_marks[5]; } student; Accessing values: student.sub_marks[0], student.sub_mark[1], student.name 31

Self-Referential Structures A structure containing a member which is a pointer to the same structure type is called self-referential structures. It is used to build various kinds of linked data structures. Example: struct employee char name[20]; char gender; float salary; struct employee *empptr; }; 32

Structures and Functions Structures can be passed to a function using call by value and call by reference methods. By default the structure is passed using call by value approach to a function. For calling by reference, structure should be a array of structures or structure variable should be pointer variable. 33

Structures and Functions (Contd.) Example: Passing structures to a function (call by value): struct emp int empno; char empname[10]; }; void main( ) void display(struct emp); struct emp emp1 = 101, AAAA } ; display(emp1); } void display(struct emp emp2) printf( %d, emp2.empno); printf( %s, emp2.empname); } 34

Structures and Functions (Contd.) Example: Passing structures to a function (call by reference): struct emp int empno; char empname[10]; }; void main( ) void change(struct emp *); struct emp emp1 = 101, AAAA } ; change(&emp1); printf( %d, emp1->empno); /*prints 102*/ } void change (struct emp *emp2) emp2->empno =102; } 35

Q & A Allow time for questions from participants 36

Try it Out: 1 Problem Statement: Write a program to convert given weight in pounds to Imperial and international units 37

Try it Out: 1 (Contd.) Code: #include <stdio.h> void print_converted(int pounds) /* Convert U.S. Weight to Imperial and International Units. Print the results */ int stones = pounds / 14; int uklbs = pounds % 14; float kilos_per_pound = 0.45359; float kilos = pounds * kilos_per_pound; } printf(" %3d %2d %2d pounds, stones, uklbs, kilos); %6.2f\n", main(int argc,char *argv[]) int pounds; Refer File Name : <ses10_1.c> for soft copy of the code 38

Try it Out: 1 (Contd.) Code: if(argc!= 2) printf("usage: convert weight_in_pounds\n"); exit(1); } } sscanf(argv[1], "%d", &pounds); /* Convert String to int */ printf(" US lbs UK st. lbs INT Kg\n"); print_converted(pounds); getchar(); Refer File Name : <ses10_1.c> for soft copy of the code 39

Try it Out: 1 (Contd.) How it Works: This program explains how to use command line arguments. While running the program pass the weight which needs to be converted in to different units as input argument Read the command line argument, convert the pound in to different units by applying formula. Print the values on the screen 40

Try it Out: 2 Problem Statement: Write a program to store values in a structure and pass the structure to a function and print the values on the screen 41

Try it Out: 2 (Contd.) Code: #include <stdio.h> struct s_type int i; double d; } var1; void f(struct s_type temp); void main(void) var1.i=99; var1.d = 98.6; f(var1); getchar(); } void f(struct s_type temp) printf("%d %1f", temp.i, temp.d); } Refer File Name : <ses10_2.c> for soft copy of the code 42

Try it Out: 2 (Contd.) How it Works: In this program, declare a structure comprising of two different data type members Assign values to each member of a structure. Pass the structure in a function, where it access each member of structure and print it on the screen 43

Q & A Allow time for questions from participants 44

Test Your Understanding 1. State whether the following statements are True or False: a) The tag name of a structure is optional. b) Structures may contain members of only one data type. c) Structure members will share the memory locations. 2. Write a Program to perform basic banking operations using array of structures. 45

Problem Solving and 'C' Programming Session 10: Summary C supports four storage class specifiers (auto, static, extern, and register) to define scope and life time for the variable. The command line arguments argc, argv are used to pass arguments to main() function. Structure is a derived data type which is used to store heterogeneous data items under a single unit. Structure members can be accessed by structure variables using dot operator. Structures can be nested and can have self reference also. Structure can be passed to a function by both call by value approach and call by reference approach. 46

Problem Solving and 'C' Programming Session 10: Source C Reference Card (ANSI) C Reference Manual by Dennis Ritchie Programming in C: A Tutorial by Brian W. Kernighan, Bell Laboratories Byron Gottfried, Programming in C, Tata McGraw Hill Deitel & Deitel, C How to Program, Third Edition, Prentice Hall Disclaimer: Parts of the content of this course is based on the materials available from the Web sites and books listed above. The materials that can be accessed from linked sites are not maintained by Cognizant Academy and we are not responsible for the contents thereof. All trademarks, service marks, and trade names in this course are the marks of the respective owner(s). 47

You have completed the Session 10 of Problem Solving and 'C' Programming 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein is subject to change without notice.