201
Course Modules Chapter 1: Introduction to Program Design Chapter 2: Programming Environment Chapter 3: History of Programming Language Chapter 4: Structure of C Program Chapter 5: Data Types Chapter 6: Identifiers Chapter 7: Basic I/O

Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

  • Upload
    others

  • View
    18

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Course ModulesCourse Modules

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Chapter 2: Programming EnvironmentChapter 2: Programming Environment

Chapter 3: History of Programming LanguageChapter 3: History of Programming Language

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

Chapter 5: Data TypesChapter 5: Data Types

Chapter 6: IdentifiersChapter 6: Identifiers

Chapter 7: Basic I/OChapter 7: Basic I/O

Page 2: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

Chapter 8: Control StructuresChapter 8: Control Structures

Chapter 10: FunctionsChapter 10: Functions

Chapter 11: Advanced Control ConstructsChapter 11: Advanced Control Constructs

Chapter 12: Storage Class and Scope RulesChapter 12: Storage Class and Scope Rules

Chapter 13: Advanced FunctionsChapter 13: Advanced Functions

Chapter 14: RecursionChapter 14: Recursion

Page 3: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: StructuresChapter 16: Structures

Chapter 15: PointersChapter 15: Pointers

Chapter 17: UnionsChapter 17: Unions

Chapter 18:File HandlingChapter 18:File Handling

Chapter 19: Storage Class and Scope RulesChapter 19: Storage Class and Scope Rules

Chapter 20:Standard Library Functions & HeadersChapter 20:Standard Library Functions & Headers

Page 4: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

What is a Program ?What is a Program ?

Stages of program developmentStages of program development

Some definitionsSome definitions

Page 5: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Lets understand what a Program is

A Program is a set of instructions to solve a problem.

And now define an Algorithm…

An Algorithm is a step by step solution to a problem

But both sound similar? So what is the difference ifany?Program and an algorithm represent solutions to problems , but aprogram is written in a programming language and an algorithm is not language specific. It is written in English like language called . So we can say that a program is an implementation of an algorithm in aspecific programming language.

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Page 6: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Program design is very important before coding the program. Programmer must consider all aspects of the program in detail before coding a program.

Why a program at all?

A program is not the problem: it is a solution to a problem. Hence problem definition is very important.

Problem definition

Programmers are very clear about the input to the program and the output from the program and constraints under which the program has to operate.

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Page 7: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Outlining the program structure

The next step after the problem definition is to decide how to solve the problem. We use the top-down approach. It means that decompose the whole problem into the number of independent tasks, and thencut the tasks unto smaller subtasks and so on until they are small enough to be grasped by mind. The task and subtasks are nothing but functions. Each small module or tasks can be easily programmed and linked together in the main program.

Algorithm development

An algorithm is any well defined computational procedure that takes some value or set of values, as input and produces some value, or set of values, as output.

Page 8: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Algorithm are never concerned with software engineering issues of data abstraction, modularity, error handling etc. It is pure logic.

Enough time must be always spent in algorithm development.

Selection of control structure

Control structure are nothing but the way to direct the flow ofexecution. the three basic control structure are:

1. Sequence structure :- control flow goes from one statement to another in sequence.

2. Selection structure :- Based on the condition, flow of control may go to different in the program as in the if....else statement.

Page 9: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

3. Looping structure :- It is used when a set of instruction is to be evaluated repeatedly.

Program Coding

As explained above, program is always to be coded into small procedures i.e. to achieve modular design.

Meaningful variable name are to be used.

For example, area = length * breadth is more meaningful thana = l*b;

Function name must be meaningful so that anybody could understand it's functionality in the program.

Page 10: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Code must be well documented. Comments must be used whenever necessary.

To increase the readability of the code, proper indentation must be used. For example the following code :

if (x<y) { flag = TRUE; printf(" x is larger than y"); } else flag = FALSE;

is perfectly valid code but is a poor programming style.

Page 11: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Use indentation to write it as

if ( x < y ){

flag = TRUE;printf(" x is larger than y");

}else

flag = FALSE;

Page 12: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Program Testing

Detection of error is called program testing. It is very difficult to write an error free program in the first time even by expert programmer.

Error type

Syntax Error :- Violation of rule of the language result in the syntax error. Compiler detect it at the time of compilation.

Logical Error :- This cause incorrect result. This is due to the lack of emphasis on the algorithm development.

Run-time Error :- Errors such as mismatch of data type or referencing an out of range array element or division by zero result in the run-time error. Program may give wrong result.

Page 13: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design

Let us take an example. Mr.Samasya staying in Delhi wants to purchase a book from Calcutta. He approaches Ms. Samadan to solve the problem. Hence buying a book is the problem. Now, Ms. Samadanstarts dividing the problem into small tasks. She jots down the various steps - enquire whether the book is available, book a ticket, purchase book, return ticket. These are stepwise solution to the problem. (An algorithm). She then sends one of her staff members to

Calcutta and Mr. Samasya is very happy. So,

PROBLEM DESIGN ----->ALGORITHM------>PROGRAM

Seven steps in all - This is what program design is all about!!!

Page 14: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 2: Programming Environment Chapter 2: Programming Environment

Various programming environments Various programming environments

Various stages while executing a C programVarious stages while executing a C program

Page 15: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 2: Programming Environment Chapter 2: Programming Environment

Various programming environments

Entering a Program

Once the program has been written, it must be entered into the computer. Most new version of C include a screen editor. To enter a new program, it must be typed into the editing area. Once the program has been entered it should be saved before it is executed.

Select Save As from the File menu and supply a program name such as area.c. Once saved, the same program can be recalled by selecting Open from the File menu.

Page 16: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Compiling & Executing To compile and execute, select Run from the Debug menu. If the program does not compile successfully, a list of error will appear in the separate window, otherwise, program will ask you for input (if any) and display output within the new window.

Entering a Program

The program must be entered into a file say area.c. If the file is created with the help of a text editor, either ed or vi. The command for calling the editor and creating the file is:

ed filenameIf the file already existed, it is loaded else a new file is created.

Various stages while executing a C program

Chapter 2: Programming Environment Chapter 2: Programming Environment

Page 17: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Compiling and linking

The compiling command is cc filename.c.

If there is no error object file filename.o will be created. Linking with a library file such as sqrt() are done automatically.

Executing

Use the command a.out and get the desired result.Note: Linker always gives executable object code the same name a.out. In order to save a program from overwriting while compiling another program you should rename the file by command

mv a.out filename.

Chapter 2: Programming Environment Chapter 2: Programming Environment

Page 18: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Generation of computer languagesGeneration of computer languages

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

Structured, Functional, Modular ProgrammingStructured, Functional, Modular Programming

Introduction to C languageIntroduction to C language

Page 19: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

The olden days of machine language

The computer was an electronic machine in the 1950’s. The capabilities of this electronic machine as a computing machine have increasedphenomenally in the subsequent years.Since the earlier days programmers have been looking for various ways of feeding computers with the most appropriate instructions to carry out the task in the best possible manner. Thus the earliest computers had to be programmed by directly loading their memories with machine level instructions.

Generation of computer languages

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

Page 20: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

The advantage was:It was very fast as the program directly interacted with the machine’s hardware.DisadvantageIt was very cumbersome to translate the program to machine levelinstruction.Different machines from different vendors had different sets of machine instructions.

Whew! Different different and different --- You can imagine how difficult that was.

Page 21: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

Assembly LanguagesThis was the first refinement to the cumbersome machine languages. Using assembly languages a programmer can represent a computation using textual mnemonics to represent instructions and data. Special software called assemblers can translate such representation i.e. Assembly language program into a set of machine level instructions. Advantage:Since it uses text mnemonics to represent the program it is comparatively easier than machine language.

Page 22: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

DisadvantageAssembly languages are ‘machine-dependent’ i.e. the program written for a certain model of the machine may not be portable on a different machine.

OOPS! That means I have to write different code for different machines! That’s bad news!

Page 23: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

The High Level languages

The high level languages like C, Fortran ,Cobol etc. solved this problem of ‘machine dependence’.These languages had standardizedways of writing code and also had a language syntax so that programsbecame more readable. The high level languages were mostly general purpose with few exceptions like COBOL and others.Thetranslation from high level code to low level code(i.e.. The machine level instructions) was done the compiler or the interpreter.(RememberAssemblers!)

Page 24: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

Understand terms- Structured,functional,modular

Structured ProgrammingIn 1968, Computer Scientist Edsger Dijkstra of the Netherlands published a letter to the editor in the Communication of the ACM(Association of Computing Machinery) containing a title "GOTO Statement considered harmful". GOTO is a command available in all the languages (including BASIC) to transfer control to a particular statement. For the last 25 years, Dijkstra has been crusading for a better way of programming - a systematic way to organize programs -called Structured Programming.

Structured Programming has been called a revolution in programmingand one of the most important advances in computer software of the past two decades.

Page 25: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

There is no standard definition of structured programming available but is often thought to be programming without the use of a GOTO statement. Indeed, structured programming does discourage the frequent use of GOTO but there is more to it than that.

Features of Structured ProgrammingTop-down analysis for program solving Modularisation for program structure and organizationStructured codes for the individual modules.

A High Level Language supports several control statements (also called structured control statements or structured code) to produce a well-organised (structured) module.

Page 26: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

These control statements represent conditional and repetitive type of executions. Each language has different syntax for these statements.

In PASCAL, the IF and CASE statements are examples of conditional execution whereas FOR, WHILE and REPEAT statements represent repetitive execution. In BASIC, FOR-NEXT and WHILE-WEND are examples of repetitive execution.

Problems with Structured Programming

Analyzing the reasons for the failures in program development reveals that there are weaknesses in the procedural paradigm itself. No matter how well the structured programming approach is implemented, large

Page 27: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

programs become excessively complex. What are the reasons for this failure of procedural languages? One of the most crucial is the role played by data.Data Undervalued In a procedural language, the emphasis is on doing things. And the subdivision of a program into functions continues this emphasis.Where does data fit in this paradigm? Data is usually the reason for a program's existence.Thus Structured ness is only one aspect of modular design. When the project becomes very large management of the modules themselves becomes a serious burden. The quest for finding a solution has led to the popularity of object oriented programming in the recent years.

Structured is good – Object oriented is more real-world I suppose!

Page 28: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

Introduction to C language

C is a general purpose, structured programming language. It was developed at AT&T's Bell laboratories of USA in 1972 by a singleperson Dennis Ritchie.In 1970s, the work on Unix system was going on. it was being written in Assembly level language (ALP), a language which uses simple English words like MOV, ADD etc. But that was very difficult to debug. So a new language C was developed along with Unix. Although few high level language existed but they could not get popularity due to one reason or other.

The table below shows the evolution of C :

Page 29: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

YEAR LANGUAGE DEVELOPED BY REMARKS

- ALP - Difficult to debug

1960 ALGOL International committee Too general

1963 CPL Cambridge University Big size

1967 BCPL Martin Richard No data types

1970 B Ken Thomson Very specific

1972 C Dennis Ritchie Versatile

Page 30: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 3:History of Programming LanguageChapter 3:History of Programming Language

The growing popularity of C, changes made into over years has created a necessity of its standard definition. It was done in 1983 by American National Standard Institute (ANSI)

That's quite an effort. We have A's then B then C

Page 31: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

Basic structure of a C programBasic structure of a C program

Using Comments in CUsing Comments in C

Page 32: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

The basic structure of the C program is as follows:

Ex: To print a message on the screen

#include<stdio.h>//Header FileInclusion

void main()//Start of the main function

{

printf("This is my first program in C");//Executable statements

}//End of main()

Page 33: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

The above program prints the message This is my first program in C on the screen.

The first section shows header file inclusions. These header files contain the definitions for the various funtions and keywords used in the program. Here, the header file is stdio.h and this basically contains the input output related functions.(For the time being).The main() is the start of the program. A function is denoted by (). void indicates that the function does not return any values. main() is the name of the function .The executable lines are terminated with a ; and here it displays the message on the screen. printf is a function used to display data on the screen

Shall we dissect this program and understand the contents please?

Page 34: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Comments in C

Comments are almost always a good thing. Comments are used to inform the person looking at the listing what is being done.

This type of comment begins with the /* character pair and ends with */, not the end of the line.

While this style is not generally used in C++, it has uses in special situations.

You can write a multi-line comment with only two comment symbols: /* this is a potentially very long multi-line comment */

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

Page 35: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

The main() starts with a { and ends with a }. This is called a block.

I got it! But what is that // doing here?

You can also insert a /* */ comment anywhere in the middle of a program line:

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

Page 36: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

The building block of C programs are functions. A function is a subroutine that may include one or more statements designed to perform a specific task. Writing a C program means writing functions and putting them together. Let's take a bigger example.

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

/* This program displays the cosine of an angle*/#include <math.h>#define PI =3.1416main(){ int angle=60;float x,y; x=(PI/180)*angle; y=cos(x);printf("cos 50 degree is %f", y);

}

Page 37: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

SECTIONS MEANING EXAMPLE

Documentation set of comments like name, use of program and others details

/* This program displays the cosine of an angle */

Link instruction to compilers to link function from system library.

#include <math.h>

Definition symbolic name definition.

#define PI =3.1416

Page 38: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

SECTIONS MEANING EXAMPLE

Global Declaration variables which can be used in different function.

/* No such declaration in this program */

Main() Program

tells compiler about variable used in the executable part.

instruction to execute

main() { int angle=60; float x,y; x=(PI/180)*angle; y=cos(x);printf("cos 50 degree is %f", y)}

Declaration

Execution

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

Page 39: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Display can well be done in main() function only but for proper work division display() function was used. In computer program, it becomes a complete necessity.

It will be explained further in coming chapters.

Chapter 4: Structure of C ProgramChapter 4: Structure of C Program

Page 40: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 5: Data TypesChapter 5: Data Types

Datatypes in CDatatypes in C

Constants and variablesConstants and variables

Escape sequencesEscape sequences

Page 41: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Datatypes in CThe fundamental building blocks of any language are the datatypes it can handle since a program has to represent data in order to do useful processing . These datatypes are used in all languages to declare variables or constants which will contain values when the program is running.C supports many different types of data, each of which may be represented differently within the computer's memory. the basic data types are listed below.

Chapter 5: Data TypesChapter 5: Data Types

Page 42: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

char single character 1 byte -128 to 127

int integer quantity 2 bytes or one word (varies from one

compiler to another)

-32,768 to 32,767

float floating-point number 1 word(4 bytes) 3.4e-38 to 3.4e+38

DATATYPE DESCRIPTION MEMORYREQUIREMENTS

RANGE

Chapter 5: Data TypesChapter 5: Data Types

Page 43: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

DATATYPE DESCRIPTION MEMORY REQUIREMENT

RANGE

double double-precision floating point number

2 words(8 bytes) 1.7e-308 to 1.7e+308

void type-specifier (used for defining a function that does not return anything)

Chapter 5: Data TypesChapter 5: Data Types

Page 44: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 5: Data TypesChapter 5: Data Types

In addition there are a no. of data type qualifiers short, long, signed and unsigned which can be used to augment the basic data types. The size and range of the basic data types using these qualifiers is listed in the table below.

TYPE SIZE RANGE

char or signed char

1 byte -128 to 127

unsigned char 1 byte 0 to 255

int or signed int 2 byte -32,768 to 32,767

Page 45: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

TYPE SIZE RANGE

unsigned int 2 byte 0 to 65,535

short int or signed int 1 byte -128 to 127

unsigned short int 1 byte 0 to 255

long int or signed long int

4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

Chapter 5: Data TypesChapter 5: Data Types

Page 46: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

float 4 byte 3.4e-38 to 3.4e+38

double 8 byte 1.7e-308 to 1.7e+308long double 10 byte 3.4e-4392 to 1.1e+4392

TYPE SIZE RANGE

The standard headers <limits.h> and <float.h> contains symbolic constants for all of these sizes and other information.

Whew! That quite difficult. So many types and such large numbers! Is there an easy way out!!?

Chapter 5: Data TypesChapter 5: Data Types

Page 47: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

To calculate the range for any datatype is very easy. For unsigned numbers the range is0 - 2n-1

For signed numbers the range is- 2n-1 to 2 n-1 -1

That's perfect and so very easy to work out!!!

Although so many datatypes have been mentioned the fundamental types are char, int,float and double.

Chapter 5: Data TypesChapter 5: Data Types

Page 48: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

VARIABLES

Variables and constants are the basic data objects manipulated in a program. before using a variable it must be declared. Expression combines variables and constants to produce new values

Rules for naming variables:

1.consists of a-z, A-Z, 0-9 but first character must be a letter.2.case-sensitive.3.underscore character can also be included.4.special characters like *,-,+,',"" are not allowed.5.blank space is not allowed within a variable name.

note: name of the variable should denote its use.

Chapter 5: Data TypesChapter 5: Data Types

Page 49: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

ex. sum, average_class, fun2.

note: Ram ,ram, RAM are different variable names.

Chapter 5: Data TypesChapter 5: Data Types

Page 50: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

CONSTANTS

A constant is a quantity that does not change.

A integer constant like 1234 consists of sequence of digits. It can be decimal, octal or hexadecimal.

ex. 2415(decimal), 0xabc2(hexa), 0243(octal).note:10,000(comma), 10-20(hypen or blank), 0900(preceded by 0) are invalid integer constants.

A real constant is a base 10 number that contains either a decimal point or an exponent or both.ex. 1., 2.543, 0.9453e-34.

Chapter 5: Data TypesChapter 5: Data Types

Page 51: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

A real constant is a base 10 number that contains either a decimal point or an exponent or both.ex. 1., 2.543, 0.9453e-34.note: 1. 1,00.00(comma), 2e+3.24(real exponent), 3e 10(blank space) are invalid real constants.

2. Integer constants are exact quantities but real constants may be approximations. 1.0 might be represented within the computer as 0.99999 or 1.00001.

Chapter 5: Data TypesChapter 5: Data Types

A character constant is a single character enclosed in a apostrophe.ex. 'a', '5', '*'.

note: ASCII characters showing the decimal equivalent of seven bits represent a character in computer.

Page 52: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Certain nonprinting characters, as well as the backslash(/) and the apostrophe('), can be expressed in terms of escape sequences. Such escape sequences always represent single characters, even though they are written in terms of two or more characters.

Chapter 5: Data TypesChapter 5: Data Types

Page 53: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 5: Data TypesChapter 5: Data Types

CHARACTER ESCAPE SEQUENCE ASCII VALUE

bell \a 007backspace \b 008horizontal tab \t 009new line \n 010vertical tab \v 011form feed \f 012carriage return \r 013quotation mark \'' 034apostrophe \' 039question mark \? 063

Page 54: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

backslash \\ 092null \0 000

A string constant consists of any number of consecutive characters (including none), enclosed in quotation marks("").ex. "hello", "243-45+32", " ". note: 1. 'A' and "A" are not equivalent.

2. The compiler places a null character(\0) the end of every string constant.

CHARACTER ESCAPE SEQUENCE ASCII VALUE

Chapter 5: Data TypesChapter 5: Data Types

Page 55: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Shall we summarize the whole thing?Constants are those whose values do not change.For ex. “India” is a name constant, 10 is an integer constant and 15th August 1949 (India’s independence) is a date constant.

The co-ordinates for the line are integer variables, a person’s name is a character variable and so on.

In technical terms when we declare a variable then we speicfythe datatype and the variable name. Thus a variable name is the name given to a memory location.

Gotcha! When we want to store data, we require a container,a space to store it and the value stored may change and that’s why it is exactly called a variable.

Chapter 5: Data TypesChapter 5: Data Types

Page 56: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 6: IdentifiersChapter 6: Identifiers

Objective:

Declaring a variable Declaring a variable

Operators and expressionsOperators and expressions

Precedence of operatorsPrecedence of operators

Page 57: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

All variables must be declared before its use. A declaration specifies a type and contains a list of one or more variables of that type.ex. int number, average, line[100];

Variable can also be initialized in its declaration. ex. int number=0;

A qualifier const can be applied to the declaration of any variable to specify that its value cannot be changed.ex. const float mean=2.456383;

Chapter 6: IdentifiersChapter 6: Identifiers

Declaring a variable

Page 58: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

OPERATORS AND EXPRESSIONS

Various elements of the program like constants, variables, array elements, function references can be added together by various operators to form expression

ARITHMETIC OPERATORS

They are binary operators as they work with two operands.The operators are + , - , * , / and % (modulo operator).

Chapter 6: IdentifiersChapter 6: Identifiers

Page 59: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

There is a unary –(minus operator) which multiplies its operand by –1 ie. It switches the sign.

Example:

int no1=10;

int no2=20;

printf( no1+no2); //Will print 30

printf(no2%no1); //Will print 0

printf(no2%3); //Will print 2

Chapter 6: IdentifiersChapter 6: Identifiers

Page 60: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

The Increment and Decrement operators They are the ++ and -- operatorsThe ++ operator increments the operand by 1 and the – operator decrements its operand by 1.

Chapter 6: IdentifiersChapter 6: Identifiers

int no1=10;no1++;printf(no1); //Will print 11 as the above statement

is equivalent to saying no1=no1+1;

Page 61: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

There are a prefix and postfix increment/decrement operators . Both the forms are equivalent if used separately without the assignment. But when the latter is done the meaning of the operation changes.

Chapter 6: IdentifiersChapter 6: Identifiers

For ex.

int no1=10;

no1++; (or) ++no1; will mean the same.

But,

int result = no1++; ---------------- Statement1

int result = ++no1; ---------------- Statement2

Page 62: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 6: IdentifiersChapter 6: Identifiers

Statement1 will cause assignment to take place first followed byincrement(postfix increment)whileStatement2 will cause increment to take place first followed by assignment(prefix increment).Thus result will have 10 if statement1 is executed and result will have 11 if statement2 is executed.

Assignment followed by operation in postfix and reverse in prefix. Good!

Page 63: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Type Conversions

When an operator has operands of different types they undergo type conversion before the expression takes its final value. If either operand is long double, other is converted to long double.Otherwise , If either operand is double, other is converted to double. Otherwise , If either operand is float, other is converted to float.Otherwise , convert char and short to int.This conversion takes place automatically.

Chapter 6: IdentifiersChapter 6: Identifiers

Page 64: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 6: IdentifiersChapter 6: Identifiers

RELATIONAL AND LOGICAL OPERATORS

The term relational specifies the relationships that the values can have with each other. Expressions that contain relational operators return true or false.The relational operators used in C++ are

Operator Action

> Greater than>= Greater than or equal< Less than<= Less than or equal== Equal!= Not equal

Page 65: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 6: IdentifiersChapter 6: Identifiers

The Logical operators

They are so called because they return a logical value ie. True or false. They are used with relational operators in expressions.The operators used are

Operator Action

&& Logical AND| | Logical OR! Logical NOT

Page 66: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

The Bitwise Operators

C++ supports a full complement of bitwise operators . Bitwise operation refers to testing,setting or shifting the actual bytes in a word which correspond to the char and int data types and variants.

Operators Action

& Bitwise AND| Bitwise OR^ Bitwise exclusive OR~ Bitwise NOT>> Shift operator<< Shift left

Chapter 6: IdentifiersChapter 6: Identifiers

Page 67: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

The ternary operator C++ contains the very powerful and convenient operator that replaces certain statements of the if-then-else form. It takes the general formExp1?exp2:exp3;Exp1, the first expression1 is evaluate. If it is true then Exp2 i.e. The expression2 becomes the value of the expression . If exp1 is false then exp3 ie. Expression3 is the value of the expression.There are many more operators and will be discussed with the relevant topics.

Chapter 6: IdentifiersChapter 6: Identifiers

Page 68: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 6: IdentifiersChapter 6: Identifiers

Precedence of operators

HIGHEST

! ,~ , ++, -- , (type) , *,&, sizeof* , / , %+ , -<<,>><,<= ,>,>== = , !=&^|&&

Page 69: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

| |

?:

LOWEST= ,+= ,-= ,*= ,/= etc.

Chapter 6: IdentifiersChapter 6: Identifiers

So ( ) (parenthesis or brackets)have highest priority and shorthand assignments the least.Must keep this in mind while writing expressions.

Page 70: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

UNARY OPERATORThese operator works on single operator to give a new result. Most common example is unary minus such as -45.

Increment and decrement operatorThe increment operator adds one to the operand while decrement operator subtract one from the operand. Now comes the question what is the difference between the prefix and postfix increment operator i.e. n++ and ++n. Both increment the operand by 1 but ++n increment nbefore it's value is being used.ex: if number=10, then a = number++; sets a to 10 although number is incremented to 11.

while a = ++number ; sets a to 11.sizeof operator determines the number of bytes allocated to various type of data item.

Chapter 6: IdentifiersChapter 6: Identifiers

Page 71: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

ex: sizeof (integer) return 2 while for the declaration char madam[] ="meenakshi"; sizeof madam will return 10(one extra for null character)

Casting is used to convert value of a expression to a different data type if desired. Desired format is

(data type) expression

ex: if x is declared as integer with value 2, and y is declared as float with value 3.5, then (x+y) % 2 is invalid because first operand need to be integer. So to force operand to integer value casting is done as

((int) (x+y)) % 2

Chapter 6: IdentifiersChapter 6: Identifiers

Page 72: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

note: data type associated with the expression is not changed by a cast. Rather it is the value of the expression which undergoes change. Here (int) (x+y) will have value 5.

ASSIGNMENT OPERATOR AND EXPRESSIONS

Expression such asi = i + 4

can be written in short hand form using arithmetic assignment operator += as

i += 2.Similarly other arithmetic operator can be used as assignment operator.note: there should not be any blank space between + and = in arithmetic assignment operator.

Chapter 6: IdentifiersChapter 6: Identifiers

Page 73: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

CONDITIONAL OPERATOR

The statementsif(a>b)

max=a;else

max=b;finds the maximum of two number a and b. The sort hand rule is to use conditional operator ( ? : ). Thus simple way to write above statement is

max = (a>b) ? a : b;

Chapter 6: IdentifiersChapter 6: Identifiers

PRECEDENCE

Precedence means order of evaluation. Operator with higher precedence level is evaluated first.

Page 74: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

While associativity is the order in which consecutive operations within

the same precedence group are carried out.

Chapter 6: IdentifiersChapter 6: Identifiers

Page 75: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

OPERATOR CATEGORY

OPERATORS ASSOCIATIVITY

Unary - ++ -- ! sizeof(type)

R→ L

Arithmetic * / %(same precedence) + -

L→ R

Relational operators

> >= < <= = = != L→ R

Bitwise operator & ^ | L→ R

Logical && || L→ R

Chapter 6: IdentifiersChapter 6: Identifiers

Page 76: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

OPERATOR CATEGORY

OPERATORS ASSOCIATIVITY

Conditional operator

? : L→ R

Assignment operator

= += -= *= /= %= L→ R

Chapter 6: IdentifiersChapter 6: Identifiers

Page 77: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Example :-Evaluation of expression:

n=a*b/2+3/2*b+2+d; where a=3, b=2,c=3.4; n is declared as int.stepwise operation:

n=3*2/2+3/2*2+2+3.4n=6/2+1*2+2+3.4 //note:3/2 is 1 not 1.5 as it is an integer division

and hence result is also integer.n=3+2+2+3.4n=10 //note: n is declared as integer and hence can take

only integer value. It is assigned10 ,not 10.4.

Chapter 6: IdentifiersChapter 6: Identifiers

We have been talking of expressions so far can we have a little more detail please?

Page 78: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

EXPRESSIONS

Operators , constants and variables are the components of expressions.

Chapter 6: IdentifiersChapter 6: Identifiers

An expression is a valid combination of the above mentioned elements. Great!

Order of evaluation Neither C nor C ++ specifies the order in which the subexpressions

of an expression are evaluated. This leaves the compiler free torearrange an expression to produce more optimal code. For ex.X=exp1+exp2;This statement does not ensure that exp2 will be evaluated after

exp1.

Page 79: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Type conversion in expressions

When constants and variables of different types are mixed in expressions they are converted to the same type. This is called type promotion. The compiler converts all operands upto the type of the largest operand . The diagram can be shown as follows:

Chapter 6: IdentifiersChapter 6: Identifiers

Okay! Since lower dataypes are converted to higher datatypes it is called promotion.

Page 80: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 6: IdentifiersChapter 6: Identifiers

CASTING IN EXPRESSIONS

We can force an expression to be of a specific typr by using a cast. The general form of the cast is(type) expressionTechnically casts are operators. A cast is unary and has the same precedence as any other unary operator.

Short-hand assignment

There is a variation of the assignment statement that simplifies coding of some types of assignment operations.The are the +=, -= , *= , /= .This notation is widely used in programming.

Page 81: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

Various input output functionsVarious input output functions

Page 82: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

C offers library functions for number of input/output operation like getchar, putchar, scanf, printf, gets, puts. Most program begins with the preprocessor statement #include <stdio.h>. This header file gives required information to the library function scanf and printf.

getchar() and putchar() Function

getchar() takes a single character from the standard input device generally keyboard.char c= getchar(); statement assigns a single character inputted from keyboard to the variable c.Similarly putchar(c) function puts a single character c on the standard output device monitor.

Page 83: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

Inputting data through scanf function

scanf() function is used to enter any datatype, an integer, a float or a string.

eg: scanf("%d %f %s , &n,&interest, message);

The control string %d %f %s indicate that arguments n, interest, message represent integer, float, string respectively as per itsdeclaration.note: never forget to put &(ampersand) before variable name which are not string or an array name.note: A variable declared as character type will scan its ASCII value if the control string is %d meant for integer.

Page 84: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

Outputting data through printf function

printf() perform the similar function as scanf but to output the data.

eg: printf("%d", n);

note: No & is used while outputting the data.

Page 85: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O Conversion string Corresponding controlled variable

type

%c character

%d integer

%e float with exponent( in output mode), float (in input mode)

%f float without exponent( in output mode), float (in input mode)

%g float using e-type and f-type. Trailing zero and decimal point will not will be displayed( in output mode), float (in input mode)

%o Octal integer

Page 86: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

Conversion string Corresponding controlled variable type

%s string( in output mode), string terminated by blank space (in input mode)

%u unsigned decimal integer

%x hexadecimal integer

%[^\n] string terminated by newline (in input mode)

Page 87: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

scanf(Revisited)

In case of string, %s will be able to control the input of a string only up to the point a blank space is met. To solve this problem, we use control string as %[ ABCDEFGHIJKLMNOPQRSTUVWXYZ12345;'./] .

Now inputted string may take all character specified inside [] and will terminate inputting string when any character outside this set is given as input.

Another way to input string is by using the control argument [^(character)]. Now the program will input the string until a character or a escape sequence is inputted.

Page 88: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

printf (Revisited)

It is possible to out the formatted data for example :to specify the maximum number of decimal place for a float data type or maximumnumber of characters for a string.Minimum width and precision may be specified for a float type data. Minimum width is to limit the number of digit or character to a specified limit while precision set the number of digit after the decimal point.

Page 89: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

Example of formatting a float:

a=906.324

printf ("%7f %7.3f %7.1f ",a,a,a) output on execution will be 906.324000 906.324 906.3

printf ("%f %.3f %.1f",a,a,a) output on execution will be 906.324000 906.324 906.3

printf ("%e %.5e %.2e",a,a,a) output on execution will be 9.063240e+029.06324e+02 9.06e+02

Page 90: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

In first example, field width is 7 and a has also 7 character width, so whole number will be outputted. Precision is specified after field width with a point. Default precision is 6 character after decimal. If field width specification is more, then leading blank will come in the output before the number.

Chapter 7: Basic I/O Chapter 7: Basic I/O

Example of formatting a String:

char message[10];printf ("%10s %20s %10.5s %.5",message,message,message,message)

Page 91: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 7: Basic I/O Chapter 7: Basic I/O

if message is assigned electronics during program, output on execution will be electronics electronics elect elect

Even though electronics contains 11 character and field width specification is only 10,the first string breaks the minimum field width criteria. Second string is right justified within the specified width. Precision criteria of 5 will just allow 5 character to be outputted and field width criteria will work as earlier.

Page 92: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

Selection statements (if and switch)Selection statements (if and switch)

Looping statements (for,while,do..while)Looping statements (for,while,do..while)

Page 93: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures Control flows is the manner in which control flows in a program.It's type are :

1.sequential : control flows from one statement to other in sequence.

2.conditional : control flows as per the condition which can be either true or false.

3.Iterative : control flows in a loop repeatedly

Any high level programming language has three features viz. Sequence,Iteration and Decision.Since C is a structured and High level language it also has these constructs . Selection statements imply decision.The constructs available here are the if construct and the switch construct.

Selection statements(if and switch)

Page 94: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

The if constructThe general format is

if(expression)statement;

elsestatement;

if(expression)statement;

else if(expression)statement;

elsestatement;

The other form of if is as follows:

Page 95: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

Example. Accept a number from the user and display if it is an even or odd number.

The if is an alternative to the ternary operator I guess!

#include<stdio.h>void main(){

int no; //Declare a variable to accept the number

printf(”Enter the number”);scanf("%d); //Accept input from the

user

if(no%2==0 //Check for odd or even no.the expression evaluates

Page 96: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

printf(”Even number”); //to a true or false.

else

printf(”Odd number”); //Executable statement

}Let us consider some more examples:

1. if (speed > 60)printf("drive slowly");

elseprintf(" your speed is all right"); //note the indentation i.e. the

way code are written with proper spacing.

2. if (square) {scanf ("%f",&side);area = side*side;

Page 97: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

printf("area of square is: %f",area);}else {

scanf("%f %f",&length,&breadth);area = length*breadth;printf("area of rectangle is: %f",area);}

note: square must be assigned a non zero value before the second example is being executed.

note: If there are more than one statement are to be executed if the condition is true or false, they must be put under braces.An example with if …… elseifAccept an alphabet from the user and check if it is a vowel

Page 98: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

#include<stdio.h>void main(){

char alphabet; //Declare a variable to accept the alphabet

printf(”Enter the alphabet”);scanf("%c",&alphabet); //Accept

input from the userif((alphabet==’a’) || (alphabet==’A’)) //The expression

evaluatesprintf(”vowel”); //to a true or false

else if((alphabet==’e’) || (alphabet==’E’))

printf(”vowel”); //Executable

Page 99: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

statement

else if((alphabet==’i’) || (alphabet==’I’))

printf(”vowel”);

else if((alphabet==’o’) || (alphabet==’O’)) //The expression uses logical operators also

printf(”vowel”);

else if((alphabet==’u’) || (alphabet==’U’))

printf(”vowel”);

Chapter 8 : Control Structures Chapter 8 : Control Structures

Page 100: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

The switch construct

Switch statement is called a multiple-branch selection statement. It successively tests the value of the expression against a list of integer or character constants . When a match is found the statements associated with that constant are executed.

else

printf(”consonant”);

}

Page 101: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

break;

}

The general form of the switch clause is as follows:

switch(expression)

{

case constant1: statement;

break;

case constant2:statement;

Page 102: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

Loops or iteration is another characteristic feature of any high level language. This feature allows statements to be executed repeatedly until a certain condition is reached. To understand the loop let’s take a real life example of a loop. Consider a relay race consisting of four members. Here the athletes run around the track and pass on the rod till the fourth player finishes. The components that we see are as follows - there is a start condition i.e.. The first player starts the race, there is a stop condition the fourth player stops the race, there is an action repeated i.e.. Running and of course there is a counter , the judge who counts the four athletes starting from one to four.

8.2 Looping statements(for,while,do..while)8.2 Looping statements(for,while,do..while)

Page 103: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

Components of a loop Similarly , in an iteration loop the above mentioned components should ideally be present.If some of the components are missing it may result in an infinite loop i.e. A loop which runs for infinite times. C provides a number of looping constructs which may be used in iteration problems.The following are the loops:

The for loop The general form of the for loop is as follows:

for (initialization;condition;reinitialization)

statement;

Page 104: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

The initialization section is used to set the loop counter variable in other words sets the start condition. Condition specifies the stop condition and is a relational expression and this determines when the loop will exit.

The reinitialization section increments or decrements the counter variable according to the context of the loop. Statement indicates the action repeated.

Ex.Print the first ten odd numbers.

Let us identify the four components in this simple loop problem.The start condition is 1 and stop condition is 10, action repeated is printing of numbers .

Page 105: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

The for loop will be written as follows:

for(int ctr=0,no=1;ctr<10;ctr=ctr+1)

{

cout<<no;

no=no+2;

}

Ex2: Print the numbers from 100 in descending order for(int ctr=100;ctr>0;ctr--){

cout<<ctr;}

Page 106: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

In this example the counter has been decremented.

Okay!Reinitialization can both be increment and decrement. The above loop rus for 100 times

Let us see some more examples.

Ex: Accept 10 alphabets from the user and convert them to uppercase if they are in lowercase and vice versa.

#include<stdio.h> //Header file inclusion

void main() //Main function

{

char alphabet; //Declaration of variables

Page 107: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control StructuresChapter 8 : Control Structures

for(int ctr=0;ctr<10;ctr++)

{

printf(”Enter the alphabet %d “,ctr+1); //Prompt the user for input

scanf("%c",&alphabet); //Accept the input

if((alphabet >=65 && alphabet <=90 )) //Check for uppercase //alphabets

alphabet=alphabet+32;

{

printf(”Enter the alphabet %d “,ctr+1); //Prompt the user

// for input

Page 108: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

scanf("%c",&alphabet); //Accept the input

if((alphabet >=65 && alphabet <=90 )) //Check for uppercase // alphabets

alphabet=alphabet+32; //Convert to // lowercase

else if(alphabet>=97 && alphabet<=122) //Check //for lowercase //

//characters

alphabet=alphabet-32; //Convert to uppercase

printf(alphabet); //Display the alphabet

}

}

Page 109: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

In this example we have used some relational operators and relational operators also.

ASCII link

Suppose I write for ( int I=0 ; ;I++) ,is it valid?

Very much. This is called an infinite loop where the condition part always returns a true value.

This is a bodyless loop , a loop which has no action to be performed except for iteration. We will see one such example when we do arrays .

One more question, for(int I=0;I<10;I++);what does this mean?

Page 110: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

The while loop The syntax for the while loop is as follows:

Example:Accept characters and display till the user presses ‘n’;

while(Condition){

<statements>}

Page 111: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

#include<stdio.h>

void main(){

char ch=’ ‘; //Declaration of variableswhile(ch!=’n’) //Accept characters till user enters n{

sanf("%c",&ch);printf(ch); //Display characters}}

Page 112: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

Thus a while loop is normally used when the number of iterations are not exactly known as in the above case.

Consider another example.

Print the first ten odd numbers. #include<stdio.h>void main(){

int counter;int number=1;

Page 113: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

while(counter < 10)

{

printf(number);

number+=2;

}

}

Chapter 8 : Control Structures Chapter 8 : Control Structures

There is something wrong,the initialization and reinitializationpart of loop is missing I suppose.

Page 114: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

Excellent! This may result in undesired consequences like infinite loops. This is a logical error on the part of the programmer. The correct code would be as follows:

int counter=0; //Statement 1while(counter<10){

cout<<number;number+=2;counter++; //Statement2

} If statement 1 and 2 are missed then the loop becomes logically wrong.

Page 115: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

3.The do…..while loop

The general structure of the do….while loop is as follows:

Then what is the difference? Why two loops doing the same job?

do{<statements>

}while(condition);The loop works very much the same as that of the while loop.

Page 116: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures

Thus a do while loop is executed atleast once. Example:

The difference lies in the fact that in a do while loop the condition is checked after execution of the statements while in the while loop the condition is checked before the loop is executed.

int ch=10;do{

cout<<”Iam an executable statement”;}while(ch!=10);

Page 117: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 8 : Control Structures Chapter 8 : Control Structures This will print the message once as the condition checking is done after the loop is executed. Had it been a while loop then the message would not have been printed at all.

Okay! The mantra is Use a for loop for finite iterations, a while loop when number of iterations are not known and a do while loop if the loop has to be executed at least once.

Page 118: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

Two dimensional arraysTwo dimensional arrays

One dimensional arraysOne dimensional arrays

Arrays(Creation and initialization)Arrays(Creation and initialization)

Arrays and stringsArrays and strings

Page 119: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Arrays are collections of homogenous elements in continuous locations of memory having the same name.

Why arrays?

Most of the C application require the processing of large number of data. The data may be identical and to be stored in sequential memory location. So we share same name to to point a set of identical data. So array is a collection of similar elements. these similar elements may be int, char etc.

Three words- homogenous elements, continuous locations and same name I'll remember that!

Chapter 9: ArraysChapter 9: Arrays

Page 120: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

Array Declaration

Like any other variable array need to be declared.

eg: int marks[60];char message[40];

int specifies the type of variable stored in the array marks. 60 tells the compiler the number of elements to be stored in the array.

note:- Compiler never gives error if you enter more than 60 elements in the array. However, elements may go into the memory area not reserved by compiler for the array. This may cause data corruption . So a proper check must be put in the program so that user may not enter data more than the maximum specified limit.

Page 121: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

Accessing Array elementAll the array element are given a label starting from 0. marks[0] specifies the first element stored in the array. Similarly marks[20] is the twenty-first element of the array. Thus the same variable name have different content depending on it's label.

Entering Data into an Arrayfor (i=0;i<=59;i++){

printf("\n Enter marks");scanf("%d",&marks[i]);

}

Page 122: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: ArraysThe for loop can be used to enter the data into array. The loop goes 60 times each time storing an element into the array.

note: We need not go for reading marks[60] as it will go out of bound.

Array initialization

note: In initialization, declaring the size of the array is optional.

If a array element is not initialized, it carries garbage value.

int number[5] ={1,2,3,4,5};int n[]={1,2,3};

Page 123: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

As soon as array is declared, compiler allocates the space to the array. Each memory space has its unique address where a particular value is stored.

An Example Write a program to read marks of 60 student in the class and calculate the class average.

main(){

float avg, sum=0;int i, marks[60];

Page 124: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

for (i=0;i<60;i++){

printf("\n Enter marks");scanf("%d", &marks[i]);

}

for (i=0;i<=59;i++)sum=sum+marks[i];

avg=sum/60;printf("\nAverage marks of the class is: %f",avg);

}

Page 125: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: ArraysTwo Dimensional arrays

A m*n array can be thought of with m rows and n column so as to keep track of values in the tabular form.for example: A two dimensional array containing float type data with maximum 10 rows and 10 column can be declared as

float table[10][10];

note: This table may contain a maximum of 100 element, though the compiler will not complain if you enter more than 100 element but this may lead to data corruption. So a check on upper limit must be there in the program.

Page 126: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

An Example on Two Dimensional array

Write a program to add two n*n matrix. A n*n matrix may be viewed as the table with n rows and n column. Each cell in the table contain a value to be entered by user.main(){

int n, a[10][10], b[10][10], c[10][10];

printf("enter the number of rows and column.The number of rows and column must be less than 10");

Page 127: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

scanf ("%d", &n);printf("enter first matrix ");for ( int i=0;i<n;i++)

for (int j=0;j<n;j++)scanf ("%d", &a[i][j]);

for ( i=0;i<n;i++)for (j=0;j<n;j++)

scanf ("%d", &b[i][j]);for ( i=0;i<n;i++)

for (j=0;j<n;j++)c[i][j]=a[i][j]+b[i][j];

for( i=0;i<n;i++) {printf('\n');for (j=0; j<n; j++)

printf("%d ", c[i][j]);}

Page 128: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

note: A two dimension array can be read or written out using two nested loop. In the above example, inner loop causes one row to be read from the user while outer loop and outer loop controls the rows.

In printing the matrix after adding ,we are changing line after each row so as to give tabular look.

I can have arrays three dimensions too, but two itself is complex enough!

Page 129: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arrays

Arrays and Strings Strings or simply any text are nothing but one dimensional array of characters. Each character within the string will be stored within one element of the array.

eg:char text[] = "electronics";

There are 12 element in this array , 11 for the word and 1 for null character(\0) which is added automatically at the end of the string. There are different library function under the header file string.h which processes the string.

Page 130: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 9: ArraysChapter 9: Arraysfor example:

strlen(s) will return the number of character in the string.strcpy(s1,s2) copy string s2 to string s1.

The bottomline is character arrays have a terminator at the end.

Page 131: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 10: FunctionsChapter 10: Functions

What are functions?What are functions?

Prototype of functionsPrototype of functions

Page 132: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 10: FunctionsChapter 10: Functions

Every C program is a collection of functions. Even main() is a function. Program execution always begins with main(). A function is a set of instructions that does something.

Why functions?

i) Writing function avoids rewriting the same code over and over again. Suppose it is required to find the number of ways of choosing r element out of n element (i.e. n! / r! * (n-r)!). For this finding the factorial 3 times is a tedious job. So it would be preferable to jump to factorial subprogram three times and return to the main program.

What are functions?What are functions?

Page 133: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 10: FunctionsChapter 10: Functionsii) Functions help us to organize our work very well and keep track of what we are doing. This way the work can be divided into separate smaller modules called functions and then combined together.

Example:

#include<stdio.h>void test();void again(); main() {printf ("\n Hello! I am in main");test();

Page 134: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 10: FunctionsChapter 10: Functions

{

printf ("Are you there");}

void again() {printf ("I'm here again");

}

again();test();

}

void test()

Output:

Hello! I'm in main.

Page 135: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 10: FunctionsChapter 10: Functions

Are you thereI'm here againAre you there

Explanation: void test(); and void again(); are the function prototypes or declarations so that the compiler knows that these functions are going to come later in the program. void specifies that function returns nothing to the place where it is called.test(); and again(); are the function calls.void test() and void again() are the function headers from where the function definition starts.

Page 136: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 10: FunctionsChapter 10: Functions

A function has a name, return type and a set of arguments and arguments are optional

Function arguments and ReturnLet's see a function call avg = calavg(a,b,c);

On calling this function in main, function will return and assign average of three numbers a, b, c to the variable avg. a, b, c are the function arguments and are called actual arguments.

Function can be defined as:-

float calavg( int x, int y, int z){return (x+y+z) / 3; }

Page 137: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 10: FunctionsChapter 10: Functions

x, y, z are the formal arguments. Actual arguments and formal parameters may be the same. The return statement returns the value following it to the calling program. float specifies the type of value that is to be returned by the function.

Page 138: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 11:ADVANCED CONTROL CONSTRUCTS Chapter 11:ADVANCED CONTROL CONSTRUCTS

Some more control constructs-

goto,continue,break statementsSome more control constructs-

goto,continue,break statements

Page 139: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Let's revise and add some more to what we have already learnt.

Chapter 11:ADVANCED CONTROL CONSTRUCTS Chapter 11:ADVANCED CONTROL CONSTRUCTS

The do-while statement

Sometimes it is required to execute the loop at least one time, we use do-while loop.

example:do {

..........(do some computation)printf("Do you want to continue the computation. enter y for

yes");

Page 140: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 11:ADVANCED CONTROL CONSTRUCTS Chapter 11:ADVANCED CONTROL CONSTRUCTS

scanf("%c", ch); } while ( ch = ='y');

Again and again this message comes on the screen till you enter 'y' and at least one time the computation will go on with this message. switch statementIn order to avoid the great size of if else statement, we use switch statement. The general form is :switch (expression)

{ case expression 1: statement; ..........

case expression m: statement; }

Page 141: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 11:ADVANCED CONTROL CONSTRUCTS Chapter 11:ADVANCED CONTROL CONSTRUCTS

note: expression must result to only either integer or character type.

example:

switch (grade) {case10: printf ("excellent"); break;case 9:case 8: printf ("good"); break;case 7:case 6: printf ("average"); break;case 5:case 4:case 3:

Page 142: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 11:ADVANCED CONTROL CONSTRUCTS Chapter 11:ADVANCED CONTROL CONSTRUCTS

case 2:case 1: case 0: printf ("improve"); break;default: printf ("Wrong entry");}

break statement is used so that control comes out of the switch block or any other block under braces {}where it is used.

note: If your grade is 9, then control flows from case 9: to case 8:statement and a message good comes on screen.

Page 143: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 11:ADVANCED CONTROL CONSTRUCTS Chapter 11:ADVANCED CONTROL CONSTRUCTS

As the continue statement is met ,the next part of the loop is skipped and computation proceeds directly to the next pass through the loop.for example:

for ( i =1; i <=10 ; i++) {scanf ("%f" , &a);if ( x<0) {

printf("error : negative number not allowed");continue;

}. . . . . . . . . . . . (process the non negative number.)

}

The continue statement

Page 144: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 11:ADVANCED CONTROL CONSTRUCTS Chapter 11:ADVANCED CONTROL CONSTRUCTS

note: This program neglects the negative number and asks for the nextentry by going back to the top of loop as soon as it encounters the continue statement. Had it been break statement instead of continue statement, control would have come out of the loop without doinganything as soon as it found the negative number.

exit() function It is a standard library function. When it gets executed the program execution is immediately terminated. It is worth noting that a break statement would have taken the control outside the loop or switch statement whereas exit() transfers the control outside the program.

Page 145: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

goto statement

Chapter 11:ADVANCED CONTROL CONSTRUCTS Chapter 11:ADVANCED CONTROL CONSTRUCTS

goto statement transfers the control from one part to any other part of the program. However, use of goto should be avoided.

note: If the condition is satisfied the goto statement transfers control to the label msg causing printf() following msg to be executed.

example: if (ans= = 5) goto msg;........................................................msg: printf ("With good programming skills use of goto can

always be avoided");

Page 146: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 12: STORAGE CLASS AND SCOPE RULES Chapter 12: STORAGE CLASS AND SCOPE RULES

Auto,static and extern variablesAuto,static and extern variables

Lifetime and scope of these variables Lifetime and scope of these variables

Page 147: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 12: STORAGE CLASS AND SCOPE RULES Chapter 12: STORAGE CLASS AND SCOPE RULES

Storage class refers to the visibility of a variable and its scope within the program i.e. the portion of the program over which the variable is recognized. There are four different storage class in C: automatic, external, static and register which are identified by the keywords auto, extern, static and register respectively. They are classified depending on the following four parameters:

1)storage: where these variables are stored.2)default initial value: value assigned to the variable at the time of declaration.3)scope: refers to the portion of program over which the variable is recognized.4)life: how long would the variable exist.

Page 148: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 12: STORAGE CLASS AND SCOPE RULES Chapter 12: STORAGE CLASS AND SCOPE RULES

STORAGE CLASS

STORAGE DEFAULT INITIAL VALUE

SCOPE LIFE

auto memory garbage value

local to the block where it is defined

till the control remains within the block in which the variable is defined.

register CPU registers (fastest memory)

garbage value

local to the block where it is defined

till the control remains within the block in which the variable is defined.

Page 149: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 12: STORAGE CLASS AND SCOPE RULES Chapter 12: STORAGE CLASS AND SCOPE RULES

STORAGE CLASS STORAGE DEFAULTINITIAL VALUE

SCOPE LIFE

static memory zero local to the block where it is defined.

value of variable persists between different function calls.

extern memory zero global throughout the program

note: Default storage class for a variable is auto.

Page 150: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 12: STORAGE CLASS AND SCOPE RULES Chapter 12: STORAGE CLASS AND SCOPE RULES

Variables declared have a certain scope I see or maybe I can't see!!

Page 151: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 12: STORAGE CLASS AND SCOPE RULES Chapter 12: STORAGE CLASS AND SCOPE RULES

Local Variables

The variables declared within the function are called local variable because scope of these type of declaration of variable only exist to the function in which they are defined. The local variables are declared at the start of function body.Example: int sum(){int x, y, s;.............} int difference(){int x, y, s;..............}

The variables x,y,s which are declared in both the functions are local and have different memory allocation. They have no relation among themselves.

Page 152: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 12: STORAGE CLASS AND SCOPE RULES Chapter 12: STORAGE CLASS AND SCOPE RULES

Global Variables

The scope of global variable remains throughout the program. Also, they hold their values during the entire execution of the program. Global variables are always declared outside of all functions.It is used when a variable must be accessible to more than one function. However, external variables create organizational problem for the very reason that they can be accessed by any function. The wrong function may access them or function may access them incorrectly.

Global variables I can always see, local variables I can see only within the local block0

Page 153: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Scope rules of functions

By default the scope of a variable is local to the function in which it is defined. Hence a variable defined in main() is local to the main() function and similarly a variable defined in a subprogram has to be returned to make it available in the calling function.

Chapter 12: STORAGE CLASS AND SCOPE RULES Chapter 12: STORAGE CLASS AND SCOPE RULES

Page 154: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 13: ADVANCED FUNCTIONSChapter 13: ADVANCED FUNCTIONS

Methods of parameter passingMethods of parameter passing

Call by valueCall by value

•Call by reference•Call by reference

•Functions and arrays•Functions and arrays

Page 155: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 13: ADVANCED FUNCTIONSChapter 13: ADVANCED FUNCTIONS

Now that we have seen functions and their usage, let us look into the various conceptsBefore we proceed to these important concepts, let us understandsomething about the function. A function is only a set of instructions and the function name is a pointer to the start of the instructions which make the function. So when a function is called, the control switches from the caller function to the called function. After the function is executed the control returns back to the caller.

There are two ways of passing parameters: 1.call by value and 2. call by reference.

13.1 Methods of parameter passing13.1 Methods of parameter passing

Page 156: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 13: ADVANCED FUNCTIONSChapter 13: ADVANCED FUNCTIONS

In the first method value is passed to a function via actual argument. Value of actual argument is copied into the formal argument in the function. Therefore, the value of corresponding formal arguments can be altered within the function but the value of actual argument within the calling routine will not change.Example: main(){int x=10, y=20;swap(x,y);printf("\n x=%d y=%d", x, y);} swap( int a, int b){int temp;

13.2 Call by value13.2 Call by value

a=b;

Page 157: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 13: ADVANCED FUNCTIONSChapter 13: ADVANCED FUNCTIONS

printf("\n a=%d b=%d", a, b);}output: a=20 b=10

x=10 y=20note: The value of x and y remain unchanged even after exchanging thevalue of a and b.

b=temp;

13.3 Call by reference13.3 Call by referenceIn the second method (call by reference), the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This will facilitate the programmer to access the actual arguments and hence will be able to manipulate them. Addresses of the actual argument are sent from the calling program throughaddress of or & operator while they are received in the called function by the pointer variable.

Page 158: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 13: ADVANCED FUNCTIONSChapter 13: ADVANCED FUNCTIONS

13.4 Functions and arrays13.4 Functions and arrays

The entire array can be passed to a function as an argument.

Example:

float avg (int , int []); //function prototype main(){int x, lot[100]; float average;...............average= avg (x, lot); //function call...............}float avg (int n, int a[]) //function definition{....................}

Page 159: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 13: ADVANCED FUNCTIONSChapter 13: ADVANCED FUNCTIONS

Explanation: When declaring a one-dimensional array as formal argument the array name is written as pair of empty square braces while the size must be declared in the main function at the time of declaration. To pass an array to a function the array name must appear by itself, without bracket, as actual argument within the function call.

argc and argvThe arguments that we pass on to main() at the command prompt are called command line arguments. The function main can have two arguments, argc and argv. Out of these argv is an array of pointers to strings and argc is an integer whose value is equal to the number of strings to which argv points. When the program is executed the string on the command line are passed to main(). More precisely the string at command line are stored in memory and addresses of first string is stored in argv[0] , and so on.

Page 160: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 13: ADVANCED FUNCTIONSChapter 13: ADVANCED FUNCTIONS

If I pass the value to the function , I am doing it by call by value, and If I pass the addresses of the arguments I am going for call by reference.Can we have the advantages and disadvantages please?

Call by value:

Advantages: 1. Simple mechanism 2. Used in calling functions with few argumentsDisadvantages: Memory wastage as the variables are duplicated

Call by reference:

Advantages: 1. Used when one need not return a value or indirectly return more than one value2.Useful in passing arraysDisadvantages: More complicated than the previous mechanism.

Page 161: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 14: RECURSIONChapter 14: RECURSION

•An example showing the working of recursive process•An example showing the working of recursive process

•Define recursion •Define recursion

Page 162: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Recursion is a low level feature of the 'C' language. It is a very powerful mechanism of doing complicated programs and reducing the size of the programs.Recursion is a process by which the function calls itself repeatedly until some specified condition has been satisfied. Also referred to as 'circular definition', recursion is thus the process of defining ion terms of own self.

Chapter 14: RECURSIONChapter 14: RECURSION

14.1 Define recursion 14.1 Define recursion

Conditions that are to be satisfied for a recursive problem:

•The problem must be written in recursive form.•The problem statement must include a stopping condition.

Page 163: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 14: RECURSIONChapter 14: RECURSION

For example: In recursive form n! = n * (n-1)! and stopping condition is 1! = 1.

Calculating Factorial of number n#include <studio.h>

long int factorial(int n); main(){

int n;printf(" \nEnter the number whose factorial is to be calculated\n");scanf("%d", &n);

Example showing the working of recursive process

Page 164: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

printf("n! = %ld\n", factorial(n));}long int factorial(int n){

if (n<= 1)return(1);

elsereturn (n * factorial(n-1));

} The function call will proceed in the following way:

n! = n*(n-1)!(n-1)! = (n-1)* (n-2)!---------------------2! = 2 * 1!

Chapter 14: RECURSIONChapter 14: RECURSION

Page 165: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 14: RECURSIONChapter 14: RECURSION

That is excellent! The factorial program looks very small using recursion

Page 166: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 15: POINTERSChapter 15: POINTERS

Arrays and PointersArrays and Pointers

What are pointers?What are pointers?

Pointer ArithmeticPointer Arithmetic

ExercisesExercises

Array of PointersArray of Pointers

Pointers and stringsPointers and strings

Two dimensional arrays and pointersTwo dimensional arrays and pointers

Page 167: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 15: POINTERSChapter 15: POINTERS

What is a Pointer?

o A pointer is a variable which contains the address in memory ofanother variable. We can have a pointer to any variable type.

o Pointers are basically the same as any other variable. However,what is different about them is that instead of containing actual information, they contain a pointer to the memory location whereinformation can be found. This is a very important concept, and many programs and ideas rely on pointers to be able to carry outtheir tasks, linked lists for example.

o So what is a pointer? A pointer is a way to get at another object. Essentially it is a way to grab an instance of an object and then either pass that instance a message or retreive some data from that object.

Page 168: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 15: POINTERSChapter 15: POINTERS

oA pointer is actually just an address of where an instance is held in memory.

The unary or monadic operator & gives the ``address of a variable''.

The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.

To declare a pointer to a variable do:

int *pointer;

note: We must associate a pointer to a particular type: You can't assign the address of a short int to a long int, for instance.

Page 169: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 15: POINTERSChapter 15: POINTERS

It is worth considering what is going on at the machine level in memory to fully understand how pointer work. . Assume for the sake of this discussion that variable x resides at memory location 100, y at 200 and ip at 1000. Note A pointer is a variable and thus its values need to be stored somewhere. It is the nature of the pointers value that is new.Pointer, Variables and Memory Now the assignments x = 1 and y = 2

obviously load these values into the variables. ip is declared to be a pointer to an integer and is assigned to the address of x (&x). So ip gets loaded with the value 100.

Next y gets assigned to the contents of ip. In this example ip currently points to memory location 100 -- the location of x. So y gets assigned to the values of x -- which is 1.

Page 170: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 15: POINTERSChapter 15: POINTERS

We have already seen that C is not too fussy about assigning values of different type. Thus it is perfectly legal (although not all that common) to assign the current value of ip to x. The value of ip at this instant is 100.

Finally we can assign a value to the contents of a pointer (*ip).

IMPORTANT: When a pointer is declared it does not point anywhere. You must set it to point somewhere before you use it.

Page 171: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 15: POINTERSChapter 15: POINTERS

So ...

int *ip; *ip = 100;

will generate an error (program crash!!). The correct use is:

int *ip;

int x;

ip = &x;

*ip = 100;

We can do integer arithmetic on a pointer:

float *flp, *flq;

*flp = *flp + 10;

++*flp;

Page 172: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 15: POINTERSChapter 15: POINTERS

(*flp)++;

flq = flp;note: A pointer to any variable type is an address in memory -- which is an integer address. A pointer is definitely NOT an integer.Data is stored in memory like this :The reason we associate a pointer to a data type is so that it knows how many bytes the data is stored in. When we increment a pointer weincrease the pointer by one ``block'' memory.So for a character pointer ++ch_ptr adds 1 byte to the address.For an integer or float ++ip or ++flp adds 4 bytes to the address.Consider a float variable (fl) and a pointer to a float (flp)Pointer Arithmetic Assume that flp points to fl then if we increment the

pointer ( ++flp) it moves to the position shown 4 bytes on. If on the other hand we added 2 to the pointer then it moves 2 float positions i.e 8 bytesas shown in the Figure.

Page 173: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: STRUCTURESChapter 16: STRUCTURES

What are Structures?What are Structures?

Referencing elements of a StructureReferencing elements of a Structure

Pointers to StructuresPointers to Structures

Page 174: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: STRUCTURESChapter 16: STRUCTURES

Structures are collections of heterogenous elements in continuous locations of memory having same name.

Hey! This sounds very similar!

Structures are different from arrays only with respect to the type of elements, ie. homogenous in case of arrays and heterogenous in case of structures.

Why structures?

An ordinary variable can store one piece of data and an array can store large number of data but of same data-type. Structure is the data type which can store large number of data of different data type. Suppose in a class there are 60 student, you want to store the name (string), age (integer), marks (integer) of each student.

Page 175: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: STRUCTURESChapter 16: STRUCTURES

This can be done by defining structure variable as follows:struct class{

char name[20];int age;int marks;

};struct student[60];

Now each array element student[i] has memory space corresponding to three variable name, age and marks.

note: To declare a structure the above group of statement is used. Ifyou want to add more element to the structure you can very well do it.

Always declare structure outside main() above main().

Page 176: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: STRUCTURESChapter 16: STRUCTURES

Referencing Structure element

In array we can access individual element of an array using a subscript like a[i]. Structure use dot(.) operator to access its element. If you want to access the age of i-th student in the class, use

student[i].agenote: It is not necessary to have structure variable to be an array always. You can have single structure variable like

struct student1;

note: A structure variable can be assigned to another structure variable. In this case all the element of the first variable will be assigned to corresponding variable in the second variable.

Page 177: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: STRUCTURESChapter 16: STRUCTURES

student[1] = student [2]; is same as

student[1].name = student[2].name;

student[1].age = student[2].age;

student[1].marks = student[2].marks

Page 178: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: STRUCTURESChapter 16: STRUCTURES

example:struct address{

char city[20];long pin;

}struct person{

char name[20];struct address a;

}person allen;

note: One structure can be nested within another structure.

To access the pin variable of allen use allen.address.pin which looks very logical.

Page 179: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: STRUCTURESChapter 16: STRUCTURES

Passing entire structure to function

If structure is declared before main() as declared in the first example, thenvoid display( struct class);main(){struct student[0] ={"allen", 17, 78};display(student[0]);

}display (struct class s){

printf("\n %s %d %d", s.name, s.age, s.marks);}

output is allen 17 78

Page 180: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 16: STRUCTURESChapter 16: STRUCTURES

note: Watch closely the way function is being called, declared and defined.Structure Pointer

Consider the following statementsclass *ptr;ptr = &student[0];

Here, The pointer is pointing to first element of the variable student[0] i.e. student[0].name.Dot(.) operator can not be used with the pointer variable. If you want to refer to student[0].marks, C provides the -> arrow operator i.e. ptr->marks refer to the structure variable.

Page 181: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Example:main(){struct student[0] ={"allen", 17, 78};display(&student[0]);

}display (struct class *ptr){

printf("\n %s %d %d", ptr->name, ptr->age, ptr->marks);}output is allen 17 78

Chapter 16: STRUCTURESChapter 16: STRUCTURES

note: To access the structure elements using pointer to a structure use '>' operator.

Page 182: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Unions

Chapter 17: UNIONSChapter 17: UNIONS

UnionsUnions

Typedef KeywordTypedef Keyword

Enumerated DatatypesEnumerated Datatypes

Page 183: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 17: UNIONSChapter 17: UNIONS

Unions, like, structure contains elements whose individual data type may differ from one another. However the difference is there in the way they are stored in the memory. each member element of a structure variable is given its own storage area but all member element within the union share the same memory block only one at a time.

Declarationunion person {

char name[10];int age ;

} p1;the union person has two member and p1 is an union variable of type person.

Page 184: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 17: UNIONSChapter 17: UNIONS

note: name[10] require 10 bytes and age require 2 byte. So memory provided to the union variable p1 is maximum of two i.e. 10 byte instead of 12 byte.

An union variable can be initialized provided its storage class is either extern or static. Only one member of an union can be assigned a value at one time.

All union operation works similar to that of structure.

Enumerated Data type

Your own data type can be created and variable of this data type can be given different value.enum is the keyword used for this purpose.

Page 185: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 17: UNIONSChapter 17: UNIONS

example: enum Boolean = {FALSE, TRUE};

FALSE is assigned the integer value 0 and TRUE is assigned 1.

enum month = { JAN = 1, FEB, MARCH, APRIL };JAN is assigned 1, FEB is assigned 2 and so on.

The variable JAN, FEB, TRUE, FALSE can be used with the values 1, 2, 1, 0 respectively in the program.

Page 186: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 17: UNIONSChapter 17: UNIONS

To make the code more clear and easy to understand, we can define the name of the existing data type using the keyword typedef.

example: typedef char ONETEXT;

Now for declaring the variable t1 and t2 of type char, writeONETEXT t1,t2;

rather thanchar t1, t2;

Page 187: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 18:FILE HANDLINGChapter 18:FILE HANDLING

Files Files

Reading/Writing from/to files Reading/Writing from/to files

File functions File functions

Page 188: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 18:FILE HANDLINGChapter 18:FILE HANDLING

Till now, you have entered data from the keyboard. However, in many application dealing with large number of data, data are kept stored in the form of data file. C provides you the facility to read and write data file. For file handling, a buffer area is to be established where information is stored temporarily while being transferred between the computer's memory and data file.

This is done byFILE *fptr;

where *fptr is the file pointer.

Page 189: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 18:FILE HANDLINGChapter 18:FILE HANDLING

Next step is to open the file. to open a filefptr = fopen ("data.txt" , "r");

Here, "data.txt" is the data file name."r" is the mode in which file is opened. "r" stands for reading

mode (reading from file).Other mode are:

"w" - write mode (writing into new file)"a" - append mode (appending into existing file)"r+" - read and write mode both"w+" - read and write mode both

note: In the "w" and "w+" mode, if the file name specified already exist, it get deleted. In "a" mode, a new file will be created if the specified file name does not exist.

Page 190: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 18:FILE HANDLINGChapter 18:FILE HANDLING

Writing into the file

The following program gets a line of text from the keyboard and put it into the file data.txt.

main(){

FILE *fptr;fptr = fopen ("data.txt" , "w");do

putc( char c = getchar(), fptr);while ( c!= '\n');

}

note: putc (character variable, file pointer) command puts the content of the character variable into the file signified by fptr.

Page 191: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 18:FILE HANDLINGChapter 18:FILE HANDLING

Reading from a File

getc(fptr) is the command used for getting a single character from the file signified by fptr. As soon as the first character is retrieved, pointer points to the next character in sequence in data file.

If the file does not exist, file pointer gets NULL assignment. So to check it, use the following code after opening the file:

if (fptr = = NULL)printf ("\nERROR- can not open file");

Page 192: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

fprintf() and fscanf()

The general form of fprintf() instruction isfprintf (file pointer, "control string", variable name);

example: fprintf( fptr, "\n%s", text);This will put the content of the string variable text into the file.

The general form of fscanf() instruction is fscanf ( (file pointer, "control string", variable name);

example: fscanf( fptr, "\n%s", text);This will read a string from the file and put it into the variable text.

Chapter 18:FILE HANDLINGChapter 18:FILE HANDLING

Page 193: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 19:C PREPROCESSORSChapter 19:C PREPROCESSORS

MacrosMacros

ProcessorsProcessors

Conditional CompilationConditional Compilation

Page 194: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

C preprocessor is a program that processes our source program before it is passed to the compiler.

Macro definition#define, also known as the Macro expansion directive (macro substitution) is used to replace an identifier in a program by a predefined string composed of one or more tokens. The common forms of macro substitution are:1)Simple macro substitutionex. #define PI 3.1415926 2)Argumented macro substitutionex. #define SQUARE(x) (x*x)3)Nested macro substitutionex. #define SQUARE(x) (x*x)

#define CUBE(x) (SQUARE(x)*x)

Chapter 19:C PREPROCESSORSChapter 19:C PREPROCESSORS

Page 195: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 19:C PREPROCESSORSChapter 19:C PREPROCESSORS

File inclusion

In order to include an external file containing functions or macro definitions in a program we use the #include<filename> directive. The preprocessor includes the entire contents of filename into the source code of the program.

Filename included between double quotation marks("") is first searched in the current directory and then in the standard directories. ex. #include "test.c"Filename included between <> is searched only in the standard directories. ex. #include<stdio.h>note: A file cannot include itself.

Page 196: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 19:C PREPROCESSORSChapter 19:C PREPROCESSORS

Conditional compilation

To achieve conditional compilation, under the following cases:

1) To comment obsolete lines of code, i.e. code of program which is not required at present.2) To make the program portable, depending on the different types of computers.

Page 197: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 19:C PREPROCESSORSChapter 19:C PREPROCESSORS

We can insert the preprocessing commands, #ifdef and #endif, having the general form

#ifdef macronamestatement 1;statement 2;statement 3;

#endif .

Instead of #ifdef we may also use #ifndef directive (if not defined) which works just opposite to #ifdef.

Page 198: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Besides these directives we may also use #if and #elif directive to test an

expression.

note: Some miscellaneous directives are also provided by C viz.

#undef (to undefine an already defined macro ) and #pragma.

Chapter 19:C PREPROCESSORSChapter 19:C PREPROCESSORS

ex. #if (expression)statement 1;statement 2;

#else statement 3;statement 4;

#endif

Page 199: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 20:C STANDARD LIBRARY & HEADER FILESChapter 20:C STANDARD LIBRARY & HEADER FILES

Library FunctionsLibrary Functions

Header FilesHeader Files

Page 200: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 20:C STANDARD LIBRARY & HEADER FILESChapter 20:C STANDARD LIBRARY & HEADER FILES

Library functions

They are prewritten functions or routines that carry out the various commonly used operations or calculations. Library functions are contained within the library files provided with all C compilers.

Library files

While converting the C source program into an executable object program, the compiled source program is linked with one or more library files to produce the final executable code. This requires the source program to include declarations for the library functions, which are contained in the library files.

Page 201: Course ModulesCourse Modules Chapter 1: Introduction to …€¦ · Chapter 1: Introduction to Program Design Chapter 1: Introduction to Program Design Outlining the program structure

Chapter 20:C STANDARD LIBRARY & HEADER FILESChapter 20:C STANDARD LIBRARY & HEADER FILES

Header files

Header files are the special source files which contain the required library-function declarations which are related to each other.ex. math.h contains the declarations for various mathematical functions.

time.h contains the declarations for various time and date functions.

string.h contains the declarations for various string functions