0% found this document useful (0 votes)
46 views113 pages

C Language Overview for Beginners

- C was invented in 1972 by Dennis Ritchie at Bell Labs to write the UNIX operating system. - It is a structured, procedural programming language that derives from earlier languages like B. - The "Hello World" program demonstrates the basic structure of a C program, including main function, header file inclusion, printf statement, and return value.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views113 pages

C Language Overview for Beginners

- C was invented in 1972 by Dennis Ritchie at Bell Labs to write the UNIX operating system. - It is a structured, procedural programming language that derives from earlier languages like B. - The "Hello World" program demonstrates the basic structure of a C program, including main function, header file inclusion, printf statement, and return value.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 113

7.

Introduction to C

7.1 C – Language History

• C language is a structure oriented programming language, was developed at Bell Laboratories in


1972 by Dennis Ritchie
• C language features were derived from earlier language called “B” (Basic Combined
Programming Language – BCPL)
• C language was invented for implementing UNIX operating system
• In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language” and commonly known as K&R C
• In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”,
was completed late 1988.

7.2 C standards

• C89/C90 standard – First standardized specification for C language was developed by American
National Standards Institute in 1989. C89 and C90 standards refer to the same programming
language.
• C99 standard – Next revision was published in 1999 that introduced new futures like advanced
data types and other changes.

C11 and Embedded C

• C11 standard adds new features to C and library like type generic macros, anonymous
structures, improved Unicode support, atomic operations, multi-threading, and bounds-checked
functions. It also makes some portions of the existing C99 library optional, and improves
compatibility with C++.
• Embedded C includes features not available in normal C like fixed-point arithmetic, named
address spaces, and basic I/O hardware addressing
• Operating systems, C compiler and all UNIX application programs are written in C language

• It is also called as procedure oriented programming language  C language is reliable, simple and
easy to use.
• C has been coded in assembly language

7.3 Features of C language:

1
• Reliability
• Portability
• Flexibility
• Interactivity
• Modularity
• Efficiency and Effectiveness

7.4 Uses of C language:

C language is used for developing system applications that forms major portion of operating systems
such as Windows, UNIX and Linux. Below are some examples of C being used.

• Database systems
• Graphics packages
• Word processors
• Spread sheets
• Operating system development
• Compilers and Assemblers
• Network drivers
• Interpreters

Which level the C language is belonging to?


S.n High Level Middle Level Low Level
o
High level languages provides Middle level languages don’t provide Low level languages
almost everything that the all the built-in functions found in high provides nothing other
1 programmer might need to do level languages, but provides all than access to the
as already built into the building blocks that we need to machines basic
language produce the result we want instruction set
Examples:
2 C, C++ Assembler
Java, Python
C language is a structured language
S.n Structure oriented Object oriented Non structure
o
1 In this type of language, large In this type of language, programs There is no specific
programs are divided into small are divided into objects structure for programming
programs called functions this language

2 Prime focus is on functions and Prime focus is on the data that is N/A

2
being operated and not on the
procedures that operate on data
functions or procedures
Data moves freely around the
Data is hidden and cannot be
3 systems from one function to N/A
accessed by external functions
another
Program structure follows “Top Program structure follows “Bottom
4 N/A
Down Approach” UP Approach”
Examples:
5 C++, JAVA and C# (C sharp) BASIC, COBOL, FORTRAN
C, Pascal, ALGOL and Modula-2
7.5 Key points to remember:

1. C language is structured, middle level programming language developed by Dennis Ritchie


2. Operating system programs such as Windows, Unix, Linux are wriiten by C language
3. C89/C90 and C99 are two standardized editions of C language
4. C has been written in assembly language

Further Reading:
http://www.tutorialspoint.com/cprogramming/
http://www.cprogramming.com Summary:

• C was invented to write an operating system called UNIX.


• C is a successor of B language which was introduced around 1970
• The language was formalized in 1988 by the American National Standard Institue (ANSI).
• By 1973 UNIX OS almost totally written in C.
• Today C is the most widely used System Programming Language.
• Most of the state of the art software have been implemented using C
Exercises

A.Objective Type Questions:


1. Which of the following language is predecessor to C Programming Language?

ABBCPLC++

2. C programming language was developed by

Dennis RitchieKen ThompsonBill GatesPeter Norton

3. C was developed in the year ___

3
1970197219761980

4. C is a ___ language

High LevelLow LevelMiddle LevelMachine Level

4
8 Basic Program

We are going to learn a simple “Hello World” C program in this section. Also, all the below topics are
explained in this section which are the basics of a C program.

1. C basic program with output and explanation


2. Steps to write C programs and get the output
3. Creation, Compilation and Execution of a C program
 How to install C compiler and IDE
4. Basic structure of a C program

C Basic Program:
#include <stdio.h>

int main()
{
/* Our first simple C basic program */
printf("Hello World! "); getch();
return 0;
}

Output:

Hello World!

Explanation for above C basic Program:

Let’s see all the sections of the above simple C program line by line.
S.no Command Explanation
This is a preprocessor command that includes standard input output
1 #include <stdio.h>
header file(stdio.h) from the C library before compiling a C program
2 int main() This is the main function from where execution of any C program begins.
3 { This indicates the beginning of the main function.
whatever is given inside the command “/* */” in any C program,
4 /*_some_comments_*/
won’t be considered for compilation and execution.
5 printf(“Hello_World! “); printf command prints the output onto the screen.
6 getch(); This command waits for any character input from keyboard.
7 return 0; This command terminates C program (main function) and returns 0.

5
8 } This indicates the end of the main function.
8.1 Steps to write C programs and get the output:

Below are the steps to be followed for any C program to create and get the output. This is common
to all C program and there is no exception whether its a very small C program or very large C program.

1. Creation, Compilation and Execution of a C program:


Prerequisite:

o If you want to create, compile and execute C programs by your own, you have to install C
compiler in your machine. Then, you can start to execute your own C programs in your
machine. o You can refer below link for how to install C compiler and compile and execute C
programs in your machine. o Once C compiler is installed in your machine, you can create,
compile and execute C programs as shown in below link.

C – Environment Setup Using IDE tool C –

Environment Setup Using GCC compiler

8.2. Basic structure of C program:

Structure of C program is defined by set of rules called protocol, to be followed by programmer while
writing C program. All C programs are having sections/parts which are mentioned below.

1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
6
Example C program to compare all the sections:

You can compare all the sections of a C program with the below C program.

1 /* C basic structure program Documentation section


2 Author: fresh2refresh.com
3 Date : 01/01/2012
4 */
5 #include <stdio.h> /* Link section */
6 int total = 0; /* Global declaration and definition section */
7 int sum (int, int); /* Function declaration section */
8 int main () /* Main function */
9 {
10 printf ("This is a C basic program \n");
11 total = sum (1, 1);
12 printf ("Sum of two numbers : %d \n", total);
13 return 0;
14 }
15 int sum (int a, int b) /* User defined function */
16 { /* definition section */
17 return a + b; 18 }

Output:

This is a C basic program


Sum of two numbers : 2

8.3 Description for each section of a C program:

o Let us see about each section of a C basic program in detail below.


o Please note that a C program mayn’t have all below mentioned sections except main
function and link sections.
o Also, a C program structure mayn’t be in below mentioned order.
S.No Sections Description
We can give comments about the program, creation or modified
date, author name etc in this section. The characters or words or
anything which are given between “/*” and “*/”, won’t be
1 Documentation section
considered by C compiler for compilation process.These will be
ignored by C compiler during compilation. Example : /* comment
line1 comment line2 comment 3 */

7
Header files that are required to execute a C program are included in this
2Link Section section

3 Definition Section In this section, variables are defined and values are set to these variables.
4 Global declaration Global variables are defined in this section. When a variable is to be
used
section throughout the program, can be defined in this section.

Function prototypeFunction prototype gives many information about a function like


return
5 declaration sectiontype, parameter names used inside the function.
Every C program is started from main
function and this function contains
6Main function two major sections called declaration section and executable
section.
User defined function User can define their own functions in this section which perform
7
section particular task as per the user requirement.
C – printf and scanf

• printf() and scanf() functions are inbuilt library functions in C which are available in C library by
default. These functions are declared and related macros are defined in “stdio.h” which is a
header file.
• We have to include “stdio.h” file as shown in below C program to make use of these printf() and
scanf() library functions.

C printf() function:

o printf() function is used to print the “character, string, float, integer, octal and
hexadecimal values” onto the output screen. o We use printf() function with %d format
specifier to display the value of an integer variable.
o Similarly %c is used to display character, %f for float variable, %s for string variable, %lf
for double and %x for hexadecimal variable.
o To generate a newline,we use “\n” in C printf() statement.

Note:

o C language is case sensitive. For example, printf() and scanf() are different from Printf()
and Scanf(). All characters in printf() and scanf() functions must be in lower case.

Example program for C printf() function:

8
1 #include <stdio.h>
2
3 int main()
4 {
5 char ch = 'A';
6 char str[20] = "fresh2refresh.com";
7 float flt = 10.234;
8 int no = 150;
9
10 double dbl = 20.123456;
11 printf("Character is %c \n", ch);
12 printf("String is %s \n" , str);
13 printf("Float value is %f \n", flt);
14 printf("Integer value is %d\n" , no);
15
16 printf("Double value is %lf \n", dbl);
17 printf("Octal value is %o \n", no);
18 printf("Hexadecimal value is %x \n", no);
19
20 return 0;
21
22 }
Output:

Character is A String is
fresh2refresh.com Float
value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96

You can see the output with the same data which are placed within the double quotes of printf
statement in the program except

o %d got replaced by value of an integer variable (no), o %c got replaced by


value of a character variable (ch), o %f got replaced by value of a float
variable (flt), o %lf got replaced by value of a double variable (dbl), o %s got
replaced by value of a string variable (str), o %o got replaced by a octal value
corresponding to integer variable (no), o %x got replaced by a hexadecimal
value corresponding to integer variable o \n got replaced by a newline.

9
2. C scanf() function:

oscanf() function is used to read character, string, numeric data from keyboard o
Consider below example program where user enters a character. This value is assigned
to the variable “ch” and then displayed.
o Then, user enters a string and this value is assigned to the variable ”str” and then
displayed.
Example program for printf() and scanf() functions in C:

1 #include <stdio.h>
2
3 int main()
4 {
5 char ch;
6 char str[100];
7
8 printf("Enter any character \n");
9 scanf("%c", &ch);
10 printf("Entered character is %c \n", ch);
11
12 printf("Enter any string ( upto 100 character ) \n");
13 scanf("%s", &str);
14 printf("Entered string is %s \n", str);
15 }

Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai
o The format specifier %d is used in scanf() statement. So that, the value entered is
received as an integer and %s for string.
o Ampersand is used before variable name “ch” in scanf() statement as &ch.
o It is just like in a pointer which is used to point to the variable. For more information
about how pointer works

Further Reading:

http://www.tutorialspoint.com/cprogramming/ http://www.cprogramming.com

10
Summary:

• C is a case sensitive programming language. It means in C printf and Printf will have different
meanings.
• C has a free-form line structure. End of each C statement must be marked with a semicolon.
• Multiple statements can be one the same line.
• White Spaces (ie tab space and space bar ) are ignored.
• Statements can continue over multiple lines.

Expected Learning Outcome:


Students will acquire knowledge basic structure of C Language.

Exercises
A. Objective Type Questions:
1. C language is available for which of the following Operating Systems?

DOSWindowsUnixAll of these
2. Which of the following symbol is used to denote a pre-processor statement?

!#~;
B.Questions

1.Explain the Basic Structure of the C Program.


9.1 C– Tokens and keywords

C tokens, Identifiers and Keywords are the basics in a C program. All are explained in this page with
definition and simple example programs.

9.2 C tokens:

o C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.
o Each and every smallest individual units in a C program are known as C tokens.

o C tokens are of six types. They are,

1. Keywords (eg: int, while),


2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
11
6. Operators (eg: +, /,-,*)

C tokens example program:

1 int main()
2 {
3 int x, y, total;
4 x = 10, y = 20;
5 total = x + y;
6 Printf (“Total = %d \n”, total);
7 } where,

o main – identifier
o {,}, (,) – delimiter o int – keyword
o x, y, total – identifier o main, {, },
(, ), int, x, y, total – tokens

Do you know how to use C token in real time application programs? We have given simple real time
application programs where C token is used. You can refer the below C programs to know how to use C
token in real time program.
Real time application C programs for your reference:

1. C program example – Real time Calculator program 2. C


program example – Real time Bank Application program

9. 3. Identifiers in C language:

o Each program elements in a C program are given a name called identifiers.


o Names given to identify Variables, functions and arrays are examples for identifiers. eg.
x is a name given to integer variable in above program.

Rules for constructing identifier name in C:

1. First character should be an alphabet or underscore.


2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.

9.4 Keywords in C language:

12
o Keywords are pre-defined words in a C compiler. o Each keyword is meant to perform
a specific function in a C program. o Since keywords are referred names for compiler,
they can’t be used as variable name.

C language supports 32 keywords which are given below


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigne
d
continue for signed void
default goto sizeof volatile
do if static while
9.5 C – Constant

• C Constants are also like normal variables. But, only difference is, their values can not be
modified by the program once they are defined.
• Constants refer to fixed values. They are also called as literals  Constants may be belonging to
any of the data type.

• Syntax:

const data_type variable_name; (or) const data_type *variable_name;

Types of C constant:

1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
S.n Constant type data type Example
o
1 Integer constants int unsigned 53, 762, -478 etc

13
int long int 5000u, 1000U etc
long long int 483,647
2,147,483,680
float 10.456789
2 Real or Floating point constants
doule 600.123456789
3 Octal constant Int 013 /* starts with 0 */
4 Hexadecimal constant Int 0×90 /* starts with 0x */
5 character constants Char ‘A’ , ‘B’, ‘C’
6 string constants Char “ABCD” , “Hai”
Rules for constructing C constant:

1. Integer Constants in C:

o An integer constant must have at least one digit. o It must not have a decimal
point. o It can either be positive or negative. o No commas or blanks are
allowed within an integer constant.
o If no sign precedes an integer constant, it is assumed to be positive. o The
allowable range for integer constants is -32768 to 32767.
2. Real constants in C:

o A real constant must have at least one digit o It must have a decimal point o
It could be either positive or negative o If no sign precedes an integer
constant, it is assumed to be positive. o No commas or blanks are allowed
within a real constant.

3. Character and string constants in C:

o A character constant is a single alphabet, a single digit or a single special


symbol enclosed within single quotes.
o The maximum length of a character constant is 1 character. o String
constants are enclosed within double quotes.

4. Backslash Character Constants in C:

o There are some characters which have special meaning in C language. o They
should be preceded by backslash symbol to make use of special function of
them. o Given below is the list of special characters and their purpose.
Backslash_character Meaning
\b Backspace

14
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
How to use constants in a C program?

o We can define constants in a C program in the following ways.


1. By “const” keyword
2. By “#define” preprocessor directive
o Please note that when you try to change constant values after defining in C
program, it will through error.

1. Example program using const keyword in C:

1 #include <stdio.h>
2
3 void main()
4 {
5 const int height = 100; /*int constant*/
6 const float number = 3.14; /*Real constant*/
7 const char letter = 'A'; /*char constant*/
8 const char letter_sequence[10] = "ABC"; /*string constant*/
9 const char backslash_char = '\?'; /*special char cnst*/
10
11 printf("value of height : %d \n", height );
12 printf("value of number : %f \n", number );
13 printf("value of letter : %c \n", letter );
14 printf("value of letter_sequence : %s \n", letter_sequence);
15 printf("value of backslash_char : %c \n", backslash_char); 16 }

15
Output:

value of height : 100 value of


number : 3.140000 value of
letter : A value of
letter_sequence : ABC value of
backslash_char : ?

2. Example program using #define preprocessor directive in C:

C1 #include <stdio.h>
2
3 #define height 100
4 #define number 3.14
5 #define letter 'A'
6 #define letter_sequence "ABC"
7 #define backslash_char '\?'
8
9 void main()
10 {
11
12 printf("value of height : %d \n", height );
13 printf("value of number : %f \n", number );
14 printf("value of letter : %c \n", letter );
15 printf("value of letter_sequence : %s \n", letter_sequence);
16 printf("value of backslash_char : %c \n", backslash_char);
17
18 }

Output:

value of height : 100 value of


number : 3.140000 value of
letter : A value of
letter_sequence : ABC value of
backslash_char : ?

Further Reading:

http://www.tutorialspoint.com/cprogramming/ http://www.cprogramming.com

16
Summary:

In a passage of text, individual words and punctuation marks are called tokens or lexical units. Similarly,
the smallest individual unit in a c program is known as a token or a lexical unit. C tokens can be classified
as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

Expected Learning Outcome:


Students will acquire knowledge on C-tokens.

Exercises
A.Objective Type Questions:
1. Which of the following are tokens in C?

KeywordsVariablesConstantsAll of the above


2. Which of the following are tokens in C?

KeywordsVariablesConstantsAll of the above


B. Questions:
1. Explain about C-tokens.
2. List out keywords in C Language.
10 C – Variable

• C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
• The value of the C variable may get change in the program.
• C variable might be belonging to any of the data type like int, float, char etc.

10.1 Rules for naming C variable:

1. Variable name must begin with letter or underscore.


2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name

17
10.2 Declaring & initializing C variable:

• Variables should be declared in the C program before to use.


• Memory space is not allocated for a variable while declaration. It happens only on
variable definition.
• Variable initialization means assigning a value to the variable.
S.No Type Syntax Example
1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;
2 Variable data_type variable_name = int x = 50, y = 30; char flag = ‘x’,
initialization value; ch=’l’;
There are three types of variables in C program They are,

1. Local variable
2. Global variable
3. Environment variable

10.3 Example program for local variable in C:

• The scope of local variables will be within the function only.


• These variables are declared within the function and can’t be accessed outside the function.
• In the below example, m and n ivariables are having scope within the main function only. These
are not visible to test function.
• Like wise, a and b variables are having scope within the test function only. These are not visible
to main function.
1 #include<stdio.h>
2
3 void test();
4
5 int main()
6 {
7 int m = 22, n = 44;
8 // m, n are local variables of main function
9
10 /*m and n variables are having scope
11 within this main function only.
12 These are not visible to test funtion.*/
13 /* If you try to access a and b in this function,
14 you will get 'a' undeclared and 'b' undeclared
15 error */
16
17 printf("\nvalues : m = %d and n = %d", m, n);

18
18
19 test();
20
21 }
22
23 void test()
24 {
25 int a = 50, b = 80;
26 // a, b are local variables of test function
27
28 /*a and b variables are having scope
29 within this test function only.
30 These are not visible to main function.*/
31 /* If you try to access m and n in this function,
32 you will get 'm' undeclared and 'n' undeclared
33 error */
34
35 printf("\nvalues : a = %d and b = %d", a, b); 36 }

Output:

values : m = 22 and n = 44
values : a = 50 and b = 80
10.4. Example program for global variable in C:

o The scope of global variables will be throughout the program. These variables can be
accessed from anywhere in the program. o This variable is defined outside the main
function. So that, this variable is visible to main function and all other sub functions.

1 #include<stdio.h>
2
3 void test();
4
5 int m = 22, n = 44;
6 int a = 50, b = 80;
7
8 int main()
9 {
10
11 printf("All variables are accessed from main function");
12

19
13 printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
14
15 test();
16
17 }
18
19 void test()
20 {
21
22 printf("\n\nAll variables are accessed from" \
23 " test function");
24
25 printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
26 }

Output:

All variables are accessed from main function


values : m = 22 : n = 44 : a = 50 : b = 80

All variables are accessed from test function


values : m = 22 : n = 44 : a = 50 : b = 80
Difference between variable declaration &
definition in C:
S.no Variable declaration Variable definition
1 Declaration tells the compiler about data type and Definition allocates memory for the
size of the variable. variable.
2 Variable can be declared many times in a program. It can happen only one time for a variable
in a program.
3 The assignment of properties and identification to a Assignments of storage space to a
variable. variable.
Further Reading:

http://www.tutorialspoint.com/cprogramming/ http://www.cprogramming.com

Summary:

A variable is just a named area of storage that can hold a single value (numeric or character). The C
language demands that you declare the name of each variable that you are going to use and its type, or
class, before you actually try to do anything with it.

20
The Programming language C has two main variable types

• Local Variables
• Global Variables

Expected Learning Outcome:


Students will acquire knowledge of C-Variables.

Exercises
A.Objective Type Questions:
1. Which of the following are tokens in C?

KeywordsVariablesConstantsAll of the above


2. Which of the following are tokens in C?

KeywordsVariablesConstantsAll of the above


B. Questions:
1. Discuss the following
a. Local Variable
b. Global Variable
11 C – Data Types

• C data types are defined as the data storage format that a variable can store a data to perform a
specific operation.
• Data types are used to define a variable before to use in a program.
• Size of variable, constant and array are determined by data types.

11.1 C – data types:

There are four data types in C language. They are,


S.n Types Data Types
o
1 Basic data types int, char, float, double
2 Enumeration data type Enum
3 Derived data type pointer, array, structure, union
4 Void data type Void
11.2 Basic data types in C:

Integer data type:

21
• Integer data type allows a variable to store numeric values.
• “int” keyword is used to refer integer data type.
• The storage size of int data type is 2 or 4 or 8 byte.
• It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor, 2
byte (16 bit) of memory will be allocated for int data type.
• Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit
processor is allocated for int datatype.
• int (2 byte) can store values from -32,768 to +32,767
• int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
• If you want to use the integer value that crosses the above limit, you can go for “long int” and
“long long int” for which the limits are very high.

Note:

• We can’t store decimal values using int data type.


• If we use int data type to store decimal values, decimal values will be truncated and we will get
only whole number.
• In this case, float data type can be used to store decimal values in a variable.
11.3 Character data type:

• Character data type allows a variable to store only one character.


• Storage size of character data type is 1. We can store only one character using character data
type.
• “char” keyword is used to refer character data type.
• For example, ‘A’ can be stored using char datatype. You can’t store more than one character
using char data type.
• Please refer C – Strings topic to know how to store more than one characters in a variable.

11.4 Floating point data type:

Floating point data type consists of 2 types. They are,

1. float
2. double

1. float:

• Float data type allows a variable to store decimal values.


• Storage size of float data type is 4. This also varies depend upon the processor in the CPU as
“int” data type.

22
• We can use up-to 6 digits after decimal using float data type.
• For example, 10.456789 can be stored in a variable using float data type.

2. double:

• Double data type is also same as float data type which allows up-to 10 digits after decimal.
• The range for double datatype is from 1E–37 to 1E+37.

sizeof() function in C: sizeof() function is used to find the memory space

allocated for each C data types. 1 #include <stdio.h>

2 #include <limits.h>
3
4 int main()
5 {
6
7 int a;
8 char b;
9 float c;
10 double d;
11 printf("Storage size for int data type:%d \n",sizeof(a));
12 printf("Storage size for char data type:%d \n",sizeof(b)); 13 printf("Storage size for float data type:
%d \n",sizeof(c));
14 printf("Storage size for double data type:%d\
n",sizeof(d));
15 return 0; 16 }

Output:

Storage size for int data type:4


Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

11.5 Modifiers in C:

• The amount of memory space to be allocated for a variable is derived by modifiers.


• Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.

23
• For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.

• There are 5 modifiers available in C language. They are,

1. short
2. long
3. signed
4. unsigned
5. long long
 Below table gives the detail about the storage size of each C basic data type in 16 bit processor.
Please keep in mind that storage size and range for int and float datatype will vary depend on
the CPU processor (8,16, 32 and 64 bit)
S.No C Data types storage Range
Size
1 Char 1 –127 to 127
2 Int 2 –32,767 to 32,767
3 Float 4 1E–37 to 1E+37 with six digits of
precision
4 Double 8 1E–37 to 1E+37 with ten digits of
precision
5 long double 10 1E–37 to 1E+37 with ten digits of
precision
6 long int 4 –2,147,483,647 to 2,147,483,647
7 short int 2 –32,767 to 32,767
8 unsigned short int 2 0 to 65,535
9 signed short int 2 –32,767 to 32,767
10 long long int 8 –(2power(63) –1) to 2(power)63 –1
11 signed long int 4 –2,147,483,647 to 2,147,483,647
12 unsigned long int 4 0 to 4,294,967,295
13 unsigned long long 8 2(power)64 –1
int
11.6 Enumeration data type in C:

• Enumeration data type consists of named integer constants as a list.


• It start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the
list.

24
Enum syntax in C:

enum identifier [optional{ enumerator-list }];

• Enum example in C:

enum month { Jan, Feb, Mar }; or


/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
enum month { Jan = 20, Feb, Mar };
/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22 respectively by default */

• The above enum functionality can also be implemented by “#define” preprocessor directive as
given below. Above enum example is same as given below.
#define Jan 20;
#define Feb 21;
#define Mar 22;

11.7 C – enum example program:

1
#include <stdio.h>
2
3
int main()
4
{
5 enum MONTH { Jan = 0, Feb, Mar };
6
7 enum MONTH month = Mar;
8
9
if(month == 0)
10
printf("Value of Jan");
11
else if(month == 1)
12
printf("Month is Feb");
13
if(month == 2)
25
14
printf("Month is Mar");}
15

Output:

Month is March

11.8 Derived data type in C:

• Array, pointer, structure and union are called derived data type in C
language.

11.9 Void data type in C:

• Void is an empty data type that has no value.  This can be used in
functions and pointers.

Further Reading:

http://www.tutorialspoint.com/cprogramming/ http://www.cprogramming.com

Summary:

C has a concept of 'data types' which are used to define a variable before its use. The definition of a
variable will assign storage for the variable and define the type of data that will be held in the location.
The value of a variable can be changed any time. C has the following basic built-in datatypes.

• int
• float
• double
• char
• void

Expected Learning Outcome:


Students will acquire knowledge of C-datatypes.

Exercises
A.Objective Type Questions:
1. What will be the maximum size of a float variable?

26
1 byte2 bytes4 bytes8 bytes
2. What will be the maximum size of a double variable?

1 byte4 bytes8 bytes16 bytes

B. Questions:
1. Explain in detail about C-Datatypes.
2. Discuss the following
a. Derived Datatype
b. User defined Datatype
12 C – Operators and Expressions

• The symbols which are used to perform logical and mathematical operations in a C program are
called C operators.
• These C operators join individual constants and variables to form expressions.
• Operators, functions, constants and variables are combined together to form expressions.
• Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant and
A + B * 5 is an expression.

12.1 Types of C operators:

C language offers many types of operators. They are,

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

S.no Types of Operators Description


1 Arithmetic_operators These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
2 Assignment_operators These are used to assign the values for the variables in C programs.
3 Relational operators These operators are used to compare the value of two variables.
4 Logical operators These operators are used to perform logical operations on the
given two variables.

27
5 Bit wise operators These operators are used to perform bit operations on given two
variables.
6 Conditional (ternary) Conditional operators return one value if condition is true and
operators returns another value is condition is false.
7 Increment/decrement These operators are used to either increase or decrease the value
operators of the variable by one.
8 Special operators &, *, sizeof( ) and ternary operators.
12.2 C- Arithmetic Operators

Arithmetic Operators in C:

o C Arithmetic operators are used to perform mathematical calculations like addition,


subtraction, multiplication, division and modulus in C programs.
S.no Arithmetic Operators Operation Example
1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
Example program for C arithmetic operators:

o In this example program, two values “40″ and “20″ are used to perform arithmetic
operations such as addition, subtraction, multiplication, division, modulus and output is
displayed for each operation.

1 #include <stdio.h>
2 int main()
3 {
4 int a=40,b=20, add,sub,mul,div,mod;
5
6 add = a+b;
7 sub = a-b;
8 mul = a*b;
9 div = a/b;
10 mod = a%b;
11
12 printf("Addition of a, b is : %d\n", add);
13 printf("Subtraction of a, b is : %d\n", sub);
14 printf("Multiplication of a, b is : %d\n", mul);
15 printf("Division of a, b is : %d\n", div);

28
16 printf("Modulus of a, b is : %d\n", mod); 17 }

Output:

Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0

29
C–

12.3 Assignment Operators

Assignment operators in C:

o In C programs, values for the variables are assigned using assignment operators. o For
example, if the value “10″ is to be assigned for the variable “sum”, it can be assigned as
“sum = 10;”
o Other assignment operators in C language are given below.

Operators Example Explanation


Simple assignment operator = sum=10 10 is assigned to variable sum
Compound assignment operators += sum+=10 This_is_same_as_sum=sum+10…………
-= sum-=10 This is same as sum = sum-10
*= sum*=10 This is same as sum = sum*10
/+ sum/=10 This is same as sum = sum/10
%= sum%=10 This is same as sum = sum%10
&= sum&=10 This is same as sum = sum&10
^= sum^=10 This is same as sum = sum^10
Example program for C assignment operators:

o In this program, values from 0 – 9 are summed up and total “45″ is displayed as output.
o Assignment operators such as “=” and “+=” are used in this program to assign the values
and to sum up the values.

1 # include <stdio.h>
2 int main()
3 {
4 int Total=0,i;
5 for(i=0;i<10;i++)
6 {
7 Total+=i; // This is same as Total = Toatal+i
8 }
9 printf("Total = %d", Total);
10 }
Output:

30
C–

Total = 45
12.4 Relational Operators

Relational operators in C:

o Relational operators are used to find the relation between two variables. i.e. to compare
the values of two variables in a C program.
S.n Operators Example Description
o
1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
Example program for relational operators in C:

o In this program, relational operator (==) is used to compare 2 values whether they are
equal are not.
o If both values are equal, output is displayed as ” values are equal”. Else, output is
displayed as “values are not equal”.
o Note : double equal sign (==) should be used to compare 2 values. We should not single
equal sign (=).

1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 if (m == n)
6 {
7 printf("m and n are equal");
8 }
9 else
10 {
11 printf("m and n are not equal");
12 }
13 }

31
C–

Output:

m and n are not equal


12.5 Logical Operators

Logical operators in C:

o These operators are used to perform logical operations on the given expressions. o There
are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical
NOT (!).
S.n Operators Name Example Description
o
logical
1 && (x>5)&&(y<5) It returns true when both conditions are true
AND
2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true
It reverses the state of the operand “((x>5) && (y<5))” If
logical
3 ! !((x>5)&&(y<5)) “((x>5) && (y<5))” is true, logical NOT operator makes it
NOT
false
Example program for logical operators in C:

1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 int o=20,p=30;
6
7 if (m>n && m !=0)
8 {
9 printf("&& Operator : Both conditions are true\n");
10 }
11 if (o>p || p!=20)
12 {
13 printf("|| Operator : Only one condition is true\n");
14 }
15 if (!(m>n && m !=0))
16 {

32
C–

17 printf("! Operator : Both conditions are true\n");


18 }
19 else
20 {
21 printf("! Operator : Both conditions are true. " \
22 "But, status is inverted as false\n");
23 }
24 }

33
Output:

&& Operator : Both conditions are true


|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted
as false

o In this program, operators (&&, || and !) are used to perform logical operations on the
given expressions.
o && operator – “if clause” becomes true only when both conditions (m>n and m! =0) is
true. Else, it becomes false.
o || Operator – “if clause” becomes true when any one of the condition (o>p || p!=20) is
true. It becomes false when none of the condition is true.
o ! Operator – It is used to reverses the state of the operand. o If the conditions (m>n &&
m!=0) is true, true (1) is returned. This value is inverted by “!” operator.
o So, “! (m>n and m! =0)” returns false (0).

34
12.6 C – Bit wise Operators

Bit wise operators in C:

o These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
o Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).

Truth table for bit wise operation Bit wise operators


X y x|y x&y x^y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
<< Left Shift
>> Right Shift
 Consider x=40 and y=80. Binary form of these values are given below.

x = 00101000
y= 01010000

• All bit wise operations for x and y are given below.

x&y = 00000000 (binary ) = 0 (decimal)


x|y = 01111000 (binary) = 120 (decimal)
~x =1111111111111111111111111111111111111111111111111111111111010111
.. ..= -41 (decimal) x^y = 01111000
(binary) = 120 (decimal) x << 1 =
01010000 (binary) = 80 (decimal) x >> 1
= 00010100 (binary) = 20 (decimal)

Note:

• Bit wise NOT : Value of 40 in binary is


0000000000000000000000000000000000000000000000000000000000101000. So, all 0′s are
converted into 1′s in bit wise NOT operation.

35
•Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be
left shifted by one place. If we use it as “x << 2 “, then, it means that the bits will be left shifted
by 2 places.
Example program for bit wise operators in C:

o In this example program, bit wise operations are performed as shown above and output is
displayed in decimal format.

1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
5
6 AND_opr = (m&n);
7 OR_opr = (m|n);
8 NOT_opr = (~m);
9 XOR_opr = (m^n);
10
11 printf("AND_opr value = %d\n",AND_opr );
12 printf("OR_opr value = %d\n",OR_opr );
13 printf("NOT_opr value = %d\n",NOT_opr );
14 printf("XOR_opr value = %d\n",XOR_opr );
15 printf("left_shift value = %d\n", m << 1);
16 printf("right_shift value = %d\n", m >> 1); 17 }

Output:

AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41 XOR_opr value = 120 left_shift value = 80 right_shift value = 20

12.7 C – Conditional Operators

Conditional or ternary operators in C:

o Conditional operators return one value if condition is true and returns another value is
condition is false.
o This operator is also called as ternary operator.

Syntax : (Condition? true_value: false_value);

36
Example : (A > 100 ? 0 : 1);
.

In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal
o
to if else conditional statements.
Example program for conditional/ternary operators in C:

1 #include <stdio.h>
2 int main()
3 {
4 int x=1, y ;
5 y = ( x ==1 ? 2 : 0 ) ;
6 printf("x value is %d\n", x);
7 printf("y value is %d", y); 8 }

Output:

x value is 1
y value is 2

12.8 C – Increment/decrement Operators

• Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.

• Syntax:

Increment operator : ++var_name;


(or) var_name++; Decrement
operator :
– - var_name; (or) var_name – -;

 Example:

Increment operator :
++i;i++;
Decrement operator: –-i; i–-;

Example program for increment operators in C:

37
o In this program, value of “i” is incremented one by one from 1 up to 9 using “i++”
operator and output is displayed as “1 2 3 4 5 6 7 8 9”.
1 //Example for increment operators
2
3 #include <stdio.h>
4 int main()
5 {
6 int i=1;
7 while(i<10)
8 {
9 printf("%d ",i);
10 i++;
11 }
12 }

Output:

123456789

Example program for decrement operators in C:

o In this program, value of “I” is decremented one by one from 20 up to 11 using “i–”
operator and output is displayed as “20 19 18 17 16 15 14 13 12 11”.

1 //Example for decrement operators


2
3 #include <stdio.h>
4 int main()
5 {
6 int i=20;
7 while(i>10)
8 {
9 printf("%d ",i);
10 i--;
11 }
12 }

38
Output:

20 19 18 17 16 15 14 13 12 11
Difference between pre/post increment & decrement operators in C:

o Below table will explain the difference between pre/post increment and decrement
operators in C.
S.n Operator type Operator Description
o

1 Pre increment ++i Value of i is incremented before assigning it to variable i.

2 Post-increment i++ Value of i is incremented after assigning it to variable i.

3 Pre decrement – –i Value of i is decremented before assigning it to variable i.

4 Post_decrement i– – Value of i is decremented after assigning it to variable i.


Example program for pre – increment operators in C:

1 //Example for increment operators


2
3 #include <stdio.h>
4 int main()
5 {
6 int i=0;
7 while(++i < 5 )
8 {
9 printf("%d ",i);
10 }
11 return 0;
12 }
Output:
1234

o Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-increment


operator.
o Step 2 : This incremented value “1″ is compared with 5 in while expression. o Step 3 :
Then, this incremented value “1″ is assigned to the variable “i”.
o Above 3 steps are continued until while expression becomes false and output is
displayed as “1 2 3 4″.

39
Example program for post – increment operators in C:

1 #include <stdio.h>
2 int main()
3 {
4 int i=0;
5 while(i++ < 5 )
6 {
7 printf("%d ",i);
8 }
9 return 0;
10 }
Output:

12345
o Step 1 : In this program, value of i ”0″ is compared with 5 in while expression. o Step
2 : Then, value of “i” is incremented from 0 to 1 using post-increment operator. o Step
3 : Then, this incremented value “1″ is assigned to the variable “i”.
o Above 3 steps are continued until while expression becomes false and output is
displayed as “1 2 3 4 5″.

Example program for pre - decrement operators in C:

1 #include <stdio.h>
2 int main()
3 {
4 int i=10;
5 while(--i > 5 )
6 {
7 printf("%d ",i);
8 }
9 return 0;
10 }
Output:
9876

o Step 1 : In above program, value of “i” is decremented from 10 to 9 using predecrement


operator.

40
o Step 2 : This decremented value “9″ is compared with 5 in while expression. o Step 3 :
Then, this decremented value “9″ is assigned to the variable “i”.
o Above 3 steps are continued until while expression becomes false and output is
displayed as “9 8 7 6″.
Example program for post - decrement operators in C:

1 #include <stdio.h>
2 int main()
3 {
4 int i=10;
5 while(i-- > 5 )
6 {
7 printf("%d ",i);
8 }
9 return 0;
10 }

Output:

98765

o Step 1 : In this program, value of i ”10″ is compared with 5 in while expression. o Step
2 : Then, value of “i” is decremented from 10 to 9 using post-decrement operator. o
Step 3 : Then, this decremented value “9″ is assigned to the variable “i”.
o Above 3 steps are continued until while expression becomes false and output is
displayed as “9 8 7 6 5″. 12.9 C – Special Operators

Special Operators in C:

o Below are some of special operators that C language offers.


S.no Operators Description
This is used to get the address of the variable.
1 &
Example : &a will give address of a.
This is used as pointer to a variable.
2 *
Example : * a where, * is pointer to the variable a.
This gives the size of the variable.
3 Sizeof ()
Example : size of (char) will give us 1.
Example program for & and * operators in C:

41
o In this program, “&” symbol is used to get the address of the variable and “*” symbol is
used to get the value of the variable that the pointer is pointing to. Please refer C –
pointer topic to know more about pointers.
1 #include <stdio.h>
2
3 int main()
4 {
5 int *ptr, q;
6 q = 50;
7 /* address of q is assigned to ptr*/
8 ptr = &q;
9 /* display q's value using ptr variable */
10 printf("%d", *ptr);
11 return 0; 12 }

Output:

50

Example program for sizeof() operator in C:

o sizeof() operator is used to find the memory space allocated for each C data types.

1 #include <stdio.h>
2 #include <limits.h>
3
4 int main()
5 {
6
7 int a;
8 char b;
9 float c;
10 double d;
11 printf("Storage size for int data type:%d \n",sizeof(a));
12 printf("Storage size for char data type:%d \n",sizeof(b)); 13 printf("Storage size for float data type:
%d \n",sizeof(c));
14 printf("Storage size for double data type:%d\n",sizeof(d));
15 return 0;
16 }

42
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
Further Reading:

http://www.tutorialspoint.com/cprogramming/ http://www.cprogramming.com

Summary:

C language supports following type of operators.

• Arithmetic Operators
• Logical (or Relational) Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Expected Learning Outcome:


Students will acquire knowledge on C Operators and Expressions.

Exercises
A.Objective Type Questions:
1. Which of the following is an example of compounded assignment statement?

a = 5a += 5a = b = ca = b
2. The operator && is an example for ___ operator.

AssignmentIncrementLogicalRational
3. The operator & is used for

Bitwise ANDBitwise ORLogical ANDLogical OR


4. The operator / can be applied to

integer valuesfloat valuesdouble valuesAll of these


5. The equality operator is represented by

43
:=.EQ.===

B. Questions:
1. Explain in detail about C-Operators with examples.
2. Discuss the following
a. Conditional Operators
b. Increment and Decrement Operators

44
13 C – Decision Control statement

• In decision control statements (C if else and nested if), group of statements are executed when
condition is true. If condition is false, then else part statements are executed.
• There are 3 types of decision making control statements in C language. They are,

1. if statements
2. if else statements
3. nested if statements

13 .1 If”, “else” and “nested if” decision control statements in C:

o Syntax for each C decision control statements are given in below table with description.

Decision control
Syntax Description
statements
if (condition) In these type of statements, if condition is true, then
if
{ Statements; } respective block of code is executed.
if (condition)
{ Statement1; In these type of statements, group of statements are executed when
if…else Statement2;} else condition is true. If condition is false, then else part statements are
{ Statement3;executed.
Statement4; }
if
(condition1)
{ Statement1; }
else_if
If condition 1 is false, then condition 2 is checked and statements are
(condition
nested if executed if it is true. If condition 2 also gets failure, then else part is
2)
executed.
{ Stateme
nt2; } else
Statemen
t 3;
Example program for if statement in C:

In “if” control statement, respective block of code is executed when condition is true.

Output:

45
1 int main()
2 {
3 int m=40,n=40;
4 if (m == n)
5 {
6 printf("m and n are equal");
7 }
8 }

m and n are equal


Example program for if else statement in C:

In C if else control statement, group of statements are executed when condition is true. If condition is
false, then else part statements are executed.

1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 if (m == n) {
6 printf("m and n are equal");
7 }
8 else {
9 printf("m and n are not equal");
10 }
11
12 }
Output:
m and n are not equal

Example program for nested if statement in C:

o In “nested if” control statement, if condition 1 is false, then condition 2 is checked and
statements are executed if it is true.
o If condition 2 also gets failure, then else part is executed.

Output:

46
1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 if (m>n) {
6 printf("m is greater than n");
7 }
8 else if(m<n) {
9 printf("m is less than n");
10 }
11 else {
12 printf("m is equal to n");
13 }
14 }

m is greater than n
13.2 C – Loop control statements

Loop control statements in C are used to perform looping operations until the given condition is true.
Control comes out of the loop statements once condition becomes false.

Types of loop control statements in C:

There are 3 types of loop control statements in C language. They are,

1. for
2. while 3.do-while

o Syntax for each C loop control statements are given in below table with description.
S.no Loop Name Syntax Description
Where,
exp1 – variable initialization
for (exp1; exp2; expr3) ( Example: i=0, j=2, k=3 )
1 for exp2 – condition checking
{ statements; }
( Example: i>5, j<3, k=3 )
exp3 – increment/decrement

Output:

47
( Example: ++i, j–, ++k )
while (condition) where,
2 while
{ statements; } condition might be a>5, i<10
do { statements; } where,
3 do while
while (condition); condition might be a>5, i<10
Example program (for loop) in C:

In for loop control statement, loop is executed until condition becomes false.

#include <stdio.h>

int main()
{ int i;

for(i=0;i<10;i++)
{
printf("%d ",i); } }

0 123456789

Output:

48
Example program (while loop) in C:

In while loop control statement, loop is executed until condition becomes false.

1 #include <stdio.h>
2
3 int main()
4 {
5 int i=3;
6
7 while(i<10)
8 {
9 printf("%d\n",i);
10 i++;
11 }
12
13 }
Output:
3456789

Example program (do while loop) in C:

In do..while loop control statement, while loop is executed irrespective of the condition for first time.
Then 2nd time onwards, loop is executed until condition becomes false.

1 #include <stdio.h>
2
3 int main()
4 {
5 int i=1;
6
7 do
8 {
9 printf("Value of i is %d\n",i);
10 i++;
11 }while(i<=4 && i>=2);
12
13 }

49
Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Difference between while & do while loops in C:
S.no while do while
Loop is executed only when Loop is executed for first time irrespective of the condition. After
1
condition is true. executing while loop for first time, then condition is checked.
13.3 C – Case control statements

The statements which are used to execute only specific block of statements in a series of blocks are
called case control statements.

There are 4 types of case control statements in C language. They are,

1. switch
2. break
3. continue 4. goto

switch case statement in C:

o Switch case statements are used to execute only specific case statements based on the
switch expression.
o Below is the syntax for switch case statement.

switch (expression)
{
case label1: statements; break;
case label2:
statements; break;
default: statements;
break;
}
Example program for switch..case statement in C:

1 #include <stdio.h>
2

50
3 int main ()
4 {
5 int value = 3;
6
7 switch(value)
8 {
9 case 1:
10 printf("Value is 1 \n" );
11 break; 12 case 2:
13 printf("Value is 2 \n" );
14 break; 15 case 3:
16 printf("Value is 3 \n" );
17 break; 18 case 4:
19 printf("Value is 4 \n" );
20 break;
21 default :
22 printf("Value is other than 1,2,3,4 \n" );
23 }
24
25 return
0; 26 }

Output:

Value is 3

break statement in C:

oBreak statement is used to terminate the while loops, switch case loops and for loops
from the subsequent execution.
o Syntax: break;
Example program for break statement in C:

1 #include <stdio.h>
2
3 int main()
4 {

51
5 int i;
6
7 for(i=0;i<10;i++)
8 {
9 if(i==5)
10 {
11 printf("\nComing out of for loop when i = 5");
12 break;
13 }
14 printf("%d ",i);
15 }
16
17 }

Output:

01234
Coming out of for loop when i = 5

Continue statement in C:

o Continue statement is used to continue the next iteration of for loop, while loop and
dowhile loops. So, the remaining statements are skipped within the loop for that
particular iteration.
o Syntax : continue;

Example program for continue statement in C:

1 #include <stdio.h>
2
3 int main()
4 {
5 int i;
6
7 for(i=0;i<10;i++)
8 {
9 if(i==5 || i==6)
10 {
11 printf("\nSkipping %d from display using " \

52
12 "continue statement \n",i);
13 continue;
14 }
15 printf("%d ",i);
16 }
17
18 }

Output:

01234
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement
789

goto statement in C:

o goto statements is used to transfer the normal flow of a program to the specified label in
the program.
o Below is the syntax for goto statement in C.

{
…….
go to label;
…….
…….
LABEL:
statements;
}

Example program for goto statement in C:

1 #include <stdio.h>
2
3 int main()
4 {
5 int i;

53
6
7 for(i=0;i<10;i++)
8 {
9 if(i==5)
10 {
11 printf("\nWe are using goto statement when i = 5");
12 goto HAI;
13 }
14 printf("%d ",i);
15 }
16
17 HAI : printf("\nNow, we are inside label name \"hai\" \n");
18
19 }

Output:

01234
We are using goto statement when i = 5
Now, we are inside label name “hai”

Further Reading: List the chapters in Reference books/ web resources

http://www.tutorialspoint.com/cprogramming/ http://www.cprogramming.com

Summary:

C provides two styles of flow control:

• Branching
• Looping

Branching is deciding what actions to take and looping is deciding how many times to take a certain
action.

Expected Learning Outcome:

54
Students will acquire knowledge on Decision control statements and loop control statements.
Exercises

A.Objective Type Questions:

1.What is the output of the following program?

#include<stdio.h>
void main()
{ char c= 'a';
switch(c)
{ case 65 : printf("inside case A,");
break;
case 97 : printf("inside case a,");
break;
default: printf("inside default case");
break;
}}

A. inside default case


B. inside case a,
C. Compilation Error
D. inside case A,

2.What is the output of the following program?

#include<stdio.h>
voidmain()
{ inti=10;
switch(i)
{ case1: printf(" i=1");
break; case10: printf("
i=10"); case11: printf("
i=11"); break;
case12: printf(" i=12");
}
}
A. i=10 i=11 i=12
B. i=1 i=10 i=11 i=12
C. i=10 i=11
D. None of the Above

55
COURSE PLAN

Select a course (a theory subject): Programming for Problem Solving

Select a unit: Module III

Select a Topic: Arrays and Functions

1. Objectives
To study about the concepts of Arrays, types of arrays

2. Outcomes
Students will acquire knowledge on array declaration and (runtime & Compilation) initialization.

3. Pre-requisites
Know the concept of basic data types in C Language
4. Terminology used other than normal known scientific / engg terms and their
fundamental explanations / relations

Plan for the lecture delivery

1. How to plan for delivery – black board / ppt / animated ppt / (decide which is good
for this topic)
Power Point Presentation
2. How to explain the definition and terms with in it
Explain the memory allocation using Arrays, types of arrays and its initialization concepts

3. How to start the need for any derivation / procedure / experiment / case study
Not Applicable
4. Physical meaning of math equations / calculations
Not Applicable

56
5. Units and their physical meaning to make them understand practical reality and
comparison between different units
Understand the array concept easily apply the array concept in Array of structure in the
next unit.

6. What is the final conclusion?

Students will acquire knowledge on array declaration and (runtime & Compilation) initialization.

7. How to put it in a nut shell


One Dimension Array, Two Dimension Array, Multi Dimension Array, User define
function, Standard Library Function.
8. Important points for understanding / memorizing / make it long lasting

• Array is a Group of Similar Data Items. Each Items accessed using the Array
index number

• Three Types of Array one, Two, Multi Dimension Array


• Function is a group of statement to solve a specific task
• Two Types of function 1. User Define function 2. Standard Library Function.
• Function call the same function itself is called recursive function.

9. Questions and cross questions in that topic to make them think beyond the topic.

A 1. Array is a container of similar ……………………………


a) symbols b) data elements c) variables d) constants

B 1. Define an array
2. What are all the types of array available?
3. Give the syntax of array declaration.

C 1. Explain briefly about arrays.

D
1. Define a function?

57
2. Define formal parameter
3. Define Actual Parameter

1. Explain briefly about functions in C programming


2. Compare function call by reference with call by
value.

10. Final conclusions

Students will acquire knowledge on array declaration and (runtime & Compilation) initialization.
14.1 Introduction.
The C Programming language generally uses the variables which are nothing but a name given to
a storage area that our programs can manipulate. Each variable in C has a specific type, which
determines the size and layout of the variable's memory; the range of values that can be stored within
that memory and the limitations are it can’t store more than one value at a time. The limitation of
variables could be avoided by using the arrays.
Arrays.
C programming language provides a data structure called the array, which can store a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

First Element Last Element

A[0] A[1] A[2] ....

Fig 3.1 Arrays

58
14.2. Array Declaration.

To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows, Syntax
<type> <array Name> [ array Size ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than
zero and type can be any valid C data type. For example, to declare a 10-element array called balance of
type double, use this statement:

double balance[10];

59
14.3. Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } cannot be larger than the number of elements that we declare
for the array between square brackets [ ].
Following is the pictorial representation of the same array we discussed above:

Fig 3.2 Array with elements

14.4. Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example:

double salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary variable.
Following is an example which will use all the above mentioned three concepts viz. declaration,
assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */ int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
} return
0;
} 125

When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

14.5 Types of Arrays.


Arrays are classified with their allocation and usage, namely

• Two dimensional Array


• Multi- dimensional Array

14.5.1 Multi-dimensional Arrays

61
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:

type name[size1][size2]. . .[sizeN];

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:

int threedim[5][10][4];

14.5.2 Two-Dimensional Arrays


The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer
array of size x, y you would write something as follows:
type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional
array can be think as a table which will have x number of rows and y number of columns. A 2dimentional
array a, which contains three rows and four columns can be shown as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in ‘a’.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */

62
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};


Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example:
int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram. Let us check below program where we have used nested loop to handle a two dimensional
array:
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i]
[j] ); }
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0 a[0]
[1]: 0 a[1][0]: 1
a[1][1]: 2 a[2]
[0]: 2 a[2][1]: 4
a[3][0]: 3 a[3]
[1]: 6 a[4][0]: 4
a[4][1]: 8

63
As explained above, you can have arrays with any number of dimensions, although it is likely that most
of the arrays you create will be of one or two dimensions.
14.6.Passing Arrays as Function Arguments

If you want to pass a single-dimension array as an argument in a function, you would have to declare
function formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received. Similar
way you can pass multi-dimensional array as formal parameters.
Way-1

Formal parameters as a pointer as follows. You will study what is pointer in next chapter.
void myFunction(int *param)
{
.
.
.
}

Way-2

Formal parameters as a sized array as follows:


void myFunction(int param[10])
{
.
.
.
}

Way-3
Formal parameters as an unsized array as follows:
void myFunction(int param[])
{
.
.
.
}

64
Example
Now, consider the following function, which will take an array as an argument along with another
argument and based on the passed arguments, it will return average of the numbers passed through the
array as follows:

double getAverage(int arr[], int size)


{ int
i;
double avg;
double sum;
for (i = 0; i < size; ++i)
{ sum +=
arr[i];
} avg = sum /
size; return avg;
}

Now, let us call the above function as follows:


#include <stdio.h>
/* function declaration */ double
getAverage(int arr[], int size); int
main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument
*/ avg = getAverage( balance, 5 ) ; /* output
the returned value */ printf( "Average value is:
%f ", avg ); return 0;
}

When the above code is compiled together and executed, it produces the following result:
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C
performs no bounds checking for the formal parameters.
Return array from function

65
C programming language does not allow to return an entire array as an argument to a function.
However, you can return a pointer to an array by specifying the array's name without an index. You will
study pointer in next chapter so you can skip this chapter until you understand the concept of Pointers
in C.
If you want to return a single-dimension array from a function, you would have to declare a function
returning a pointer as in the following example:
int * myFunction()
{
}
Second point to remember is that C does not advocate to return the address of a local variable to
outside of the function so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an
array and call this function as follows:

#include <stdio.h>
/* function to generate and return random numbers */
int * getRandom( )
{
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i)
{
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
/* main function to call above defined function */
int main ()
{
/* a pointer to an int
*/ int *p; int i;
p = getRandom();
for ( i = 0; i < 10; i++ )
{
printf( "*(p + %d) : %d\n", i, *(p + i));
}

66
return 0;
}
15. Functions in C.

15.1. Introduction
Function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions. You can
divide up your code into separate functions. How you divide up your code among different functions is
up to you, but logically the division usually is so each function performs a specific task. A function
declaration tells the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function.

Functions

The C standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one memory location
to another location and many more functions.

A function is known with various names like a method or a sub-routine or a procedure, etc.

15.2. Defining a Function.


A function definition in C programming language consists of a function header and a function
body. General form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
body of the function
}

Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In
this case, the return_type is the keyword void.

67
Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.

Function Body: The function body contains a collection of statements that define what the
function does.
Example
Following is the source code for a function called max(). This function takes two parameters num1 and
num2 and returns the maximum between the two:
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration
*/ int result; if (num1 > num2)
result = num1; else result =
num2;
return result;
}

15.3. Function Declarations

A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.

A function declaration has the following parts:


return_type function_name( parameter list );

For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so following is
also valid declaration:
int max(int, int);

68
Function declaration is required when you define a function in one source file and you call that function
in another file. In such case you should declare the function at the top of the file calling the function.

15.4. Calling a Function


While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called function
performs defined task, and when its return statement is executed or when its function-ending closing
brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:

#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition
*/ int a = 100; int b = 200; int
ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration
*/ int result; if (num1 > num2)
result = num1; else result =
num2; return result;
While running final executable, it would produce the following result:}

Max value is : 200


69
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
15.5 Function call by value
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the parameter inside
the function have no effect on the argument.
By default, C programming language uses call by value method to pass arguments. In general, this means
that code within a function cannot alter the arguments used to call the function. Consider the function
swap() definition as follows.
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */ y =
temp; /* put x into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example:
#include <stdio.h>
/* function declaration
*/ void swap(int x, int y);
int main ()
{
/* local variable definition */ int a = 100;
int b = 200; printf("Before swap, value of
a : %d\n", a ); printf("Before swap, value
of b : %d\n", b ); /* calling a function to
swap the values */ swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0; 135
}
Let us put above code in a single C file, compile and execute it, it will produce the following result:
Before swap, value of a :100
Before swap, value of b :200

Which shows that there is no change in the values though they had been changed inside the function.
15.6 Function call by reference

The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the parameter affect the passed argument.

To pass the value by reference, argument pointers are passed to the functions just like any other value.
So accordingly you need to declare the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables pointed to by its arguments.
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y
*/ return;
}
71
Let us call the function swap() by passing values by reference as in the following example:

#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{
/* local variable definition */ int a = 100;
int b = 200; printf("Before swap, value of a
: %d\n", a ); printf("Before swap, value of
b : %d\n", b ); /* calling a function to
swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}

Let us put above code in a single C file, compile and execute it, it will produce the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Which shows that there is no change in the values though they had been changed inside the function.

Summary:

The function is a program that calls another program for execution.


Passing parameters to the functions could be understood using the program.
6.2. Recursive function

72
Recursion is the process of repeating items in a self-similar way. Same applies in programming
languages as well where if a programming allows you to call a function inside the same function that is
called recursive call of the function as follows.

void recursion()
{
recursion(); /* function calls itself */
} int main()
{
recursion(); }

The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go in
infinite loop.

Recursive function are very useful to solve many mathematical problems like to calculate factorial of a
number, generating Fibonacci series, etc.

Number Factorial
Following is an example, which calculates factorial for a given number using a recursive function:

#include <stdio.h>
int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
} int
main()

{ int i =
15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result:
Factorial of 15 is 2004310016

73
Fibonacci Series
Following is another example, which generates Fibonacci series for a given number using a
recursive function:
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{ int
i;
for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonaci(i));
} return
0;
}
When the above code is compiled and executed, it produces the following result:
0 1 1 2 3 5 8 13 21 34
COURSE PLAN

Select a course (a theory subject): Programming for Problem Solving

Select a unit: Module IV

Select a Topic: Structure & Union, Strings

1. Objectives
To study about how to create & use a Structures for heterogeneous data items

74
2. Outcomes
Students will acquire knowledge on structure and array of structure in C Language

3. Pre-requisites
Knowledge of Data types, Array and Function.
4. Terminology used other than normal known scientific / engg terms and their
fundamental explanations / relations
Not Applicable

Plan for the lecture delivery

1. How to plan for delivery – black board / ppt / animated ppt / (decide which is good
for this topic)
Power Point Presentation
2. How to explain the definition and terms with in it
Explain the concept of Array and compare with Structure variables.
3. How to start the need for any derivation / procedure / experiment / case study
Not Applicable
4. Physical meaning of math equations / calculations
Not Applicable
5. Units and their physical meaning to make them understand practical reality and
comparison between different units
Not Applicable
6. What is the final conclusion?
Students will acquire knowledge on structure and array of structure in C Language and Know the
various string Operations in C Language.
7. How to put it in a nut shell
8. Important points for understanding / memorizing / make it long lasting Structure is a
group of Dissimilar items.
String is a Group of Character
Various String functions are a) strlen() b) strcmp() c)strcat d)strlwr e)strupr() f) strrev()
75
9. Questions and cross questions in that topic to make them think beyond the topic.

A 1. Example of heterogeneous data type in C language?


a) Unsigned int b) structure c) array d) int
……………………………
2. Syntax of structure declaration ……………………………
3. Which operator to use …………………to access Structure individual Elements

B 1. What is structure?
2. What is different between structure & array?
3. Uses of structure
4. Write the program for Book information storing structure declaration

C 1. Write the program for 100 Books information insertion & displaying using structure
2. Write the program for student information details using structure

D 1. Union is a ______________item:

2. Different between union & structure is _______________mechanism

3. State True or False:


a) Union allocate more memory
4. Union can access only ___________ at a time
a) One member b)All members c) array of member

E 1. Different between Structure & Union


2. Define union
3. Explain Memory mechanism in Union

10. Final conclusions

To study about how to create & use a Structures for heterogeneous data items add to the
clarity of the program
Array(Unit III) handle only all ints, or all floats or all chars at a time. In fact when we handle real
world data, we don’t usually deal with little atoms of information by themselves—things like
integers, characters and such. Instead we deal with entities that are collections of things, each thing
having its own attributes, just as the entity we call a ‘book’ is a collection of things such as title,
author, call number, publisher, number of pages, date of publication, etc. As you can see all this data
76
is dissimilar, for example author is a string, whereas number of pages is an integer. For dealing with
such collections, C provides a data type called ‘structure’. A structure gathers together, different
atoms of information that comprise a given entity.

17. Structures

Introduction

Data type is the type of the data, that are going to access within the program. ‘C’ Supports different data
types, each data type may have predefined memory requirement and storage representation.

17.1 Why Use Structures

information and how arrays can hold a number of pieces of information of the same data type.
These two data types can handle a great variety of situations. But quite often we deal with entities that
are collection of dissimilar data types.

Example Suppose you want to store data about a book.

Table 4.1.1
INFORMATIONS DATA TYPE
NAME Character Array
(char [100])
PRICE float
BOOK NUMBER OF PAGE int
Then we can follow two approaches:  Construct individual arrays, one for storing names, another for
storing prices and still another for storing number of pages.

 Use a structure variable.

Table 4.1.2

First Approach Second Approach

This approach no doubt allows you to store A structure contains a number of data types
names, prices and number of pages. But as you grouped together. These data types may or may
must have realized, it is an unwieldy approach not be of the same type
that obscures the fact that you are dealing with
a group of characteristics related to a single

77
entity
main( ) main( )
{ {
char name[3] ; struct book
float price[3] ; {
int pages[3], i ; char name ;
printf ( "\nEnter names, prices and no. of pages float price ;
of 3 books\n" ) ; for ( i = 0 ; i <= 2 ; i++ ) int pages ;
scanf ( "%c %f %d", &name[i], &price[i], };
&pages[i] ); struct book b1, b2, b3 ;
printf ( "\nAnd this is what you entered\n" ) ; printf ( "\nEnter names, prices & no. of pages of 3
for ( i = 0 ; i <= 2 ; i++ ) books\n" ) ;
printf ( "%c %f %d\n", name[i], price[i], pages[i] scanf ( "%c %f %d", &b1.name, &b1.price,
); &b1.pages ) ;
} scanf ( "%c %f %d", &b2.name, &b2.price,
&b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price,
&b3.pages ) ;
printf ( "\nAnd this is what you entered" ) ; printf
( "\n%c %f %d", b1.name, b1.price, b1.pages
);
printf ( "\n%c %f %d", b2.name, b2.price, b2.pages
);
printf ( "\n%c %f %d", b3.name, b3.price, b3.pages
);
}
And here is the sample run...

Enter names, prices and no. of pages of 3 books

A 100.00 354

C 256.50 682

F 233.70 512

And this is what you entered

A 100.000000 354

C 256.500000 682

F 233.700000 512

78
Declaring a Structure

The general form of a structure declaration statement is given below:

struct <structure name>

structure element 1 ;

structure element 2 ;

structure element 3 ;

......

......
};

For example program Table 4.1.2 struct

book

char name ;

float price ;

int pages ;

};

This statement defines a new data type called struct book. Each variable of this data type
will consist of a character variable called name, a float variable called price and an integer variable called
pages
Need to sets aside space in memory in a structure by using creating

struct book b1, b2, b3

It makes available space to hold all the elements in the structure for Table 4.1.2
name is 1 byte, price is 4 bytes, pages is 2 bytes, So total 7 bytes to allocate for b1, similarly s2, s3 also.
Table 4.1.2 structure variable contains 7 bytes each. Various formats to declaring Structure variables

Table 5.1.3

79
struct book struct book Struct

{ { {

char name ; char name ; char name ;

float price ; float price ; float price ;

int pages ; int pages ; int pages ;

}; } b1, b2, b3 ; } b1, b2, b3 ;

struct book b1, b2, b3 ;

Table 4.1.3 are similar to same in declaring Structure variables

Initialize values Statically in Structure variable similar to an array


Example:
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;

Note the following points while declaring a structure type:

• The closing brace in the structure type declaration must be followed by a semicolon.

• It is important to understand that a structure type declaration does not tell the compiler to reserve
any space in memory. All a structure declaration does is, it defines the ‘form’ of the structure.

• Usually structure type declaration appears at the top of the source code file, before any variables or
functions are defined

Accessing Structure Elements

Access individual elements of use a dot (.) operator. So to refer to Table 4.1.2 of the structure defined in
our sample program we have to use, b1.pages
Similarly, to refer to price we would use,
b1.price
Note that before the dot there must always be a structure variable and after the dot there must always
be a structure element.

How Structure Elements are Stored

Whatever be the elements of a structure, they are always stored in contiguous memory locations. The
following program would illustrate this:
Table 4.1.4
80
/* Memory map of structure elements */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ; printf ( "\
nAddress of name = %u", &b1.name ) ; printf
( "\nAddress of price = %u", &b1.price ) ; printf (
"\nAddress of pages = %u", &b1.pages ) ;

Here is the output of the program...


Address of name = 65518

Address of price = 65519

Address of pages = 65523


Actually the structure elements are stored in memory

17.2 Array of Structures

In our sample program, to store data of 100 books we would be required to use 100
different structure variables from b1 to b100, which is definitely not very convenient. A better approach
would be to use an array of structures. Following program shows how to use an array of structures.

81
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b[100] ;
int i ;
for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "\nEnter name, price and pages " ) ;
scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
}
for ( i = 0 ; i <= 99 ; i++ )
printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;
}
linkfloat( )
{
float a = 0, *b ;
b = &a ; /* cause emulator to be linked */
a = *b ; /* suppress the warning - variable not used */
}
Now a few comments about the program:
(a) Notice how the array of structures is declared... struct book b[100] ;
This provides space in memory for 100 structures of the type struct book.
(b) The syntax we use to reference each element of the array b is similar to the syntax used for
arrays of ints and chars. For example, we refer to zeroth book’s price as b[0].price. Similarly, we refer first
book’s pages as b[1].pages.
(c) It should be appreciated what careful thought Dennis Ritchie has put into C language. He first
definedarray as a collection of similar elements; then realized that dissimilar data types that are often
found in real life cannot be handled using arrays, therefore created a new data type called structure. But
even using structures programming convenience could not be achieved, because a lot of variables (b1 to
b100 for storing data about hundred books) needed to be handled. Therefore he allowed us to create an
array of structures; an array of similar data types which themselves are a collection of dissimilar data
types. Hats off to the genius!

82
(d) In an array of structures all elements of the array are stored in adjacent memory locations.
Sinceeach element of this array is a structure, and since all structure elements are always stored in
adjacent locations you can very well visualise the arrangement of array of structures in memory. In our
example, b[0]’s name, price and pages in memory would be immediately followed by b[1]’s name, price
and pages, and so on.
(e) What is the function linkfloat( ) doing here? If you don’t define it you are bound to get the error
"Floating Point Formats Not Linked" with majority of C Compilers. What causes this error to occur?
When parsing our source file, if the compiler encounters a reference to the address of a float, it sets a
flag to have the linker link in the floating-point emulator. A floating point emulator is used to manipulate
floating point numbers in runtime library functions like
reference to the float is a bit obscure and the compiler does not detect the need for the
emulator. The most common is using scanf( ) to read a float in an array of structures as shown in our
program. How can we force the formats to be linked? That’s where the linkfloat( ) function comes in. It
forces linking of the floating-point emulator into an application. There is no need to call this function,
just define it anywhere in your program.

17.3 Uses of Structures

The immediate application that comes to the mind is Database Management. That is, to maintain data
about employees in an organization, books in a library, items in a store, financial accounting transactions
in a company etc. But mind you, use of structures stretches much beyond database management. They
can be used for a variety of purposes like:

Changing the size of the cursor


Clearing the contents of the screen
Placing the cursor at an appropriate position on screen
Drawing any graphics shape on the screen
Receiving a key from the keyboard
Checking the memory size of the computer
Finding out the list of equipment attached to the computer
Formatting a floppy
Hiding a file from the directory
83
Displaying the directory of a disk
Sending the output to printer
Interacting with the mouse
18 INTRODUCTION TO UNION

INTRODUCTION

To define a union, you must use the union statement in very similar was as you did while defining
structure. The union statement defines a new data type, with more than one member for your program.
Data type is the type of the data, that are going to access within the program. ‘C’ Supports different data
types, each data type may have predefined memory requirement and storage representation. Defining a
Union
Synatx Example

union [union tag]


{ union Data
member definition; { int i; float f;
member definition; char str[20];
... } d1;
member definition;
} [one or more union variables];

Example
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()

84
{
union student record1; union student record2;
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50; printf("Union record1
values example\n"); printf(" Name : %s \n",
record1.name); printf(" Subject : %s \n",
record1.subject); printf(" Percentage : %f \n\n",
record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani"); printf(" Name :
%s \n", record2.name); strcpy(record2.subject,
"Physics"); printf(" Subject : %s \n",
record2.subject); record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}

Output:
Union record1 values example
Name :
Subject :
Percentage : 86.500000
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000

18.1 WHY USE UNION

C Union is also like structure, i.e. collection of different data types which are grouped together. Each
element in a union is called member.
Union and structure in C are same in concepts, except allocating memory for their members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members

85
We can access only one member of union at a time. We can’t access all member values at the same time
in union. But, structure can access all member values at the same time. This is because, Union allocates
one common storage space for all its members. Where as Structure allocates storage space for all its
members separately.
Many union variables can be created in a program and memory will be allocated for each union variable
separately.

18.2 DIFFERENT BETWEEN STRUCTURE & UNION

S.no C Structure C Union


1 Structure allocates storage Union allocates one common storage space for all its
space for all its members members.
separately. Union finds that which of its member needs high storage space
over other members and allocates that much space
2 Structure occupies higher Union occupies lower memory space over structure.
memory space.
3 We can access all members of We can access only one member of union at a time.
structure at a time.
4 Structure example: Union example:
struct student union student
{ {
int mark; char int mark; char
name[6]; name[6];
double average; double average;
}; };
5 For above structure, memory For above union, only 8 bytes of memory will be allocated
allocation will be like below. since double data type will occupy maximum space of memory
int mark – 2B char name[6] – over other data types.
6B double average – 8B Total memory allocation = 8 Bytes
Total memory allocation =
2+6+8 = 16 Bytes

20 STRINGS

INTRODUCTION

The way a group of integers can be stored in an integer array, similarly a group of characters can be
stored in a character array. Character arrays are many a time also called strings.Character arrays or
strings are used by programming languages to manipulate text such as words and sentences.
86
20.1 What are Strings

A string constant is a one-dimensional array of characters terminated by a null ( ‘\0’ )


For example, char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
Each character in the array occupies one byte of memory and the last character is always ‘\0’.
ASCII value of ‘\0’ is 0, show the way a character array is stored in memory.
Note that the elements of the character array are stored in contiguous memory locations.
The terminating null (‘\0’) is important, because it is the only way the functions that work with a string
can know where the string ends
65525 \0
65524 r
65523 e
65522 l
65521 s
65519 e
65520 h
65518 a
C concedes the fact that you would use strings very often and hence provides a shortcut for
initializing strings. For example, the string used above can also be initialized as, char name[ ] =
"HAESLER" ;

Note that, in this declaration ‘\0’ is not necessary. C inserts the null character automatically.
/* Program to demonstrate printing of a string */ /* Program to demonstrate printing of a string */
main( ) main( )
{ {
char name[ ] = "Klinsman" ; char name[ ] = "Klinsman" ; char *ptr ; ptr =
int i = 0 ; while ( i <= 7 ) name ; /* store base address of string */
{ printf ( "%c", while ( *ptr != `\0' )
name[i] ) ; i++ ; }} { printf ( "%c", *ptr )
; ptr++ ;
}}

And here is the output...


Klinsman
As with the integer array, by mentioning the name of the array we get the base address (address of the
zeroth element) of the array. This base address is stored in the variable ptr using, ptr = name ;
Once the base address is obtained in ptr, *ptr would yield the value at this address, which gets printed
promptly through,
printf ( "%c", *ptr ) ;
Then, ptr is incremented to point to the next character in the string. This derives from two facts: array
elements are stored in contiguous memory locations and on incrementing a pointer it points to the

87
immediately next location of its type. This process is carried out till ptr doesn’t point to the last character
in the string, that is, ‘\0’.
In fact, the character array elements can be accessed exactly in the same way as the elements of an
integer array. Thus, all the following notations refer to the same element:
name[i]
*( name + i ) *(
i + name )
i[name]

The %s used in printf( ) is a format specification for printing out a string.


main( )
{
char name[25] ; printf
( "Enter your name " ) ; scanf
( "%s", name ) ; printf
( "Hello %s!", name ) ;
}

And here is a sample run of the program...


Enter your name Debashish Hello
Debashish!

Note that the declaration char name[25] sets aside 25 bytes under the array name[ ], whereas the
scanf( ) function fills in the characters typed at keyboard into this array until the enter key is hit. Once
enter is hit, scanf( ) places a ‘\0’ in the array. Naturally, we should pass the base address of the array to
the scanf( ) function.

While entering the string using scanf( ) we must be cautious about two things:
The length of the string should not exceed the dimension of the character array
This is because the C compiler doesn’t perform bounds checking on character arrays. Hence, if you
carelessly exceed the bounds there is always a danger of overwriting something important, and in that
event, you would have nobody to blame but yourselves. scanf( ) is not capable of receiving multi-word
strings.

Therefore names such as ‘Debashish Roy’ would be unacceptable. The way to get around this
limitation is by using the function gets( ). The usage of functions gets( ) and its counterpart puts( ) is
shown below.

88
main( )
{
char name[25] ; printf ( "Enter
your full name " ) ; gets
( name ) ; puts ( "Hello!" ) ; puts
( name ) ;
}

And here is the output... Enter


your name Debashish Roy
Hello!
Debashish Roy

On displaying a string, unlike printf( ), puts( ) places the cursor on the next line. Though gets( ) is capable
of receiving only one string at a time, the plus point with gets( ) is that it can receive a multi-word
string.

20.2 Pointers and Strings

Suppose we wish to store “Hello”. We may either store it in a string or we may ask the C compiler to
store it at some location in memory and assign the address of the string in a char pointer. This is shown
below:
char str[ ] = "Hello" ;
char *p = "Hello" ;
There is a subtle difference in usage of these two forms. For example, we cannot assign a string to
another, whereas, we can assign a char pointer to another char pointer. This is shown in the following
program.

main( )
{
char str1[ ] = "Hello" ; char
str2[10] ; char *s = "Good
Morning" ; char *q ;
str2 = str1 ; /* error */
q = s ; /* works
*/ }

Also, once a string has been defined it cannot be initialized to another set of characters. Unlike strings,
such an operation is perfectly valid with char pointers.
main( )
{

89
char str1[ ] = "Hello" ;
char *p = "Hello" ; str1
= "Bye" ; /* error */
p = "Bye" ; /* works */
}

20.3 Standard Library String Functions

With every C compiler a large set of useful string handling library functions are provided.
Function Use
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
Compares two strings without regard to case ("i" denotes that this function ignores
strcmpi case)
stricmp Compares two strings without regard to case (identical to strcmpi)
strnicmp Compares first n characters of two strings without regard to case
strdup Duplicates a string
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string
strset Sets all characters of string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses string
strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the following
program.

90
main( ) Description
{
char arr[ ] = "Bamboozled" ; int len1, len2 ; Note that in the first call to the function strlen( ),
len1 = strlen ( arr ) ; len2 = strlen ( "Humpty we are passing the base address of the string, and
Dumpty" ) ; printf ( "\nstring = %s length = the function in turn returns the length of the
%d", arr, len1 ) ; printf ( "\nstring = %s length = string. While calculating the length it doesn’t count
%d", "Humpty ‘\0’.
Dumpty", len2 ) ;
} Even in the second call, len2 = strlen ( "Humpty
Dumpty" ) ; what gets passed to strlen( ) is the
address of the string and not the string itself

The output would be...


string = Bamboozled length = 10
string = Humpty Dumpty length = 13

strcpy( )
This function copies the contents of one string into another. The base addresses of the source and target
strings should be supplied to this function.
main( ) Description
{ On supplying the base addresses, strcpy( ) goes on
char source[ ] = "Sayonara" ; char copying the characters in source string into the
target[20] ; strcpy ( target, source ) ; target string till it doesn't encounter the end of
printf ( "\nsource string = %s", source ) ; source string (‘\0’). It is our responsibility to see to
printf ( "\ntarget string = %s", target ) ; it that the target string’s dimension is big enough
} to hold the string being copied into it. Thus, a
string gets copied into another, piece-meal,
character by character

And here is the output...


source string = Sayonara
target string = Sayonara

strcat( )
This function concatenates the source string at the end of the target string. For example, “Bombay” and
“Nagpur” on concatenation would result into a string “BombayNagpur”.

91
main( ) Note that the target string has been made big
{ char source[ ] = "Folks!" ; char enough to hold the final string
target[30] = "Hello" ; strcat ( target,
source ) ; printf ( "\nsource string = %s",
source ) ; printf ( "\ntarget string = %s",
target ) ;
}

And here is the output...


source string = Folks!
target string = HelloFolks!
strcmp( )
This is a function which compares two strings to find out whether they are same or different. The two
strings are compared character by character until there is a mismatch or end of one of the strings is
reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value zero. If they’re
not, it returns the numeric difference between the ASCII values of the first non-matching pairs of
characters. Here is a program which puts strcmp( ) in action.
main( ) In the first call to strcmp( ), the two strings are identical—
{ char string1[ ] = "Jerry" “Jerry” and “Jerry”—and the value returned by strcmp( ) is
; char string2[ ] = "Ferry" zero. In the second call, the first character of “Jerry” doesn't
; match with the first character of “Ferry” and the result is 4,
int i, j, k ; which is the numeric difference between ASCII value of ‘J’
i = strcmp ( string1, "Jerry" ) ; j = and ASCII value of ‘F’. In the third call to strcmp( ) “Jerry”
strcmp ( string1, string2 ) ; k = doesn’t match with “Jerry boy”, because the null character at
the end of “Jerry” doesn’t match the blank in “Jerry boy”.
strcmp ( string1, "Jerry boy" ) ;
The value returned is -32, which is the value of null character
printf ( "\n%d %d %d", i, j, k ) ;
minus the ASCII value of space, i.e., ‘\0’ minus ‘ ’, which is
}
equal to -32. The exact value of mismatch will rarely concern
us. All we usually want to know is whether or not the first
string is alphabetically before the second string. If it is, a
negative value is returned; if it isn’t, a positive value is
returned. Any non-zero value means there is a mismatch

And here is the output...


0 4 -32
Summary:

• A string is nothing but an array of characters terminated by ‘\0’.


• Being an array, all the characters of a string are stored in contiguous memory locations.
• Though scanf( ) can be used to receive multi-word strings, gets( ) can do the same job in a
cleaner way. Both printf( ) and puts( ) can handle multi-word strings.
92
• Strings can be operated upon using several standard library functions like strlen( ), strcpy( ),
strcat( ) and strcmp( ) which can manipulate strings.
• More importantly we imitated some of these functions to learn how these standard library
functions are written.
• Though in principle a 2-D array can be used to handle several strings, in practice an array of
pointers to strings is preferred since it takes less space and is efficient in processing strings.
• malloc( ) function can be used to allocate space in memory on the fly during execution of the
program.

Questions:

A 1. State True or False


a) String is a an Array
2. "A" is a ___________ while ’A’ is a ____________.
3. A string is terminated by a ______ character, which is written as ______.
4. The array char name[10] can consist of a maximum of ______ characters.
5. The array elements are always stored in _________ memory locations.

B 1. Write a program that converts all lowercase characters in a given string to its
equivalent uppercase character
2. Write any 5 string library function
3. What is String? Explain

C 1. Write a program to sort a set of names stored in an array in alphabetical order.


2. Write a program any eight string library function in brief example.
COURSE PLAN

Select a course (a theory subject): Programming for Problem Solving

Select a unit: Module V

Select a Topic: Pointers & Files

1. Objectives
To study about File handing Pointer in C language

2. Outcomes
Students will acquire knowledge on Pointers and Files in C language

3. Pre-requisites
Basic C Programming
93
4. Terminology used other than normal known scientific / engg terms and their
fundamental explanations / relations
Not Applicable

Plan for the lecture delivery

1. How to plan for delivery – black board / ppt / animated ppt / (decide which is good
for this topic)
Power Point Presentation
2. How to explain the definition and terms with in it
Defining the Pointer variable , Defining the files and various file operations and modes.
3. How to start the need for any derivation / procedure / experiment / case study
Not Applicable
4. Physical meaning of math equations / calculations
Not Applicable
5. Units and their physical meaning to make them understand practical reality and
comparison between different units
Not Applicable
6. What is the final conclusion?
Understand the concept of Pointers and Various File Operations in C Language
7. How to put it in a nut shell
Pointer , File, EOF, BOF, Read Mode, Write Mode )
8. Important points for understanding / memorizing / make it long lasting
Pointer
• Pointers are variables which hold addresses of other variables.
• Pointers can be used to make a function return more than one value simultaneously.
• The array variable acts as a pointer to the zeroth element of the array. In a 1-D array, zeroth
element is a single value, whereas, in a 2-D array this element is a 1-D array.
• On incrementing a pointer it points to the next location of its type.
• Array elements are stored in contiguous memory locations and so they can be accessed
using pointers.
• Only limited arithmetic can be done on pointers
94
Files
1. File I/O can be performed on a character by character basis, a line by line basis, a record by
record basis or a chunk by chunk basis.
2. Different operations that can be performed on a file are creation of a new file, opening an
existing file, reading from a file, writing to a file, moving to a specific location in a file
(seeking and closing file.
3. File I/O is done using a buffer to improve the efficiency.
4. A file can be a text file or a binary file depending upon its contents.
5. Library function convert \n to \r\n or vice versa while writing/reading to/from a file.
6. Many library functions convert a number to a numeric string before writing it to a file,
thereby using more space on disk. This can be avoided using functions fread() and fwrite().
In low level file I/O we can do the buffer management ourselves.

9. Questions and cross questions in that topic to make them think beyond the topic.

A 1. Which of these are reasons for using pointers?


a. To manipulate parts of an array
b. To refer to keywords such as for and if
c. To return more than one value from a function
d. To refer to particular programs more conveniently

B 1. What is pointer?
2. Explains the pointer notation
3. Restriction using pointer arithmetic
4. write program for given elements to an Pointer array.(int i=5, j=6,k=7,z=20)

C 1. Find the smallest number in an array using pointers.


2. Explain pointer arithmetic With suitable example?

D 1. What is File
2. What are the various mode to open the file
3. Write a Program to read the content of a File.

E 1. How to handle error during I/O operations in file handling?


2. What are the type of files?

F 1. Develop a C program to read a data file and display its contents in a neat format?
2. Explain about the file read, write and append operations in C with suitable example?

95
10. Final conclusions
Understand the concept of Pointers and Various File Operations in C Language

96
19 Pointer

19.1 An Introduction to Pointers & Pointer Notation

• C Pointer is a variable that stores/points the address of another variable.


• C Pointer is used to allocate memory dynamically i.e. at run time.
• The variable might be any of the data type such as int, float, char, double, short etc.

Syntax : data_type *var_name;


Example : int *p; char *p;

• Where, * is used to denote that “p” is pointer variable and not a normal variable.

Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.(c) Store the value 3 at
this location.

We may represent i’s location in memory by the following memory map

Key points to remember about pointers in C:

• Normal variable stores the value whereas pointer variable stores the address of the variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• * symbol is used to get the value of the variable that the pointer is pointing to.
• If pointer is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available between these two
pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler).
97
main( )
{ int i = 3 ; printf ( "\nAddress of i =
%u", &i ) ; printf ( "\nValue of i =
%d", i ) ;
}

The output of the above program would be:


Address of i = 65524
Value of i = 3
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The
expression &i returns the address of the variable i, which in this case happens to be 65524. Since 65524
represents an address, there is no question of a sign being associated with it. Hence it is printed out
using %u, which is a format specifier for printing an unsigned integer. We have been using the ‘&’
operator all the time in the scanf( ) statement.
The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value
stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator.
main( )
{ int i =
3;
printf ( "\nAddress of i = %u",
&i ) ; printf ( "\nValue of i =
%d", i ) ; printf ( "\nValue of i
= %d", *( &i ) ) ; }
The output of the above program would
be:
Address of i = 65524
Value of i = 3
Value of i = 3
Note that printing the value of *( &i ) is same as printing the value of i.
The expression &i gives the address of the variable i. This address can be collected in a variable, by
saying, j = &i ;

98
main( )
{ int i =
3 ; int
*j ; j =
&i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}
The output of the above program would be:
Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
Value of i = 3
Value of i = 3
Work through the above program carefully, taking help of the memory locations of i and j shown earlier.
This program summarizes everything that we have discussed so far. If you don’t understand the
program’s output, or the meanings of &i, &j, *j and *( &i ), re-read the last few pages. Everything we say
about C pointers from here onwards will depend on your understanding these expressions thoroughly.
19.2 Pointer arithmetic.

99
main( )
{ int i = 3, *x ;
float j = 1.5, *y ;
char k = 'c', *z ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of j = %f", j ) ;
printf ( "\nValue of k = %c", k ) ;
x = &i ;
y = &j ;
z = &k ;
printf ( "\nOriginal address in x = %u", x ) ;
printf ( "\nOriginal address in y = %u", y ) ;
printf ( "\nOriginal address in z = %u", z ) ;
x++ ; y++ ; z++ ;
printf ( "\nNew address in x = %u", x ) ;
printf ( "\nNew address in y = %u", y ) ;
printf ( "\nNew address in z = %u", z ) ;
}

Here is the output of the program.


Value of i = 3
Value of j = 1.500000
Value of k = c
Original address in x = 65524
Original address in y = 65520
Original address in z = 65519
New address in x = 65526
New address in y = 65524
New address in z = 65520
i j k x y z
3 1.500000 ‘c’ 65524 65520 65519
65524 65520 65519
Observe the last three lines of the output. 65526 is original value in x plus 2, 65524 is original value
in y plus 4, and 65520 is original value in z plus 1.
100
This so happens because every time a pointer is incremented it points to the immediately next
location of its type.
That is why, when the integer pointer x is incremented, it points to an address two locations after the
current location, since an int is always 2 bytes long (under Windows/Linux since int is 4 bytes long, new
value of x would be 65528).
Similarly, y points to an address 4 locations after the current location and z points 1 location after the
current location.
This is a very important result and can be effectively used while passing the entire array to a function.
The way a pointer can be incremented, it can be decremented as well, to point to earlier locations. Thus,
the following operations can be performed on a pointer:

(a) For example,


Addition of a number to a pointer. Subtraction of a number from a pointer
int i = 4, *j, *k ; int i = 4, *j, *k ;
j = &i ; j = j + j = &i ;
1;j=j+9;k= j=j-2;
j+3; j=j-5;
k=j-6;

pointers... they would never work out.


(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant

19.3 Pointer to an Array

Now we will try to correlate the following two facts, which we have learnt above:
(a) Array elements are always stored in contiguous memory locations.
(b) A pointer when incremented always points to an immediately next location of its type.

101
main( ) main( )
{ int arr[ ] = { 10, 20, 36, 72, 45, { int num[ ] = { 24, 34, 12, 44, 56,
36 } ; int *j, *k ; j = &arr [ 4 ] ; 17 } ; int i ;
k = ( arr + 4 ) ; for ( i = 0 ; i <= 5 ; i++ )
if ( j == k ) { printf ( "\nelement no. %d ", i ) ;
printf ( "The two pointers point to the same printf ( "address = %u", &num[i] ) ;
location" ) ; else }
printf ( "The two pointers do not point to }
the same location" ) ;
}

The output of this program would look like this:


element no. 0 address = 65512
element no. 1 address = 65514
element no. 2 address = 65516
element no. 3 address = 65518
element no. 4 address = 65520
element no. 5 address = 65522

19.4 Array of Pointer


The way there can be an array of ints or an array of floats, similarly there can be an array of pointers.
Since a pointer variable always contains an address, an array of pointers would be nothing but a
collection of addresses. The addresses present in the array of pointers can be addresses of isolated
variables or addresses of array elements or any other addresses.

102
main( )
{
int *arr[4] ; /* array of integer pointers */
int i = 31, j = 5, k = 19, l = 71, m ; arr[0] =
&i ; arr[1] = &j ; arr[2] = &k ; arr[3] = &l ;
for ( m = 0 ; m <= 3 ; m++ )

printf ( "%d ", * ( arr[m] ) ) ;

23 FILES

23.1 What is a File?

Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of
some kind. The collection of bytes may be interpreted, for example, as characters, words, lines,
paragraphs and pages from a textual document; fields and records belonging to a database; or pixels

103
from a graphical image. The meaning attached to a particular file is determined entirely by the data
structures and operations used by a program to process the file. It is conceivable (and it sometimes
happens) that a graphics file will be read and displayed by a program designed to process textual data.
The result is that no meaningful output occurs (probably) and this is to be expected. A file is simply a
machine decipherable storage media where programs and data are stored for machine usage.

Essentially there are two kinds of files that programmers deal with text files and binary files. These two
classes of files will be discussed in the following sections.

ASCII Text files

A text file can be a stream of characters that a computer can process sequentially. It is not only
processed sequentially but only in forward direction. For this reason a text file is usually opened for only
one kind of operation (reading, writing, or appending) at any given time.

Similarly, since text files only process characters, they can only read or write data one character at a
time. (In C Programming Language, Functions are provided that deal with lines of text, but these still
essentially process data one character at a time.) A text stream in C is a special kind of file. Depending on
the requirements of the operating system, newline characters may be converted to or from
carriagereturn/linefeed combinations depending on whether data is being written to, or read from, the
file. Other character conversions may also occur to satisfy the storage requirements of the operating
system. These translations occur transparently and they occur because the programmer has signalled
the intention to process a text file.
Binary files
A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and
a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two
essential differences.

1. No special processing of the data occurs and each byte of data is transferred to or from the disk
unprocessed.
2. C Programming Language places no constructs on the file, and it may be read from, or written to, in
any manner chosen by the programmer.

104
Binary files can be either processed sequentially or, depending on the needs of the application, they can
be processed using random access techniques. In C Programming Language, processing a file using
random access techniques involves moving the current file position to an appropriate place in the file
before reading or writing data. This indicates a second characteristic of binary files. They a generally
processed using read and write operations simultaneously.

For example, a database file will be created and processed as a binary file. A record update operation will
involve locating the appropriate record, reading the record into memory, modifying it in some way, and
finally writing the record back to disk at its appropriate location in the file. These kinds of operations are
common to many binary files, but are rarely found in applications that process text files.

Why files are needed?

When the program is terminated, the entire data is lost in C programming. If you want to keep large
volume of data, it is time consuming to enter the entire data. But, if file is created, these information can
be accessed using few commands. There are large numbers of functions to handle file I/O in C language.
23.2 File operations

There are different operations that can be carried out on a file. These are:

a) Creation of new file


b) Opening an existing file
c) Reading from a file
d) Writing to a file
e) Moving to a specific location in a file (seeking)
f) Close a file.

23.3 File opening modes

When you open a file, you must specify how it is to be opened. This means whether to create it from
new, overwrite it and whether it's text or binary, read or write and if you want to append to it. This is
done using one or more file mode specifiers which are single letters "r", "b", "w", "a" and + (in
combination with the other letters). "r" - Opens the file for reading. This fails if the file does not exist or
cannot be found. "w" - Opens the file as an empty file for writing. If the file exists, its contents are

105
destroyed. "a" - Opens the file for writing at the end of the file (appending) without removing the EOF
marker before writing new data to the file; this creates the file first if it doesn't exist. Adding + to the file
mode creates three new modes:

"r+" Opens the file for both reading and writing. (The file must exist.) "w+" Opens the file as an empty
file for both reading and writing. If the file exists, its contents are destroyed.
"a+" Opens the file for reading and appending; the appending operation includes the removal of the EOF
marker before new data is written to the file and the EOF marker is restored after writing is complete;
creates the file first if it doesn't exist.

Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file


r Open for reading. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If
w Open for writing.
the file does not exist, it will be created.
Open for append. i.e, Data is
a If the file does not exists, it will be created.
added to end of file.
Open for both reading and
r+ If the file does not exist, fopen() returns NULL.
writing.
Open for both reading and If the file exists, its contents are overwritten. If
w+
writing. the file does not exist, it will be created.
Open for both reading and
a+ If the file does not exists, it will be created.
appending.
File operations

Opening a File

Before we can read(or write) information from (to) a file on a disk we must open the file. To
open the file we have called the function fopen(). It would open a file a file “PRC1.C” in ‘read
mode, which tells the C compiler that we would be reading the contents of the file. Not that “r”
is a string not a character; hence the double quotes and not single quotes. In fact fopen()
performs three important tasks when you open the file in “r’ mode:

a) Firstly it searches on the disk the file to be opened.


b) Then it loads the file from the disk into a place in memory called buffer.
c) It sets up a character pointer that points to the first character of the buffer.

106
Why do we need a buffer at all? Imagine how inefficient it would be to actually access the disk
every time we want to read a character from it. Every time we read some think from disk, it
takes some time for the disk drive to position the read/write head correctly. On a floppy disk
system, the drive motor has to actually start rotating the disk from a standstill position every
time the disk is accessed. If this were to be done for every character we read from the disk, it
would take a long time to complete the reading operation. This is where a buffer comes in. it
would be more sensible to read the contents of the file into the buffer while opening. This is
where a buffer comes in. it would be more sensible to read the contents of the file into the
buffer while opening the file and then read the file character by character from the buffer rather
than from the disk. This is shown in the below figure.

PR1.C

Memory DISK

40

fp

40

some argument also applies to writing information in a file. Instead of writing characters in the file on
the disk one character at time it would be more efficient to write charters in a buffer and then finally
transfer the content from the buffer to the disk.

To be able to successfully read from a file information like mode of opening, size of file, place in the file
from where the next read operation would be performed, etc. has to be maintained. Since all this
information is inter-related, all of it is gathered together by fopen() in a structure called FILE. fopen()

107
return the address of this structure, which we have collected in the stracture pointer called fp. We have
declared fp as

FILE * fp;

The FILE structure has been defined in the header file “stdio.h” (standing for standard input/ouput
header file). therefore, it is necessary to #include this file.

108
2
3.4 Reading file content.

C program to read a file: This program reads a file entered by the user and displays its contents
on the screen, fopen function is used to open a file it returns a pointer to structure FILE. FILE is a
predefined structure in stdio.h . If the file is successfully opened then fopen returns a pointer to file and
if it is unable to open a file then it returns NULL. fgetc function returns a character which is read from
the file and fclose function closes the file. Opening a file means we bring file from disk to ram to perform
operations on it. The file must be present in the directory in which the executable file of this code sis
present.
/ * C programming code to open a file and to print it contents on screen. * /

#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp; printf("Enter the name of file you wish to
see\n");
gets(file_name); fp =
fopen(file_name,"r"); /* read mode */
if( fp == NULL )
{ printf("Error while opening the file.\n");
exit(0);
} printf("The contents of %s file are :\n",
file_name); while( ( ch = fgetc(fp) ) != EOF )
printf("%c",ch);
fclose(fp);
return 0;
}

3.5 Error handling While opening a File

There is a possibility that when we try to open a file using the function fopen(), the file may not
be opened. While opening the file in “r” mode, this may happen because the file being opened may not
be present on the disk at all. And you obviously cannot read a file that doesn’t exist. Similarly, while
opening the file for writing, fopen() may fail due to a number of reasons, like, disk space may be
insufficient to create a new file, of the disk may be write protected or the disk is damaged and so on.

109
2
/* C program to handle Error while opening a file */

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
Fp = fopen (“PRGRAM1.C”, “r”);
if (fp == NULL)
{ puts(“cannot open file”);
Exit(1);
} return
0;
}
23.6 Closing the file

To close a file, use the fclose( ) function. The prototype of this function is:

int fclose( FILE *fp );

The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function
actually, flushes any data still pending in the buffer to the file, closes the file, and releases any memory
used for the file. The EOF is a constant defined in the header file stdio.h.

There are various functions provide by C standard library to read and write a file character by character
or in the form of a fixed length string.
3.7 Writing to a File

To write a file, use the the fputs() function.

The fputc() function is similar to the putch() function, in the senses that both output characters.
However, putch() function always writes to the VDU, whereas, fputc() write to the file. Which file? The
file signified by ft. The writing process continues till all characters from the source file have been written
to the target file, following which the while loop terminates.

110
2
/* C programming code to writes strings to a file using the function fputs() */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char s[80],.
fp=fopen(“Cprogram.txt”, “w”);
if(fp==NULL)
{
printf("Cannot open file\n");
exit(1);
} printf("\nenter a few lines of
text:”);

while(strlen(gets(s)>0)
{ fputs(s, fp);
fputs(“\n”, fp);
}
fclose(fp);
return 0;
}
23.8 A File-Copy Program

We have already used the function fgetc() which reads characters from a file. Its counterpart is a
function called fputc() which writes characters to a file. As a practical use of these character I/O
functions, we can copy the contents of one file into another, as demonstrated in the following program.
This program takes the contents of a file and copies them into another file, character by character.

111
/* File Copy Program */
#include<stdio.h>
#include<stdlib.h>

int main()
{
FILE *fs, *ft; char ch; fs
= fopen(“prg1.c”,”r”) if(
fs == NULL)
{ puts(“Cannot open Source file”);
exit(1)
}
ft = fopen(“prg2.c”,”w”);
if ( ft ==NULL)
{ puts(“Cannot open target file”);
fclose(fs); exit(2);
}
while(1)
{
ch = fgetc(fs);
if(ch==EOF)
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft)
return 0;}

Writing to a File

The fputc() function is similar to the putch() function, in the senses that both output characters.
However, putch() function always writes to the VDU (Visual Display Unit). Whereas, fputc() writes a to
the file. Which file? The file signified by ft. The writing process continues till all characters from the
source file have been written to the target file, following which the while loop terminates. In the above

112
file copy program is capable of copying only text files. To copy file with extension .EXE or JPG, we need to
open the file in binary mode.

113

You might also like