KARMAYOGI ENGINEERING COLLEGE, Shelve Pandharpur

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

Work relative to other classes

HISTORY OF C LANGUAGE. Facts about C. Why Use C?

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

Computers Programming Course 5. Iulian Năstac

Fundamental of Programming (C)

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

UNIT- 3 Introduction to C++

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

Computers Programming Course 6. Iulian Năstac

C Language, Token, Keywords, Constant, variable

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

Full file at

Basics of Programming

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

DEPARTMENT OF MATHS, MJ COLLEGE

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

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

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

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

6.096 Introduction to C++ January (IAP) 2009

C: How to Program. Week /Mar/05

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

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Introduction to C Language

Preview from Notesale.co.uk Page 6 of 52

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C - Basic Introduction

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Unit. Programming Fundamentals. School of Science and Technology INTRODUCTION

Chapter 2 - Introduction to C Programming

Fundamental of C programming. - Ompal Singh

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

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Computer Programming : C++

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Tutorial No. 2 - Solution (Overview of C)

Chapter 1 Introduction to Computers and C++ Programming

Course Outline Introduction to C-Programming

Chapter 1 & 2 Introduction to C Language

Operators. Java operators are classified into three categories:

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

Unit 4. Input/Output Functions

Data Types and Variables in C language

C++ character set Letters:- A-Z, a-z Digits:- 0 to 9 Special Symbols:- space + - / ( ) [ ] =! = < >, $ # ; :? & White Spaces:- Blank Space, Horizontal

Multiple Choice Questions ( 1 mark)

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

Fundamentals of Programming

Basics of Java Programming

The C language. Introductory course #1

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Chapter 3: Operators, Expressions and Type Conversion

Programming for Engineers Introduction to C

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

A Fast Review of C Essentials Part I

CCE RR REVISED & UN-REVISED KARNATAKA SECONDARY EDUCATION EXAMINATION BOARD, MALLESWARAM, BANGALORE G È.G È.G È..

INTRODUCTION 1 AND REVIEW

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Differentiate Between Keywords and Identifiers

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

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

Basic Elements of C. Staff Incharge: S.Sasirekha

Java Notes. 10th ICSE. Saravanan Ganesh

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Chapter 17. Fundamental Concepts Expressed in JavaScript

Maciej Sobieraj. Lecture 1

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Language Reference Manual simplicity


DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

BITG 1233: Introduction to C++

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Lexical Considerations

ANSI C Programming Simple Programs

C++ Programming: From Problem Analysis to Program Design, Third Edition

BASIC ELEMENTS OF A COMPUTER PROGRAM

Introduction to C. History of C:

Lecture 2 Tao Wang 1

Operators and Expressions:

Lecture 3. More About C

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

Computer programming & Data Structures Unit I Introduction to Computers

Objectives. In this chapter, you will:

Presented By : Gaurav Juneja

Lexical Considerations

Reserved Words and Identifiers

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Class B.Com. III Sem.

CS102: Variables and Expressions

Transcription:

KARMAYOGI ENGINEERING COLLEGE, Shelve Pandharpur Bachelor of Engineering First Year Subject Name: Computer Programming Objective: 1. This course is designed to provide a brief study of the C programming language and its concepts. 2. It stresses the strengths of C, which provide students with the means of writing efficient, maintainable, and portable code. 3. The nature of C language is emphasized in the wide variety of examples and applications. 4. To learn and acquire art of computer programming. 5. To know about popular programming languages and how to choose Programming language for solving various engineering problems. Outcomes: 1. Student will acquire basic knowledge of computers and will be able to use the programming skills acquired to build programs for simple applications 2. Understand the basic terminology used in computer programming. 3. Write, compile and debug programs in C language. 4. Use different data types in a computer program. 5. Design programs involving decision structures loops and functions. 6. Explain the difference between call by value and call by reference 7. Understand the dynamics of memory by the use of pointers. 8. Use different data structures and create/update basic data files. FE- II [Computer Programming] Mr. Dipak V Bhosale 0

Index Unit Chapter Name Page No. Unit 1 a) Fundamental of Computer 2 b) Structure of C program 10 Unit 2 Programming Control 30 Unit 3 Array and String 49 Unit 4 a) Structure and Union 56 b) Function 61 Unit 5 Basics of Pointers 69 Programs FE- II [Computer Programming] Mr. Dipak V Bhosale 1

Unit I A) Fundamental of Computers 1.1 Block diagram of Computer with description: 1. Computer: Computer is an electronic device for processing information and performing calculations; follows a program to perform sequences of mathematical and logical operations. Computer can also be defined in terms of functions it can perform. 2. A computer can i) accept data, ii) store data, iii) process data as desired, and iv) retrieve the stored data as and when required and v) print or store the result in desired format. 3. The major characteristics of a computer are high speed, accuracy, diligence, versatility and storage. 4. The block diagram of computer is shown in Figure 1.1 Figure 1.1 The block diagram of Computer 5. Input device: Computer need to receive data and instructions in order to solve the problems. So, we need to input the data and instructions into the computer. So the solution is input device. FE- II [Computer Programming] Mr. Dipak V Bhosale 2

The input device consists of one or more input devices such as keyboard, mouse, Light Pen, Optical Scanner, Touch Screen, Microphone for voice as input, Track Ball, Scanner, Camera, etc. 6. Central Processing Unit (CPU): 1) Storage Unit: It holds the data and instructions that are entered through the input unit, before they are processed. It preserves the intermediate and final results before these sent to the output unit. It also saves the data for the later use. Two types: 1) Primary Memory ex. Read Access Memory (RAM), etc. 2) Secondary Memory. Ex. Hard disk, memory card, etc 2) Arithmetic Logic Unit (ALU): All calculation operations are performed in ALU of the computer. It also does comparison and takes decision. 3) Control Unit: It controls all other units in the computer. The process of input, output, processing and storage is performed under the supervision of a unit called 'Control Unit'. 7. Output Unit: The output unit of a computer provides the information and results of a computation to user. Output devices such as printer, hard disk, monitor, speakers etc. Important terms about Computer: Software: As you are aware, computer cannot do anything on its own. It is the user who instructs computer; what to do, how to do and when to do. In order to perform any task, you have to give a set of instructions in a particular sequence to the computer. These sets of instructions are called Programs. Software refers to a set of programs that makes the hardware perform a particular set of tasks in particular order. Software can be classified mainly into following categories and sub-categories are shown below in Figure 1.2. FE- II [Computer Programming] Mr. Dipak V Bhosale 3

Figure 1.2 Software Types with examples Computer Languages: Languages are a means of communication. Normally people interact with each other through a language. On the same pattern, communication with computers is carried out through a language. This language is understood both by user and the machine. Just as every language like English, Hindi has its grammatical rules; every computer language is bound by rules known as SYNTAX of that language. The user is bound by that syntax while communicating with the computer system. Computer languages are broadly classified as: 1] Low Level Language: The term low level means closeness to the way in which machine understand. The low level languages are: A. Machine Language: This is the language (in the form of 0 s and 1 s, called binary numbers) understood directly by the computer. It is machine dependent. It is difficult to learn and even more difficult to write programs. B. Assembly Language: This is the language where the machine codes comprising of 0 s and 1 s are substituted by symbolic codes (called mnemonics) to improve their understanding. It is the first step to improve programming structure. Assembly language programming is simpler and less time consuming than machine level programming, it is easier to locate and correct errors in assembly language than in machine language programs. It is also machine dependent. Programmers must have knowledge of the machine on which the program will run 2] High Level Language: You know that low level language requires extensive knowledge of the hardware since it is machine dependent. To overcome the limitation, high level language has been evolved which uses normal English like, easy to understand statements to solve any problem. Higher level languages are computer independent and programming becomes quite easy and simple. Ex. C, C++, Java, Perl, Python, Visual Basic, Matlab, etc. FE- II [Computer Programming] Mr. Dipak V Bhosale 4

1.2 Algorithm: 1. An algorithm is a step-by-step procedure of solving a problem. The problem can be anything, 2. An algorithm is a sequence of computational steps that transform the input into the output. Figure 1.3 Algorithm Operations 3. An algorithm is finite set of instructions/statements, each of which has clear meaning and can be executed in finite amount of time with finite amount of effort to transform input(s) into desired output(s). 4. An algorithm can be represented in any way in either a specific programming language or a pseudo code or a flow chart or even control tables. 1.2.1 Characteristics of algorithm: Following are the characteristics of an algorithm as, 1. Input: An algorithm is supplied with zero or more external quantities as input. 2. Output: An algorithm must produce one or more results/outputs. 3. Clearly defined steps: Each step in an algorithm must be clear. So, one who is following the steps to take a definite action. 4. Finiteness: An algorithm must halt. Hence it must have finite number of steps. 5. Effectiveness: Every instruction must be sufficiently basic. The algorithm creation is a logical task. It requires logic development and cannot be done automatically. It requires various considerations so as to develop an algorithm that is better and efficient. 1.2.2 Sequence: 1. Most of the basic programs just require doing a sequence of step of operations so as to implement the given task. 2. In this case no statements of the algorithm are to be repeated for multiple times. 3. The statements in the algorithm are to be executed without skipping any based on certain condition to be true or false. Let s see some examples, Algorithm 1: Write an algorithm to display a statement Hello World! Step I: Display the sentence Hello World! Step II: Stop. FE- II [Computer Programming] Mr. Dipak V Bhosale 5

Algorithm 2: Write an algorithm to accept a number and display its square. Step I: Indicate user to enter the input number by displaying suitable sentence. Step II: Wait for the user to enter the number. Step III: Calculate the square of the user entered number Step IV: Display the calculated square result. Step V: Stop. Algorithm 3: Write an algorithm to accept a two numbers and display its product. Step I: Indicate user to enter the input numbers by displaying suitable sentence. Step II: Wait for the user to enter the two numbers. Step III: Calculate the product of the user entered number Step IV: Display the calculated product result. Step V: Stop. 1.2.3 Selection: 1. In many programs made for the actual use, a lot of statements are to be repeated for multiple times. 2. In this case instead of writing the statements for multiple times and increasing the algorithm size, it is preferable to write the statements once and execute them multiple times hence saving memory space. 3. Also in many some programs, we require to selectively execute certain statements of an algorithm while skip some of them. These are called as selective statements in an algorithm. Let s see some examples Algorithm 1: Write an algorithm to display the word C Programming 10 times. Step I: Initialize a variable as a Counter with initial value as 1. Step II: Check if the counter variable is greater than 10, if yes, then goto step VI Step III: Display the word C Programming Step IV: Increment the Counter. Step V: Goto step II. Step VI: Stop. Algorithm 2: Write an algorithm to display the first 5 natural numbers. Step I: Initialize a variable as a Counter with initial value as 1. Step II: Check if the counter variable is greater than 5, if yes, then goto step VI Step III: Display the value of counter variable. Step IV: Increment the Counter. Step V: Goto step II. Step VI: Stop. FE- II [Computer Programming] Mr. Dipak V Bhosale 6

1.3 Flowchart: 1. A flowchart is a graphical representation of the algorithm. 2. A flowchart is a schematic representation of an algorithm or a stepwise process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. 3. Flowcharts are used in designing or documenting a process or program. 4. A flow chart, or flow diagram, is a graphical representation of a process or system that details the sequencing of steps required to create output. 1.3.1 Advantages of Using Flowcharts: The benefits of flowcharts are as follows: 1. Communication: Flowcharts are better way of communicating the logic of a system to all concerned. 2. Effective analysis: With the help of flowchart, problem can be analyzed in more effective way. 3. Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes. 4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase. 5. Proper Debugging: The flowchart helps in debugging process. 6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part 1.3.2 The symbols of Flowcharts: Figure 1.4 Symbols of Flowchart FE- II [Computer Programming] Mr. Dipak V Bhosale 7

Some examples of flowchart: Flowchart 1: Draw a flowchart to add to two numbers. As, shown in Figure 1.5, 1) Initially two numbers are accepted from the user, this is shown using parallelogram. 2) These two numbers are then added, as shown using a rectangle. 3) The result is displayed using a parallelogram. 4) The terminal steps are shown with help of oval shape. Figure 1.5 Flowchart 1 Flowchart 2: Draw a flowchart to display the first n natural numbers. In this flowchart as shown in Figure 1.6, 1) The value of variable say n is taken from user. 2) Another variable is initialized to the value 1. The value of counter variable is checked. 3) If the value of counter variable is less than or equal to the value of variable n ; then the counter variable value is displayed and is incremented. 4) Then the couter variable value is againg checked. This process keeps on repeating until the counter value crosses the value of n, after which the algorithm stops. FE- II [Computer Programming] Mr. Dipak V Bhosale 8

Figure 1.6 Flowchart 2 FE- II [Computer Programming] Mr. Dipak V Bhosale 9

Unit I 2.1 Introduction of C program: 2.1.1 History of C program: B) Structure of C Program Dennis Ritchie Dennis Ritchie originally developed C at Bell Telephone Laboratories, Inc (now AT&T Bell Laboratories) in 1970's. It is an outgrowth of the two earlier languages, called BCPL and B, which were also developed at Bell Laboratories. C was largely confined for use within Bell Laboratories until 1978, when Brian Kernighan and Ritchie published a definitive description of the language. 2.1.2 Features and Use of C program: 1. C is general purpose structured programming language. 2. C is powerful and flexible language which helps system developers to deliver various complex tasks/operations. 3. C is portable language. Portable means that a C program written for one computer system can be complied and run on another system with little or no modification. 4. Program written in C are very efficient and fast. This is due to its variety of data types and powerful operators 5. Writing C program with user-defined functions makes program more simple and easy to understand. 6. C language has ability to extend itself. We can add our own functions to existing C library functions. 7. C allows manipulation of data at the lowest level. i.e. bit level manipulation. 8. C was initially used for system development work, in particular the programs that make up the operating system. 9. C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. 10. C is case sensitive and robust language. Due all these features and uses, C is excellent choice for your first programming language. 2.2 Structure of C program: 1. Every C program consists of one or more functions, one of, which must be called main. Additional function definitions may precede or follow the main function. 2. It is compulsory to create a main function without which the program would not run in the desired manner. FE- II [Computer Programming] Mr. Dipak V Bhosale 10

3. Each function must contain: [1] A function heading, which consists of the function name, followed by an optional list of arguments enclosed in parentheses. [2] A list of argument declarations, if arguments are included in the heading. [3] A compound statement, which comprises the remainder of the function. 4. The arguments are symbols that represent information being passed between the function and other parts of the program. (Arguments are also referred to as Parameters.) 5. Each compound statement is enclosed within a pair of braces, i.e.,. The braces may contain combinations of elementary statements (called expression statements) and other compound statements, thus, compound statements may be nested, one within another. 6. Each expression statement must end with a semi-colon (;). 7. Comments (remarks) may appear anywhere within a program, as long as they are placed within the delimiters /* and */. Example: /* this is a comment for understanding purpose only */. Such comments are helpful in identifying the program's principal features or in explaining the underlying logic of various program features. 2.3 Building blocks of C program: 2.3.1 Preprocessor: 1. In most programs the first line of program is used to link the C library file into the program before the compilation start. 2. Most of the time preprocessor is used to tells the C complier to include library files before going to actual compilation. 3. For example, the first line of the program #include<stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation. 2.3.2 Compilation: 1. Computer understands only 0 and 1 i.e. machine level language. Complier converts C language code which into the machine level. 2. The source code written in source file is the human readable source for your program. 3. It needs to be "compiled", to turn into machine language so that your CPU can actually execute the program as per instructions given. 4. If any logical error or syntactical error present in the program then complier shows the error message or warning message including the lines which contains errors. 2.3.3 Execution: Figure 2.1 Execution process of C program FE- II [Computer Programming] Mr. Dipak V Bhosale 11

1. This C programming language compiler will be used to compile your source code into final executable program. 2. There are general steps for execution of the program as follows, i) Creating C program save it with.c extension ii) Compiling the program iii) Linking the program with function iv) Executing the program 3. The execution of program is done by Operating System. After compiling the source code of C program it is called object code. 4. After linking the object code with system library it is called as executable code. Figure 2.2 How Operating System provides memory for C program to execute the program with the help Data and Code Segment on RAM? 2.4 C Character Set: To write a program in C the users are allowed to use following set of characters. uppercase letters A to Z, lower-case letters a to z, digits 0 to 9, certain special characters given below! * + \ " < # ( ) = > % ~ ; / ^ - [ :,? & _ ] '. (blank) Most versions of the language also allow certain other characters, and also @, $, which are included within strings and comments. FE- II [Computer Programming] Mr. Dipak V Bhosale 12

2.5 C tokens: 1. Token is nothing but which is serving as a sign of something else. 2. A C program consists of various tokens and a token is a keyword, an identifier, a constant, a string literal, or a symbol. 3. For example, the following C statement consists of five tokens: printf("hello, World! \n"); a. printf b. ( c. "Hello, World! \n" d. ) e. ; 2.6 Keywords and Identifiers: 1. Keywords are special words which are reserved by C compiler. 2. The following list shows the reserved words in C. These reserved words may not be used as constant or variable or any other identifier names. Table 2.1 Keyword of C Program still many more 3. C Identifier is a name used to identify a variable, function, or any other user-defined item. 4. Rules for defining the identifiers: [1] An identifier starts with a letter [A-Z] or [a-z] or an underscore _ [2] Identifiers followed by zero or more letters, underscores, and digits [0-9]. [3] C does not allow punctuation characters such as @, $, and % within identifiers. [4] Identifiers should not be keywords of the C programming. [5] C is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in C. 5. Here are some examples of acceptable identifiers: Dip kec abc move_name a_123 myname50 _temp j a23b9 retval FE- II [Computer Programming] Mr. Dipak V Bhosale 13

2.7 Variables: 1. A variable is an identifier that is used to represent some specified type of information which is actually a name given to a storage area that our programs can manipulate. 2. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. 3. A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows: type variable_list; Here, type must be a valid C data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. 2.7 Constants: Figure 2.3 Constant Hierarchies in C 1. The constants refer to fixed values that the program may not alter during its execution. 2. It is mainly of two kinds primary and secondary 3. Primary constant further divided into two kinds as Numeric which contains Integer (int) and Real (float) and Nonnumeric (char). 4. Secondary constant are such as Arrays, Pointer, Structure and Union which are derived constants. 5. Integer Constants is an integer-valued number. Thus it consists of a sequence of digits. Integer constants can be written in three different number system; decimal (base 10), octal (base 8) and hexadecimal (base 16). Example, int a = 10; // base 10 FE- II [Computer Programming] Mr. Dipak V Bhosale 14

int a = 0FF; // base 16 6. A real or floating-point constant is a base-10 number that contains either a decimal point or an exponent (or both). Several valid floating-point constants are shown below, Example, float a= 0, 1, 45.60, 0.00045, 5000, 314.16009; 7. A character constant is a single character, enclosed in apostrophes (single quotation marks). Several character constants are shown below. Example, char c = A ; char s = C Programming ; 8. We will see the secondary constant in further chapters. Escape Sequences: Certain non-printing characters, as well as the double quote ("), the apostrophe (') the question mark (?) And the backward slash (\), can be expressed in terms of escape sequences. An escape sequence always begins with a backward slash and is followed by one or more special characters. For example Character Escape Sequence bell (alert) \a backspace \b horizontal tab \t vertical tab \v newline (line feed) \n form feed \f carriage return \r quotation mark (") \" apostrophe (') \' question mark (?) \? backslash (\) \\ null \0 2.8 Primitive Data Types: 1. C supports several different types of data, each of which may be represented differently within the computer's memory. The basic data types are listed below along with the typical memory requirements. Data Types Description Typical Memory Requirements int integer quantity 2 bytes ( varies from one compiler to another) char single character 1 byte float floating-point 4 bytes (i.e. a number containing a number Decimal point and/or an exponent) double double-precision 8 bytes point number (i.e. more floating significant figures, and an exponent which may be Larger in magnitude) 2. C compilers that are written for personal computers or small minicomputers (i.e., computers whose size is less than 32 bits) generally represent a word as 4 bytes (32 bits). FE- II [Computer Programming] Mr. Dipak V Bhosale 15

3. Using the data type qualifiers like short, long, signed, unsigned, etc can enlarge scope of some basic data types. For example, Integer quantities can be defined as short int, long int or unsigned int, these data types are usually written simply as short, long or unsigned, and are understood to be integers. 4. The char type is used to represent individual characters. Hence, the char type will generally require only 1 byte of memory. Each char type has an equivalent integer interpretation, however, so a char is a really a special kind of short integer. 5. The qualifier long may be applied to float or to double, for example, long float or long double. Long float may be equivalent to double. Moreover, long double may be equivalent to double, or it may refer to a separate, "extra-large", double-precision data type requiring more than 2 words of memory. 6. Every identifier that represents a number or a character within a C program must be associated with one of the basic data types before the identifier appears in an executable statement. 7. A C program may contain the following type declaration statements: int a, b, c; float root1, root2; char f_name; 2.9 C Operators: 1. An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. 2. C language is rich in built-in operators. 3. These operators fall into several categories like Arithmetic Operators, Unary Operators, Relational Operators, Assignment Operators and Conditional Operators. 4. All these operators can be used to form expressions. The data items on which operators act are called operands. 2.9.1 Arithmetic Operator: 1. There are 5 arithmetic operators in C. Operator Action - Subtraction, also unary minus + Addition * Multiplication / Division % Modulo Division (gives remainder) 2. The operator % is also called as the modulus operator. The precedence of the arithmetic operators can be seen from the Precedence Table FE- II [Computer Programming] Mr. Dipak V Bhosale 16

3. The Computer evaluates the operators that are on the same precedence level from left to right, but parentheses may be used to alter the order of evaluation. 4. Following table shows all the arithmetic operators supported by C language with example. Assume variable A holds 10 and variable B holds 20, Table 2.1 Arithmetic Operator with example #include <stdio.h> main() int a = 21; int b = 10; int c ; c = a + b; printf("line 1 - Value of c is %d\n", c ); c = a - b; printf("line 2 - Value of c is %d\n", c ); c = a * b; printf("line 3 - Value of c is %d\n", c ); c = a / b; printf("line 4 - Value of c is %d\n", c ); c = a % b; printf("line 5 - Value of c is %d\n", c ); Output of Program will be as, Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of c is 2 Line 5 - Value of c is 1 2.9.2 Unary Operator: Most of the operators require two operands but C provides us with certain operators that act upon only one operand. Such operators are called Unary operators. Unary minus (-) 1. Unary Minus is the most common unary operator that precedes a numerical variable or a constant. 2. Unary minus returns the negative of its operand when the operand it is a signed quantity. FE- II [Computer Programming] Mr. Dipak V Bhosale 17

3. Example, a=12 b=-a The value of b is exactly the negative of a i.e. b= - 12. 4. The operation of unary operator minus is different from the arithmetic operator minus (-) which denotes subtraction. 5. The arithmetic operator requires two operands whereas unary operator requires only one operand. Increment and Decrement: Increment Operator The increment operator adds 1 to its operand. Operator Description Syntax ++ Increment ++Operand OR Operand++ Example ++A or A++ the expression will increment the value of A The sub-expression ++A increments the value of the variable A before execution. The subexpression A++ increments the value of the variable of A after execution. Decrement Operator The decrement operator subtracts 1 from its operand. Operator Description Syntax -- Decrement --Operand OR Operand-- Example --A or A-- The expression will decrement the value of A The sub-expression --A decrements value of the variable A before execution. The subexpression A-- decrements the value of the variable of A after execution. Increment and decrement operators can only be applied to single variable LVALUES. The following program shows the use of increment and decrement operators. main() int A=4; printf("the value of A before execution is %d " A++); printf("the value of A after execution is %d " A); printf("the value of A before execution is %d " ++A); printf("the value of A after execution is %d " A); printf("the value of A before execution is %d " A--); printf("the value of A after execution is %d " A); printf("the value of A before execution is %d " --A); printf("the value of A after execution is %d " A); FE- II [Computer Programming] Mr. Dipak V Bhosale 18

Output of the program as, The value of A before execution is 4 The value of A after execution is 5 The value of A before execution is 6 The value of A after execution is 6 The value of A before execution is 6 The value of A after execution is 5 The value of A before execution is 4 The value of A after execution is 4 It will display the value of the variable A with different combinations of increment and decrement operators. 2.9.3 Binary Operator: 1. A binary operator is an operator that operates on two operands and manipulates them to return a result. 2. Operators are represented by special characters or by keywords and provide an easy way to compare numerical values or character strings. 3. Binary operators are presented in the form: Operand1 Operator Operand2. 4. Example of binary operator is Equal (==), Not equal (!=), Less than (<), Logical AND (&&), Logical OR ( ), Plus (+), Multiplication (*), etc which requires two Operands. 2.9.4 Ternary (Conditional operator): 1. The Ternary Operator also referred to as a conditional operator can be used to carry out certain simple conditional operations. 2. A ternary operator operates on three operands rather than 1 or 2. It is represented by a?: (a question mark followed by a colon). 3. The syntax is: Expression1? Expression2: Expression3 4. The expression1 is first evaluated as a Boolean expression. It is a sort of a switch and determines which of the two-expression expression2 or expression3 is to be returned. 5. This is similar to the way and if statement determines which of the two statements will be executed. 6. If the value of exp1 is True, the value returned by the? : Operator is that of the exp2, located after the? Symbol but before the : symbol. If exp1 evaluates to False, the value returned is that of exp3. 7. Example B = (C >= 0)? C : -C; This expression assigns the absolute value of the variable C to variable B. 2.9.5 Logical Operator: 1. Logical operators are used to combine two or more relations. 2. There are 3 logical operators available in C viz. AND, OR, and NOT. Operator Action OR- False when both conditions are False && AND- True if all conditions are True! NOT- Negative Condition FE- II [Computer Programming] Mr. Dipak V Bhosale 19

#include <stdio.h> main() int a = 5; int b = 20; int c ; if ( a && b ) printf("line 1 - Condition is true\n" ); if ( a b ) printf("line 2 - Condition is true\n" ); /* lets change the value of a and b */ a = 0; b = 10; if ( a && b ) printf("line 3 - Condition is true\n" ); else printf("line 3 - Condition is not true\n" ); if (!(a && b) ) printf("line 4 - Condition is true\n" ); Output of program as, Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is not true Line 4 - Condition is true 2.9.6 Relational Operator: 1. In C any value other than zero is considered to be True while zero (0) is considered False. 2. Expressions that use relational or logical operators will return 0 for False and 1 for True. 3. There are four relational operators and two equality operators closely related to them. Operator Action Relational: > Greater than >= Greater than or equal to < Less than <= Less than or equal to Equality!= Not equal to == Equal to FE- II [Computer Programming] Mr. Dipak V Bhosale 20

4. All the relational operators fall into same group of precedence whereas the equality operators fall in a precedence group beneath the relational operators. 2.9.7 Assignment Operator: 1. C provides the user with various types of assignment operators. 2. All of them are used to form assignment expression which assigns the value of an expression to an identifier. 3. The most commonly used assignment operator is =. Table 2.2 Assignment Operator with example 2.9.8 Bitwise Operator: 1. For the manipulation the data at bit level, bitwise operator is used. 2. Computer understands only machine code i.e. 0 and 1 but the program which understands by the user written in high level language. 3. Computer converts high level language to machine level language. Operator Function ~ Bitwise NOT Bitwise OR & Bitwise AND ^ Bitwise XOR FE- II [Computer Programming] Mr. Dipak V Bhosale 21

Examples : Consider 26 and 9 which are represented in their binary forms as 26 = 0 0 0 1 1 0 1 0 9 = 0 0 0 0 1 0 0 1 respectively. NOT 26 will be 1 1 0 0 1 0 1 which is equal to 229. 26 9 = 27 26 & 9 = 8 2.9.9 Sizeof(): 0 0 1 1 0 1 1 0 0 0 0 1 0 0 0 1. C includes the compile-time operator called sizeof that returns the size of the variable or type that is its operand. 2. The keyword sizeof precedes the operand's variable or type name. If sizeof operates on a data type, then the type must appear in parentheses. 3. Example, sizeof(int) Returns the value 2 or whatever is the number of bytes required to store an integer. 2.10 Operator Precedence and Expressions: The hierarchy of operator precedence and the associativity i.e. (the order in which operators falling in same precedence category will execute) is show in the following table: Operator Class Operators Associativity Unary operators - ++ --! sizeof(type) R --> L Arithmetic multiply,divide,rem. * / % L --> R Arithmetic add,subtract + - L --> R Relational operators < <= > >= L --> R Equality operators ==!= L --> R Logical and && L --> R Logical or L --> R Ternary operator?: R --> L Assignment operators = += -= *= /= %= R --> L FE- II [Computer Programming] Mr. Dipak V Bhosale 22

We can always change the precedence order of any operation by including them within parentheses. Expression: 1. An expression represents a single data item, such as a number or a character. The expression may consist of a single entity, such as a constant, a variable, an array element or a reference to a function. 2. It may also consist of some combination of such entities interconnected by one or more operators. 3. Expressions can also represent logical conditions that are either true or false. However, in C the conditions true and false are represented by the integer values 1 and 0, respectively. 4. Several examples are shown below. a + b x = y c = a + b x <= y x == y ++i 2.11 Type Casting and Type Conversion 1. The data type of any variable can be changed temporarily using the Cast operator. 2. Sometimes the need arises that we may need a decimal part from a division operation and in such situations we can use the Cast operator. 3. It only converts the type of the variable temporarily and does not actually change its type. 4. Its effect remains only for that particular operation. 5. The Cast operator is also referred to as the (type) operator. The below mentioned Program will help us to understand the use of Cast operator. main() int a=10,b=3; printf("the answer of integer division is %d ",a/b); printf("the answer of floating division is %f ",(float)a/b); 6. The above program will print two results : 1) A result of the integer division (int)10/(int)3 and 2) A result of floating division (float)a/b 7. The first line of the program will print normal integer division as its output. The second statement first converts the integer type variable a to float and performs the operation. The output is then the quotient of the floating division operation. The output of the above program will be as follows: The answer of integer division is 3 The answer of floating division is 3.3333 FE- II [Computer Programming] Mr. Dipak V Bhosale 23

2.12 Formatting Input and Output: 1. A program without any input and output has no meaning. 2. In general program reads input data from keyboards or other files. Then program process the input and displays the output on screen. 3. The important aspect of C programming language is its ability to handle input and output (I /O). Some of the inputs, output function are printf, scanf, getchar, putchar etc. 2.12.1 printf: 1. The printf function is used to display the value to the output devices It moves data from the computer s memory to the standard output devices. 2. Syntax: printf( format specifier, arg1, arg2,.arg n ); Format specifier - control string arg1, arg2, arg n - variables or values 3. Format Specifier: %d int %f float %c char %s string #include<stdio.h> main() float num1; int num2=10, num3; num1=1.33; num3=5; printf( \n the value of num1 is %f, num1); printf( \n the value of num2 is %d, num2); printf( \n the value of num3 is %d, num3); return 0; Output: the value of num1 is 1.33 the value of num2 is 10 the value of num3 is 5 2.12.2 scanf: 1. The scanf function gets data from the standard input device and stores it in the computer memory. 2. Sysntax: scanf( format specifier, & arg1, & arg2,.,& argn ) ; Format specifierı is the control string to denote the data type of variable & arg1, & arg2,.,& argn are the variables which stores values. FE- II [Computer Programming] Mr. Dipak V Bhosale 24

3. Format Specifier: %d int %f float %c char %s string #include<stdio.h> void main() int num1, num2, total; printf( \n Enter the first numer ); scanf( %d, &num1); printf( \n Enter the second numer ); scanf( %d, &num2); total=num1+num2; printf( \n Sum of two number= %d, total); output: Enter the first numer 10 Enter the second numer 20 Sum of two number = 30 2.12.3 getchar: 1. The getchar function is a part of input / output function of C programming language. 2. It reads a single character from the standard input device. 3. Syntax: getchar() 2.12.4 putchar: 1. The putchar function is also part of input output library function of C language. 2. It prints only a single character to a output device. 3. Syntax: putchar(variable) #include<stdio.h> #include<conio.h> void main() char gender; clrscr(); printf( Enter the gender M or F : ); gender=getchar(); prinft( Your gender is ); putchar(gender); getch(); Output: Enter the gender M or F: M Your gender is M FE- II [Computer Programming] Mr. Dipak V Bhosale 25

2.12.5 getch, getche: 1. The function getche(), getch() reads single character at a time, it is type without waiting for enter key to be hit. 2. The difference between them is that getch() reads the typed character without echoing on the screen, while getche() reads the typed character and echoes display it on the screen. 2.12.6 Format specifier: 1. Format specifiers are the character string with % sign followed with a character. 2. It specifies the type of data that is being processed. It is also called conversion specifier. 3. When data is being output or input it must be specify with identifier( variable) and their format specifier. c d f e g h lf o x i s u a single character a decimal integer a floating point number a floating point number a floating point number a sort integer long range of floating point number (for double data types) an octal integer a hexadecimal integer a decimal, octal or hex decimal integer a string an unsigned decimal integer Appendix: a. Basic structure of C Program with example: All C programs are made up of one or more function, each performing a particulars task. Every program has a special function named main(). It is special because the execution of any program starts from main functions. General Comments Preprocessor directives Global variables main() function local variables statements -------------- function1() other functions local variables statements -------------- FE- II [Computer Programming] Mr. Dipak V Bhosale 26

/*Example number 1*/ #include<stdio.h> main() Printf ( This is first program \n ); return 0; Comments /*..*/ In C, /* is called opening comment mark and */ is closing comment mark. The C compiler ignores everything between the opening comment mark and closing comment mark. The comment is used for program documentation. #include directory: In C, #include is a preprocessor directive that tells the C preprocessor to look for a file and place the file in the location where #include indicates. The preprocessor includes the header file such as stdio.h, conio.h, string.h etc. Header file: The file that are included by the #include directive such as stdio.h is called header file. The header files are always placed at the start of a C program. Angular <> braces: In C, the angular bracket asks the C preprocessor to look for a header file in directory other than the current one. If we want to let the C preprocessor look into current directory first for header file before it starts to work, we can use double quotes to surround the name of the header file. Normally, the header file are saved in a sub directory called include. Main function: Every C program must have one and only one main functions. The main function can be put anywhere but the execution of a program starts with main function. The main function starts and end with curly braces Printf functions and new line character: The printf function is used to print the character string. The new line character which is usually sufficient at the end of the message, tells the system to move the cursor to the beginning of next line. Return statements: All function in C can return value. The main function itself returns an integer value. So, return 0 indicates that 0 is returned from main function and the program is terminated normally. We can return values other than 0 to tell the system that there is an error. b. Rules while writing the C program: 1. Every C program starts with #include<stdio.h> 2. Every C program must contain main() function. The body of main() starts with and ends with. 3. Each instruction in C program is written as a separate statement. The instruction should in lower case. It is case sensitive. FE- II [Computer Programming] Mr. Dipak V Bhosale 27

4. Every statement should terminate with semicolon ; except loops. 5. The written program must be saved with.c extension. 6. The number of must be equal to same as for ( and ). c. Steps to Write and Run the C program: 1. Open Turbo C++ or C Complier application which is already installed on your computer. a. Go to My Computer then open Local Disk (C:) drive b. Open folder Turbo C++ c. Open DOSBox.exe file. 2. Select New option from File menu (Alt+F) in C editor. 3. Type the program in editor window. 4. Save the program using Function key F2 or select Save option from File menu. a. It must be save in Bin folder of Turbo C++ as C:\TurboC++\Bin\filename.C 5. Press Alt+F9 or select option Compile from Compile menu (Alt+C) to compile the C program. 6. If any error present in program, remove it. 7. Press Ctrl+F9 or select option Run from Run menu (Alt+R) to run the properly complied program which is error free and It may have some warnings. 8. Check the output. d. Derived data types: Derived data types are derived from the fundamental data type. Some of the derived data types are short int, long int, long double etc. Data type Size in Bytes Range Signed char 1-128 to 127 Unsigned char 1 0 to 255 Short signed int 2-32768 to 32768 Short unsigned int 2 0 to 65535 Signed int 1-128 to 127 Unsigned int 1 0 to 255 Long signed int 4-2147483648 to +2147483648 Long unsigned int 4 0 to 4294967295 Float 4 3.4e-38 to 3.4e+38 Double 8 1.7e-308 to 1.7e +308 Long double 10 3.4e -4932 to 1.1e + 4932 FE- II [Computer Programming] Mr. Dipak V Bhosale 28

e. Precedence Level with associatively in detail: FE- II [Computer Programming] Mr. Dipak V Bhosale 29

Unit II Programming Control 3.1 Introduction: 1. A program consists of a number of statements which are usually executed in sequence. Programs can be much more powerful if we can control the order in which statements are run. 2. Statements fall into three general types; Assignment, where values, usually the results of calculations, are stored in Variables. Input / Output, data is read in or printed out. Control, the program makes a decision about what to do next. 3. We will show how they can be used to write powerful programs by; Repeating important sections of the program. Selecting between optional sections of a program. 4. C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value. C programming language provides following types of decision making statements. 3.2 if statement: 1. An if statement consists of a boolean expression followed by one or more statements. 2. Flow diagram of if statement: 3. The syntax of an if statement in C programming language is: if(boolean_expression) /* statement(s) will execute if the boolean expression is true */ FE- II [Computer Programming] Mr. Dipak V Bhosale 30

4. If the boolean expression evaluates to true, then the block of code inside the if statement will be executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. 5. C programming language assumes any non-zero and non-null values as true and if it is either zero or null then it is assumed as false value. 6. Example: #include <stdio.h> int main () /* local variable definition */ int a = 10; /* check the boolean condition using if statement */ if( a < 20 ) /* if condition is true then print the following */ printf("a is less than 20\n" ); printf("value of a is : %d\n", a); return 0; Output: a is less than 20 value of a is : 10 3.2. if-else statement: 1. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. 2. The syntax of an if...else statement in C programming language is: if(boolean_expression) /* statement(s) will execute if the boolean expression is true */ else /* statement(s) will execute if the boolean expression is false */ 3. If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed. FE- II [Computer Programming] Mr. Dipak V Bhosale 31

4. C programming language assumes any non-zero and non-null values as true and if it is either zero or null then it is assumed as false value. 5. Flow diagram of if-else statement: 6. Example: #include <stdio.h> int main () /* local variable definition */ int a = 100; /* check the boolean condition */ if( a < 20 ) /* if condition is true then print the following */ printf("a is less than 20\n" ); else /* if condition is false then print the following */ printf("a is not less than 20\n" ); printf("value of a is : %d\n", a); return 0; Output: a is not less than 20; value of a is : 100 FE- II [Computer Programming] Mr. Dipak V Bhosale 32

3.3 nested if else statement: 1. It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). 2. The syntax for a nested if statement is as follows: if( boolean_expression 1) /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) /* Executes when the boolean expression 2 is true */ 3. Example #include <stdio.h> int main () /* local variable definition */ int a = 100; int b = 200; /* check the boolean condition */ if( a == 100 ) /* if condition is true then check the following */ if( b == 200 ) /* if condition is true then print the following */ printf("value of a is 100 and b is 200\n" ); printf("exact value of a is : %d\n", a ); printf("exact value of b is : %d\n", b ); return 0; Output: Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200 3.4 Else if ladder: 1. An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. 2. When using if, else if, else statements there are few points to keep in mind: FE- II [Computer Programming] Mr. Dipak V Bhosale 33

a. An if can have zero or one else's and it must come after any else if's. b. An if can have zero to many else if's and they must come before the else. c. Once an else if succeeds, none of the remaining else if's or else's will be tested. 3. The syntax of an if...else if...else statement in C programming language is: if(boolean_expression 1) /* Executes when the boolean expression 1 is true */ else if( boolean_expression 2) /* Executes when the boolean expression 2 is true */ else if( boolean_expression 3) /* Executes when the boolean expression 3 is true */ else /* executes when the none of the above condition is true */ 4. Flow diagram of else-if ladder: FE- II [Computer Programming] Mr. Dipak V Bhosale 34

5. Example #include <stdio.h> int main () /* local variable definition */ int a = 100; /* check the boolean condition */ if( a == 10 ) /* if condition is true then print the following */ printf("value of a is 10\n" ); else if( a == 20 ) /* if else if condition is true */ printf("value of a is 20\n" ); else if( a == 30 ) /* if else if condition is true */ printf("value of a is 30\n" ); else /* if none of the conditions is true */ printf("none of the values is matching\n" ); printf("exact value of a is: %d\n", a ); return 0; Output: None of the values is matching Exact value of a is: 100 3.5 C Programming Loops: 1. There may be a situation, when you need to execute a block of code several number of times. 2. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. 3. Programming languages provide various control structures that allow for more complicated execution paths. 4. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages FE- II [Computer Programming] Mr. Dipak V Bhosale 35

3.5.1 while loop: 1. A while loop statement in C programming language repeatedly executes a target statement as long as a given condition is true. 2. Flow diagram of while loop: FE- II [Computer Programming] Mr. Dipak V Bhosale 36

3. The syntax of a while loop in C programming language is: while(condition) statement(s); 4. Here, statement(s) may be a single statement or a block of statements. 5. The condition may be any expression, and true is any nonzero value. The loop to be performed again while the condition is true. 6. When the condition becomes false, program control passes to the line immediately following the while loop code. 7. Key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. 8. Example: #include <stdio.h> int main () /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) printf("value of a: %d\n", a); a++; return 0; Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 FE- II [Computer Programming] Mr. Dipak V Bhosale 37

3.5.2 for loop: 1. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. 2. The syntax of a for loop in C programming language is: for ( init; condition; increment ) statement(s); 3. Here is the flow of control in a for loop: a. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. b. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. c. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. d. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. 4. Flow diagram of for loop: FE- II [Computer Programming] Mr. Dipak V Bhosale 38

5. Example: #include <stdio.h> int main () /* for loop execution */ for( int a = 10; a < 20; a = a + 1 ) printf("value of a: %d\n", a); return 0; Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 3.5.3 do-while loop: 1. Unlike for and while loops, which test the loop condition at the top of the loop. 2. The do...while loop in C programming language checks its condition at the bottom of the loop. 3. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. 4. The syntax of a do...while loop in C programming language is: do statement(s); while( condition ); 5. Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. 6. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. FE- II [Computer Programming] Mr. Dipak V Bhosale 39

7. Flow diagram of do-while loop: 8. Example: #include <stdio.h> int main () /* local variable definition */ int a = 10; /* do loop execution */ do printf("value of a: %d\n", a); a = a + 1; while( a < 20 ); return 0; Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 FE- II [Computer Programming] Mr. Dipak V Bhosale 40

3.6 break statement: 1. The break statement in C programming language has the following two usages: a. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. b. It can be used to terminate a case in the switch statement (covered in the next chapter). 2. If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. 3. The syntax for a break statement in C is as, break; 4. Flow diagram of break statement 5. Example: #include <stdio.h> int main () /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) printf("value of a: %d\n", a); a++; if( a > 15) /* terminate the loop using break statement */ break; return 0; FE- II [Computer Programming] Mr. Dipak V Bhosale 41

Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 3.7 continue statement: 1. The continue statement in C programming language works somewhat like the break statement. 2. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. 3. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. 4. For the while and do...while loops, continue statement causes the program control passes to the conditional tests. 5. The syntax for a continue statement in C is as, continue; 6. Flow diagram of continue statement 7. Example #include <stdio.h> int main () /* local variable definition */ int a = 10; /* do loop execution */ FE- II [Computer Programming] Mr. Dipak V Bhosale 42

do if( a == 15) /* skip the iteration */ a = a + 1; continue; printf("value of a: %d\n", a); a++; while( a < 20 ); return 0; Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 3.8 goto statement: 1. A goto statement in C programming language provides an unconditional jump from the goto to a labeled statement in the same function. 2. NOTE: Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto. 3. The syntax for a goto statement in C is as follows: goto label;... label: statement; 4. Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement. FE- II [Computer Programming] Mr. Dipak V Bhosale 43

5. Flow diagram of goto statement 6. Example #include <stdio.h> int main () /* local variable definition */ int a = 10; /* do loop execution */ LOOP:do if( a == 15) /* skip the iteration */ a = a + 1; goto LOOP; printf("value of a: %d\n", a); a++; while( a < 20 ); return 0; Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 FE- II [Computer Programming] Mr. Dipak V Bhosale 44

3.9 Nesting of loops: 1. C programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. 2. The syntax for a nested for loop statement in C is as follows: for ( init; condition; increment ) for ( init; condition; increment ) statement(s); statement(s); 3. The syntax for a nested while loop statement in C programming language is as follows: while(condition) while(condition) statement(s); statement(s); 4. The syntax for a nested do...while loop statement in C programming language is as follows: do statement(s); do statement(s); while( condition ); while( condition ); 5. A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa. 6. The following program uses a nested for loop to find the prime numbers from 2 to 50 #include <stdio.h> int main () /* local variable definition */ int i, j; for(i=2; i<100; i++) for(j=2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime\n", i); return 0; FE- II [Computer Programming] Mr. Dipak V Bhosale 45

Output: 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 3.10 The Infinite Loop: 1. A loop becomes infinite loop if a condition never becomes false. 2. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. 3. When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop. 4. You can terminate an infinite loop by pressing Ctrl + C keys. 5. Example #include <stdio.h> int main () for( ; ; ) printf("this loop will run forever.\n"); return 0; 3.10 Switch Case (Menu driven): 1. When the user wants to select a particular group of statements from several available groups, C provides you with the switch statement. 2. The selection is based upon the current value of an expression that is included within the switch statement. FE- II [Computer Programming] Mr. Dipak V Bhosale 46

3. A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. 4. The syntax for a switch statement in C programming language is as follows: switch(expression) case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); 5. The following rules apply to a switch statement: 1) The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type. 2) You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. 3) The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. 4) When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. 5) When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. 6) Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. 7) A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. 6. Example #include <stdio.h> int main () /* local variable definition */ char grade = 'B'; switch(grade) case 'A' : printf("excellent!\n" ); break; FE- II [Computer Programming] Mr. Dipak V Bhosale 47

case 'B' : case 'C' : printf("well done\n" ); break; case 'D' : printf("you passed\n" ); break; case 'F' : printf("better try again\n" ); break; default : printf("invalid grade\n" ); printf("your grade is %c\n", grade ); return 0; Output: Well done Your grade is B FE- II [Computer Programming] Mr. Dipak V Bhosale 48

Unit III Array and String 4.1 Introduction of Arrays: 1. C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. 2. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. 3. Instead of declaring individual variables, such as number0, number1,..., and numbern, you declare one array variable such as numbers and use numbers[0], numbers[1], and..., numbers[n] to represent individual variables. 4. A specific element in an array is accessed by an index. 5. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Figure 4.1 Array structure 4.2 Declaration of One Dimensional Array: 1. To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows: Datatype arrayname[ arraysize ]; This is called a single-dimensional array. 2. The arraysize must be an integer constant greater than zero and type can be any valid C data type. 3. For example, to declare a 10-element array called balance of type int, use this statement: int balance[10]; Now balance is a variable array which is sufficient to hold up-to 10 integer numbers. 4.3 Initialization of One Dimensional Array: 1. You can initialize array in C either one by one or using a single statement as follows: double balance[5] = 1000.0, 2.0, 3.4, 17.0, 50.0; 2. The number of values between braces can not be larger than the number of elements that we declare for the array between square brackets [ ]. 3. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: FE- II [Computer Programming] Mr. Dipak V Bhosale 49

double balance[] = 1000.0, 2.0, 3.4, 17.0, 50.0; You will create exactly the same array as you did in the previous example. 4. balance[4] = 50.0; statement assigns element number 5 th in the array a value of 50.0. Array with 4 th index will be 5 th i.e. last element. 5. Because all arrays have 0 as the index of their first element which is also called base index. 6. Following is the pictorial representation of the same array we discussed above: Figure 4.2 Array with index and data 4.4 Accessing Elements and Displaying: 1. An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example: double salary = balance[9]; 2. The above statement will take 10 th element from the array and assign the value to salary variable. 3. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays: #include <stdio.h> int main () int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) n[ i ] = i + 100; /* set element at location i to i + 100 */ /* output each array element's value */ for (j = 0; j < 10; j++ ) printf("element[%d] = %d\n", j, n[j] ); return 0; Output: Element[0] = 100 Element[1] FE- = II [Computer 101 Programming] Mr. Dipak V Bhosale 50 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105

4.5 Finding Element from Array: #include <stdio.h> int main() int array[100], search, c, n; printf("enter the number of elements in array\n"); scanf("%d",&n); printf("enter %d numbers\n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); printf("enter the number to search\n"); scanf("%d", &search); for (c = 0; c < n; c++) if (array[c] == search) /* if required element found */ printf("%d is present at location %d.\n", search, c+1); break; if (c == n) printf("%d is not present in array.\n", search); return 0; Output: Enter the number of elements in array FE- II [Computer Programming] Mr. Dipak V Bhosale 51 5 Enter 5 numbers 5 4

4.6 Declaration of Two Dimensional Array: 1. C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration: type name[size1][size2]...[sizen]; 2. For example, the following declaration creates a three dimensional 5. 10. 4 integer array: int threedim[5][10][4]; 3. The simplest form of the multidimensional array is the two-dimensional array. A twodimensional array is, in essence, a list of one-dimensional arrays. 4. To declare a two-dimensional integer array of size x, y you would write something as follows: Datatype arrayname [ x ][ y ]; Where Datatype can be any valid C data type and arrayname will be a valid C identifier. 5. A two-dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimentional array a, which contains three rows and four columns can be shown as below: Figure 4.3 Two dimensional Array 6. Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a. 4.7 Initialization of Two Dimensional Array: FE- II [Computer Programming] Mr. Dipak V Bhosale 52

1. Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = 0, 1, 2, 3, /* initializers for row indexed by 0 */ 4, 5, 6, 7, /* initializers for row indexed by 1 */ 8, 9, 10, 11 /* initializers for row indexed by 2 */ ; 2. The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example: int a[3][4] = 0,1,2,3,4,5,6,7,8,9,10,11; 4.8 Accessing and Displaying Elements: 1. An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example: int val = a[2][3]; 2. The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array: #include <stdio.h> int main () /* an array with 4 rows and 2 columns*/ int a[4][2] = 0,0, 1,2, 2,4, 3,6) ; int i, j; /* output each array element's value */ for ( i = 0; i < 5; i++ ) for ( j = 0; j < 2; j++ ) printf("a[%d][%d] = %d\n", i,j, a[i][j] ); return 0; Output: a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 4.9 String in C programming: FE- II [Computer Programming] Mr. Dipak V Bhosale 53

1. The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. 2. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello". char greeting[6] = 'H', 'e', 'l', 'l', 'o', '\0'; 3. If you follow the rule of array initialization then you can write the above statement as follows: char greeting[] = "Hello"; Following is the memory presentation of above-defined string in C programming Figure 4.6 String memory presentation 4. Actually, we do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. 5. Example #include <stdio.h> int main () char greeting[6] = 'H', 'e', 'l', 'l', 'o', '\0'; printf("greeting message: %s\n", greeting ); return 0; Output: Greeting message: Hello 4.10 String Handling Functions (strlen, strcpy, strcmp, strcat): C supports a wide range of functions that manipulate null-terminated strings. You can find a complete list of C string related functions in C Standard Library. String Function Purpose of String Function 1. strcpy(s1, s2); Copies string s2 into string s1. 2. strcat(s1, s2); Concatenates string s2 onto the end of string s1. 3. strlen(s1); Returns the length of string s1. 4. strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. Table 4.1 String functions #include <stdio.h> #include <string.h> int main () FE- II [Computer Programming] Mr. Dipak V Bhosale 54 char str1[12] = "Hello"; char str2[12] = "World";

FE- II [Computer Programming] Mr. Dipak V Bhosale 55

Unit IV A) Structure 5.1 Introduction: 1. Structures are data structures whose individual elements can differ in type. 2. A single data structure may contain integers, floating points, pointers, arrays as well as other structures. 3. The individual structure elements are referred to as members. 4. Closely associated with structure is the union which also contains multiple members. 5. Unlike a structure however, the members of the union share the same storage area though the individual members may differ in type. 6. C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in C programming, which allows you to combine data items of different kinds. 7. Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book: Title Author Subject Book ID 7.2 Definition and Declaration of Structure: 1. To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this: struct [structure tag] member definition;... member definition; [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. 2. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. 3. Example as struct Books char title[50]; char author[50]; char subject[100]; int book_id; book; FE- II [Computer Programming] Mr. Dipak V Bhosale 56

5.3 Accessing elements and displaying elements: 1. To access any member of a structure, we use the member access operator.. 2. The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. 3. You would use struct keyword to define variables of structure type. #include <stdio.h> #include <string.h> struct Books char title[50]; char author[50]; char subject[100]; int book_id; ; int main( ) struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; /* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700; /* print Book1 info */ printf( "Book 1 title : %s\n", Book1.title); printf( "Book 1 author : %s\n", Book1.author); printf( "Book 1 subject : %s\n", Book1.subject); printf( "Book 1 book_id : %d\n", Book1.book_id); /* print Book2 info */ printf( "Book 2 title : %s\n", Book2.title); printf( "Book 2 author : %s\n", Book2.author); printf( "Book 2 subject : %s\n", Book2.subject); printf( "Book 2 book_id : %d\n", Book2.book_id); return 0; Output: Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 FE- II [Computer Programming] Mr. Dipak V Bhosale 57

5.4 Introduction of Union: 1. Both structures and unions are used to group a number of variables together. But while a structure enables us to treat as a unit a number of different variables stored at different places in memory, a union enables us to treat the same space in memory as a number of different variables. 2. A union is a special data type available in C that enables you to store different data types in the same memory location. 3. You can define a union with many members, but only one member can contain a value at any given time. 4. Unions provide an efficient way of using the same memory location for multi-purpose. 5.5 Definition and Declaration of Union: 1. To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows: union [union tag] member definition; member definition;... member definition; [one or more union variables]; 2. The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. 3. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str: union Data int i; float f; char str[20]; data; 4. Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable i.e. same memory location can be used to store multiple types of data. 5. You can use any built-in or user defined data types inside a union based on your requirement. 6. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string. FE- II [Computer Programming] Mr. Dipak V Bhosale 58

6.5 Accessing elements and displaying elements: 1. To access any member of a union, we use the member access operator.. 2. The member access operator is coded as a period between the union variable name and the union member that we wish to access. 3. You would use union keyword to define variables of union type. #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; Output: data.i : 1917853763 data.f : 4122360580327794860452759994368.000000 data.str : C Programming Here, we can see that values of i and f members of union got corrupted because final value assigned to the variable has occupied the memory location and this is the reason that the value if str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having union. #include <stdio.h> #include <string.h> union Data int i; float f; char str[20]; ; FE- II [Computer Programming] Mr. Dipak V Bhosale 59

int main( ) union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 220.5; printf( "data.f : %f\n", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); return 0; Output: data.i : 10 data.f : 220.500000 data.str : C Programming Here, all the members are getting printed very well because one member is being used at a time. 5.5 Difference between structure and union: Structure 1.The keyword struct is used to define a structure 2. When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum of sizes of its members. The smaller members may end with unused slack bytes. 3. Each member within a structure is assigned unique storage area of location. 4. The address of each member will be in ascending order This indicates that memory for each member will start at different offset values. 5 Altering the value of a member will not affect other members of the structure. 6. Individual member can be accessed at a time. 7. Several members of a structure can initialize at once. Union 1. The keyword union is used to define a union. 2. When a variable is associated with a union, the compiler allocates the memory by considering the size of the largest memory. So, size of union is equal to the size of largest member. 3. Memory allocated is shared by individual members of union. 4. The address is same for all the members of a union. This indicates that every member begins at the same offset value. 5. Altering the value of any of the member will alter other member values. 6. Only one member can be accessed at a time. 7. Only the first member of a union can be initialized. FE- II [Computer Programming] Mr. Dipak V Bhosale 60

Unit IV B) Function 6.1 Introduction: 1. Function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. 2. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task. 3. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. 4. The C standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions. 5. A function is known with various names like a method or a sub-routine or a procedure, etc. 6. So function in a C program has some properties discussed below. a. Every function has a unique name. This name is used to call function from main() function. A function can be called from within another function. b. A function is independent and it can perform its task without intervention from or interfering with other parts of the program. c. A function performs a specific task. A task is a distinct job that your program must perform as a part of its overall operation, such as adding two or more integer, sorting an array into numerical order, or calculating a cube root etc. d. A function returns a value to the calling program. This is optional and depends upon the task your function is going to accomplish. Suppose you want to just show few lines through function then it is not necessary to return a value. But if you are calculating area of rectangle and wanted to use result somewhere in program then you have to send back (return) value to the calling function. 6.2 Definition of Function: 1. The general form of a function definition in C programming language is as follows: return_type function_name( parameter list ) body of the function 2. A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function: 3. Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. FE- II [Computer Programming] Mr. Dipak V Bhosale 61

4. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature. 5. Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. 6. Function Body: The function body contains a collection of statements that define what the function does. 7. Example /* function returning the max between two numbers */ int max(int num1, int num2) /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; 6.3 Declaration of Function: 1. A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. 2. A function declaration has the following parts: return_type function_name( parameter list ); 3. For the above defined function max(), following is the function declaration: int max(int num1, int num2); 4. Parameter names are not important in function declaration only their type is required, so following is also valid declaration: int max(int, int); 5. Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function. 6.4 Calling Function: 1. While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. 2. When a program calls a function, program control is transferred to the called function. A called function performs defined task, and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program. FE- II [Computer Programming] Mr. Dipak V Bhosale 62

3. To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. 4. Example #include <stdio.h> /* function declaration */ int max(int num1, int num2); int main () /* local variable definition */ int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %d\n", ret ); return 0; /* function returning the max between two numbers */ int max(int num1, int num2) /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; Output: Max value is : 200 6.5 Passing parameters to functions: 6.5.1 Function Arguments: 1. If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. 2. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. 3. While calling a function, there are two ways that arguments can be passed to a function: Call by Value Call by Reference FE- II [Computer Programming] Mr. Dipak V Bhosale 63

6.5.2 Pass/Call by value: 1. The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. 2. In this case, changes made to the parameter inside the function have no effect on the argument. 3. By default, C programming language uses call by value method to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. 4. Consider the function swap() definition as follows. /* function definition to swap the values */ void swap(int x, int y) int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put x into y */ return; 5. Example #include <stdio.h> /* function declaration */ void swap(int x, int y); int main () /* local variable definition */ int a = 100; int b = 200; printf("before swap, value of a : %d\n", a ); printf("before swap, value of b : %d\n", b ); /* calling a function to swap the values */ swap(a, b); printf("after swap, value of a : %d\n", a ); printf("after swap, value of b : %d\n", b ); return 0; Output: Before swap, value of a :100 Before swap, value of b :200 FE- II [Computer Programming] Mr. Dipak V Bhosale 64

6.6 Scope of variable: 1. A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable cannot be accessed. 2. There are three places where variables can be declared in C programming language: a. Inside a function or a block which is called local variables, b. Outside of all functions which is called global variables. c. In the definition of function parameters which is called formal parameters. 6.6.1 Local Variables: 1. Variables that are declared inside a function or block are called local variables. 2. They can be used only by statements that are inside that function or block of code. 3. Local variables are not known to functions outside their own. 4. Following is the example using local variables. Here all the variables a, b and c are local to main() function. #include <stdio.h> int main () /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0; 6.6.2 Global Variables: 1. Global variables are defined outside of a function, usually on top of the program. 2. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. 3. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. 4. Following is the example using global and local variables. FE- II [Computer Programming] Mr. Dipak V Bhosale 65

#include <stdio.h> /* global variable declaration */ int g; int main () /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; 5. A program can have same name for local and global variables but value of local variable inside a function will take preference. Following is an example #include <stdio.h> /* global variable declaration */ int g = 20; int main () Output: /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; value of g = 10 FE- II [Computer Programming] Mr. Dipak V Bhosale 66

6.6.3 Formal Parameters: 1. Function parameters, so called formal parameters, are treated as local variables within that function. 2. They will take preference over the global variables. Following is an example: #include <stdio.h> /* global variable declaration */ int a = 20; int main () /* local variable declaration in main function */ int a = 10; int b = 20; int c = 0; printf ("value of a in main() = %d\n", a); c = sum( a, b); printf ("value of c in main() = %d\n", c); return 0; /* function to add two integers */ int sum(int a, int b) printf ("value of a in sum() = %d\n", a); printf ("value of b in sum() = %d\n", b); return a + b; Output: value of a in main() = 10 value of a in sum() = 10 value of b in sum() = 20 value of c in main() = 30 FE- II [Computer Programming] Mr. Dipak V Bhosale 67

6.6.4 Initializing Local and Global Variables: 1. When a local variable is defined, it is not initialized by the system, you must initialize it yourself. 2. Global variables are initialized automatically by the system when you define them as follows: Data Type Initial Default Value int 0 char '\0' float 0 double 0 pointer NULL 3. It is a good programming practice to initialize variables properly otherwise, your program may produce unexpected results because uninitialized variables will take some garbage value already available at its memory location FE- II [Computer Programming] Mr. Dipak V Bhosale 68

Unit V Pointers 7.1 Introduction: 1. Consider the statement int xyz = 50; This statement instructs the compiler to allocate a location for the integer variable xyz, and put the value 50 in that location. Suppose that the address location chosen is 1380. So, During execution of the program, the system always associates the name xyz with the address 1380. The value 50 can be accessed by using either the name xyz or the address 1380. Since memory addresses are simply numbers, they can be assigned to some variables which can be stored in memory. Such variables that hold memory addresses are called pointers. Since a pointer is a variable, its value is also stored in some memory location. 2. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. #include <stdio.h> int main () int var1; char var2[10]; printf("address of var1 variable: %d\n", &var1 ); printf("address of var2 variable: %d\n", &var2 ); return 0; Output: Address of var1 variable: 2293532 Address of var2 variable: 2293522 FE- II [Computer Programming] Mr. Dipak V Bhosale 69

3. A POINTER is a variable whose value is the address of another variable, i.e., direct address of the memory location. 4. They have a number of useful applications. Enables us to access a variable that is defined outside the function. Can be used to pass information back and forth between a function and its reference point. More efficient in handling data tables. Pointers provide direct access to memory Pointers provide a way to return more than one value to the functions Reduces the storage space and complexity of the program Reduces the execution time of the program Provides an alternate way to access array elements Pointers can be used to pass information back and forth between the calling function and called function. Pointers allow us to perform dynamic memory allocation and de-allocation. Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc. Pointers allow us to resize the dynamically allocated memory block. Addresses of objects can be extracted using pointers In this above figure, variable X contains value 32 stored at location address 1024. Another variable Y contains value 1024 which is an address of variable X and Y is stored at location address 11200. So, as per the definition of pointer Y is acts as pointer variable. 7.2 Declaration of pointer: 1. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. 2. The general form of a pointer variable declaration is: data_type *var_name; 3. Here, data type is the pointer's base data type; it must be a valid C data type and var_name is the name of the pointer variable. 4. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. FE- II [Computer Programming] Mr. Dipak V Bhosale 70