You are on page 1of 310

Programming in C

Objectives

In this session, you will learn to:


Identify the benefits and features of C language
Use the data types available in C language
Identify the structure of C functions
Use input-output functions
Use constructs

Ver. 1.0

Slide 1 of 53

Programming in C
Identifying the Benefits and Features of C Language

Ken Thompson developed a new language called B.


B language was interpreter-based, hence it was slow.
Dennis Ritchie modified B language and made it a
compiler-based language.
The modified compiler-based B language is named as C.

Ver. 1.0

Slide 2 of 53

Programming in C
C as a Second and Third Generation Language

C language:
Possesses powerful low-level features of second generation
languages.
Provides loops and constructs available in third generation
languages.
Is very powerful and flexible.

Ver. 1.0

Slide 3 of 53

Programming in C
Block Structured Language - An Advantage for Modular Programming

C language:
Offers all essentials of structured programming.
Has functions that work along with other user-developed
functions and can be used as building blocks for advanced
functions.
Offers only a handful of functions, which form the core of the
language.
Has rest of the functions available in libraries. These functions
are developed using the core functions.

Ver. 1.0

Slide 4 of 53

Programming in C
Features of the C Language

The features that make C a widely-used language are:


Pointers: Allows reference to a memory location by a name.
Memory Allocation: Allows static as well as dynamic memory
allocation.
Recursion: Is a process in which a functions calls itself.
Bit Manipulation: Allows manipulation of data in its lowest form
of storage.

Ver. 1.0

Slide 5 of 53

Programming in C
Using the Data Types Available in C language

The types of data structures provided by C can be classified


under the following categories:
Fundamental data types
Derived data types

Ver. 1.0

Slide 6 of 53

Programming in C
Fundamental Data Types

Fundamental Data Types:


Are the data types at the lowest level.
Are used for actual data representation in the memory.
Are the base for other data types.
Have machine dependent storage requirement.
Are of the following three types:
char
int
float

Ver. 1.0

Slide 7 of 53

Programming in C
Fundamental Data Types (Contd.)

The storage requirement for fundamental data types can be


represented with the help of the following table.

Ver. 1.0

Data

Number of bytes on a
32-byte machine

Minimum

Maximum

char

-128

127

int

-2^31

(2^31) - 1

float

6 digits of precision

6 digits of precision

Slide 8 of 53

Programming in C
Derived Data Types

Derived Data Types:


Are represented in memory as fundamental data type.

Some derived data types are:


short int
long int
double float

Ver. 1.0

Slide 9 of 53

Programming in C
Derived Data Types (Contd.)

The storage requirement for derived data types can be


represented with the help of the following table.

Ver. 1.0

Data

Number of bytes
on a 32-byte
machine

Minimum

Maximum

short int

-2^15

(2^15) - 1

long int

-2^31

(2^31) - 1

double float

12 digits of precision

6 digits of
precision

Slide 10 of 53

Programming in C
Defining Data

The syntax for defining data is:


[data type] [variable name],...;

Declaration is done in the beginning of a function.


Definition for various data types is shown in the following
table.

Ver. 1.0

Data definition

Data type

Memory defined

Size (bytes)

Value assigned

char a, c;

char

a
c

1
1

char a = 'Z';

char

int count;

int

count

int a, count =10;

int

a
count

4
4

10

float fnum;

float

fnum

float fnum1,
fnum2 = 93.63;

float

fnum1
fnum2

4
4

93.63

Slide 11 of 53

Programming in C
Practice: 1.1

Write the appropriate definitions for defining the following


variables:
1. num to store integers.
2. chr to store a character and assign the character Z to it.
3. num to store a number and assign the value 8.93 to it.
4. i, j to store integers and assign the value 0 to j.

Ver. 1.0

Slide 12 of 53

Programming in C
Practice: 1.1 (Contd.)

Solution:
1. int num;
2. char chr=Z;
3. float num = 8.93;
4. int i, j=0;

Ver. 1.0

Slide 13 of 53

Programming in C
Defining Data (Contd.)

Defining Strings:
Syntax:
char (variable) [(number of bytes)];
Here number of bytes is one more than the number of
characters to store.
To define a memory location of 10 bytes or to store 9 valid
characters, the string will be defined as follows:
char string [10];

Ver. 1.0

Slide 14 of 53

Programming in C
Practice: 1.2

Write the appropriate definitions for defining the following


strings:
1. addrs to store 30 characters.
2. head to store 14 characters.

Ver. 1.0

Slide 15 of 53

Programming in C
Practice: 1.2 (Contd.)

Solution:
1. char addrs[31];
2. char head[15];

Ver. 1.0

Slide 16 of 53

Programming in C
Identifying the Structure of C Functions

In C language, the functions can be categorized in the


following categories:
Single-level functions
Multiple-level functions

Ver. 1.0

Slide 17 of 53

Programming in C
Single Level Functions

Single Level Functions:


Consider the following single-level function:
main()
{
/*print a message*/
printf("Welcome to C");
}

In the preceding function:


main(): Is the first function to be executed.
(): Are used for passing parameters to a function.
{}: Are used to mark the beginning and end of a function. These
are mandatory in all functions.
/* */: Is used for documenting various parts of a function.

Ver. 1.0

Slide 18 of 53

Programming in C
Single Level Functions (Contd.)

Semicolon (;): Is used for marking the end of an executable


line.
printf(): Is a C function for printing (displaying) constant or
variable data.

Ver. 1.0

Slide 19 of 53

Programming in C
Practice: 1.3

Identify any erroneous or missing component(s) in the


following functions:
1. man()
{
printf("This function seems to be okay")
}
2. man()
{
/*print a line*/
printf("This function is perfect;
}

Ver. 1.0

Slide 20 of 53

Programming in C
Practice: 1.3 (Contd.)

3. main()
}
printf("This has got to be right");
{
4. main()
{
This is a perfect comment line
printf("Is it okay?");
}

Ver. 1.0

Slide 21 of 53

Programming in C
Practice: 1.3 (Contd.)

Solution:
1. man instead of main() and semi-colon missing at the end of
the printf() function.
2. mam instead of main() and ) missing at the end of the
printf() function.
3. } instead of { for marking the beginning of the function and
{ instead of } for marking the end of the function.
4. Comment line should be enclose between /* and */.

Ver. 1.0

Slide 22 of 53

Programming in C
Multiple Level Functions

The following example shows functions at multiple


levels - one being called by another:
main ()
{
/* print a message */
printf ("Welcome to C.");
disp_msg ();
printf ("for good learning");
}
disp_msg ()
{
/* print another message */
printf ("All the best");
}
Ver. 1.0

Slide 23 of 53

Programming in C
Multiple Level Functions (Contd.)

The output of the preceding program is:


Welcome to C. All the best for good learning.

In the preceding program:


main(): Is the first function to be executed.
disp_msg(): Is a programmer-defined function that can be
independently called by any other function.
(): Are used for passing values to functions, depending on
whether the receiving function is expecting any parameter.
Semicolon (;): Is used to terminate executable lines.

Ver. 1.0

Slide 24 of 53

Programming in C
Practice: 1.4

Identify any erroneous or missing component(s) in the


following functions:
a. print_msg()
{ main();
printf(bye);
}
main()
{ printf(This is the main function);}
b. main()
{ /*call another function*/
dis_error();
}
disp_err();
{ printf(Error in function);}
Ver. 1.0

Slide 25 of 53

Programming in C
Practice: 1.4 (Contd.)

Solution:
a. main() is always the first function to be executed. Further
execution of the program depends on functions invoked from
main(). Here, after executing printf(), the program
terminates as no other function is invoked. The function
print_msg is not invoked, hence it is not executed.
b. The two functions, dis_error() and disp_error, are not
the same because the function names are different.

Ver. 1.0

Slide 26 of 53

Programming in C
Using the Input-Output Functions

The C environment and the input and output operations are


shown in the following figure.

Standard Input Device (stdin)

Standard Output Device (stdout)

C Environment

Standard Error Device (stderr)

Ver. 1.0

Slide 27 of 53

Programming in C
Using the Input-Output Functions (Contd.)

These are assumed to be always linked to the C


environment:
stdin - refers to keyboard
stdin - refers to keyboard
stdout - refers to VDU
stderr - refers to VDU

Input and output takes place as a stream of characters.


Each device is linked to a buffer through which the flow of
characters takes place.
After an input operation from the standard input device, care
must be taken to clear input buffer.

Ver. 1.0

Slide 28 of 53

Programming in C
Character-Based Input-Output Functions

Character-Based Input-Output Functions are:


getc()
putc()
getchar()
putchar()

The following example uses the getc() and putc()


functions:
# include < stdio.h>
/* function to accept and display a character*/
main ()
{char alph;
alph = getc (stdin); /* accept a character */
fflush (stdin); /* clear the stdin buffer*/
putc (alph, stdout); /* display a character*/
}
Ver. 1.0

Slide 29 of 53

Programming in C
Character-Based Input-Output Functions (Contd.)

The following example uses the getchar() and


putchar() functions:
# include < stdio.h >
/* function to input and display a character using the
function getchar() */
main () {
char c;
c = getchar ();
fflush (stdin); /* clear the buffer */
putchar (c);
}

Ver. 1.0

Slide 30 of 53

Programming in C
Practice: 1.5

1.

Ver. 1.0

Write a function to input a character and display the


character input twice.

Slide 31 of 53

Programming in C
Practice: 1.5 (Contd.)

Solution:

Ver. 1.0

Slide 32 of 53

Programming in C
Practice: 1.6

1.

Ver. 1.0

Write a function to accept and store two characters in


different memory locations, and to display them one after
the other using the functions getchar() and
putchar().

Slide 33 of 53

Programming in C
Practice: 1.6 (Contd.)

Solution:
/* function to accept and display two characters*/
#include<stdio.h>
main()
{
char a, b;
a=getchar();
fflush(stdin);
b=getchar();
fflush(stdin);
putchar(a);
putchar(b);
}

Ver. 1.0

Slide 34 of 53

Programming in C
String-Based Input-Output Functions

String-based input-output functions are:


gets()
puts()

The following example uses the gets() and puts()


functions:
# include < stdio.h >
/* function to accept and displaying */
main ()
{ char in_str {21}; /* display prompt */
puts ("Enter a String of max 20 characters");
gets (in_str); /* accept string
*/
fflush (stdin); /* clear the buffer */
puts (in_str); /* display input string */
}
Ver. 1.0

Slide 35 of 53

Programming in C
Practice: 1.7

1. Write a function that prompts for and accepts a name with a


maximum of 25 characters, and displays the following
message.
Hello. How are you?
(name)

2. Write a function that prompts for a name (up to 20


characters) and address (up to 30 characters) and accepts
them one at a time. Finally, the name and address are
displayed in the following way.
Your name is:
(name)
Your address is:
(address)

Ver. 1.0

Slide 36 of 53

Programming in C
Practice: 1.7 (Contd.)

Solution:

Ver. 1.0

Slide 37 of 53

Programming in C
Using Constructs

There are two types of constructs in C language:


Conditional constructs
Loop constructs

Ver. 1.0

Slide 38 of 53

Programming in C
Conditional Constructs

Conditional Constructs:
Requires relation operators as in other programming language
with a slight change in symbols used for relational operators.
The two types of conditional constructs in C are:
if..else construct
switchcase construct

Ver. 1.0

Slide 39 of 53

Programming in C
Conditional Constructs (Contd.)

The Syntax of the if..else construct is as follows:


if (condition)
{
statement 1 ;
statement 2 ;
:
}
else
{
statement 1 ;
statement 2 ;
:
}

Ver. 1.0

Slide 40 of 53

Programming in C
Practice: 1.8

1. Write a function that accepts one-character grade code, and


depending on what grade is input, display the HRA
percentage according to the following table.

Ver. 1.0

Grade

HRA %

45%

40%

30%

25%

Slide 41 of 53

Programming in C
Practice: 1.8 (Contd.)

Identify errors, if any, in the following function:


#include<stdio.h>
/*function to check if y or n is input*/
main()
{
char yn;
puts("Enter y or n for yes/no");
yn = getchar();
fflush(stdin);
if(yn=y)
puts("You entered y");
else if(yn=n')
puts("You entered n");
else
puts("Invalid input");
}
Ver. 1.0

Slide 42 of 53

Programming in C
Practice: 1.8 (Contd.)

Solution:

Ver. 1.0

Slide 43 of 53

Programming in C
Conditional Constructs (Contd.)
Syntax of switchcase construct:
switch (variable)
{
case 1 :
statement1 ;
break ;
case 2 :
statement 2 ;
:
:
break;
default :
statement
}

Ver. 1.0

Slide 44 of 53

Programming in C
Practice: 1.9

Write a function to display the following menu and accept a


choice number. If an invalid choice is entered then an
appropriate error message must be displayed, else the
choice number entered must be displayed.
Menu
1. Create a directory
2. Delete a directory
3. Show a directory
4. Exit
Your choice:

Ver. 1.0

Slide 45 of 53

Programming in C
Practice: 1.9 (Contd.)

Solution:

Ver. 1.0

Slide 46 of 53

Programming in C
Loop Constructs

The two types of conditional constructs in C are:


while loop construct.
do..while construct.
The while loop construct has the following syntax:
while (condition in true)
{
statement 1 ;
statement 2 ;

loop
body

Used to iterate a set of instructions (the loop body) as long as


the specified condition is true.

Ver. 1.0

Slide 47 of 53

Programming in C
Loop Constructs (Contd.)

The do..while loop construct:


The do..while loop is similar to the while loop, except that the
condition is checked after execution of the body.
The do..while loop is executed at least once.
The following figure shows the difference between the while loop
and the do...while loop.
while

Evaluate
Condition

do while
Execute
Body of
Loop

False

True
Execute
Body of
Loop

Evaluate
Condition

False

True

Ver. 1.0

Slide 48 of 53

Programming in C
Practice: 1.10

1. Write a function to accept characters from the keyboard until


the character ! is input, and to display whether the total
number of non-vowel characters entered is more than, less
than, or equal to the total number of vowels entered.

Ver. 1.0

Slide 49 of 53

Programming in C
Practice: 1.10 (Contd.)

Solution:

Ver. 1.0

Slide 50 of 53

Programming in C
Summary

In this session, you learned that:


C language was developed by Ken Thompson and Dennis
Ritchie.
C language combines the features of second and third
generation languages.
C language is a block structured language.
C language has various features that make it a widely-used
language. Some of the important features are:
Pointers
Memory Allocation
Recursion
Bit-manipulation

Ver. 1.0

Slide 51 of 53

Programming in C
Summary (Contd.)

The types of data structures provided by C can be classified


under the following categories:
Fundamental data types: Include the data types, which are used
for actual data representation in the memory.
Derived data types: Are based on fundamental data types.

Fundamental data types:


char, int, and float

Some of the derived data types are:


short int, long int, and double float

Definition of memory for any data, both fundamental and


derived data types, is done in the following format:
[data type] [variable name],...;

Ver. 1.0

Slide 52 of 53

Programming in C
Summary (Contd.)

In C language, the functions can be categorized in the


following categories:
Single-level functions
Multiple-level functions

For standard input-output operations, the C environment uses


stdin, stdout, and stderr as references for accessing the
devices.
There are two types of constructs in C language:
Conditional constructs
Loop constructs

Ver. 1.0

Slide 53 of 53

Programming in C
Objectives

In this session, you will learn to:


Work with operators
Use loops
Use formatted input-output functions

Ver. 1.0

Slide 54 of 53

Programming in C
Working with Operators

An operator:
Is a symbol used to command the computer to do
mathematical or logical manipulations.
Operates on data and variables.

C has a rich set of operators, which can be classified into


following various categories:
Relational operators
Logical operators
Unary operators
Binary operators
Ternary operator
Compound assignment operators
Increment/Decrement operators

Ver. 1.0

Slide 55 of 53

Programming in C
Practice: 2.1

Write a function that accepts either y or n only as input. For


any other character input, an appropriate error message
should be displayed and the input is accepted again.

Ver. 1.0

Slide 56 of 53

Programming in C
Practice: 2.1 (Contd.)

Solution:
#include<stdio.h>
main()
{ char yn;
do {
puts(Enter y/n (Yes/No));
yn=getchar ();
fflush (stdin);
if(yn!=y && yn!=n)
puts(Invalid input);
}
while(yn!=y && yn!=n);
}

Ver. 1.0

Slide 57 of 53

Programming in C
Unary Operators

Unary Operators:
Operates on a single operand.
Prefixed to an integer constant.
Tells the compiler to reverse the sign by subtracting the value
(or variable) from zero.
Has the same effect as the sign, which is used to indicate a
number less than zero, for example -12.

Ver. 1.0

Slide 58 of 53

Programming in C
Practice: 2.2

Which of the following are valid?


1. valuea=-12;
/* valuea is int* /
2. valuea = - valueb 12 /* valuea and valueb
both are int */

Ver. 1.0

Slide 59 of 53

Programming in C
Practice: 2.2 (Contd.)

Solution:
1. Valid
2. Valid

Ver. 1.0

Slide 60 of 53

Programming in C
Binary Operators

Binary Operators:
Operate on two operands.
Are as follows:
+ (add)
- (subtract)
* (multiply)
/ (divide)
% (modulo)

Ver. 1.0

Slide 61 of 53

Programming in C
Practice: 2.3

In the following set of statements:


char ch;
ch=S;
ch=ch+a-A;
ch=ch+A-a;

/*statement A*/
/*statement B*/

What will be the value of ch after:


1. Statement A is executed?
2. Statement B is executed?

Ver. 1.0

Slide 62 of 53

Programming in C
Practice: 2.3 (Contd.)

Solution:
1. ch is equal to s. Note that a-A gives 32 after statement 1 is
executed.
2. ch is back to S after statement 2 is executed.

Ver. 1.0

Slide 63 of 53

Programming in C
Binary Operators (Contd.)

There are some set or rules, if followed, would prevent


unexpected results, at the time of execution of programs:
Any operand of type char is converted to int.
All floats are converted to doubles.
If either operand is double, the other is converted to a
double, giving a double result.

Ver. 1.0

Slide 64 of 53

Programming in C
Practice: 2.4

1. In which of the following assignments is there no loss of


data? (i is an int, f a float, and d a double)
i=d;
d=f;
f=d;
i=f+d;
d=i+f;

2. Is type casting necessary in the following example?


int i,j;
float f;
double d;
d=f+(float) i + j;

Ver. 1.0

Slide 65 of 53

Programming in C
Practice: 2.4 (Contd.)

Solution:
1. a. Loss of data. int set equal to a double.
b. No loss of data. double set equal to a float.
c. Loss of data. float set equal to a double.
d. Loss of data. Right-hand result is a double while left-hand
side is just an int.
e. No loss of data. Right-hand result is a double and
left-hand side is also a double.
2. Not necessary. The ints will automatically be converted to
doubles (following the conversion of the float to a double).

Ver. 1.0

Slide 66 of 53

Programming in C
Ternary Operator

Ternary Operator:
Is a shorthand method for writing if.else conditional
construct.
Helps in reducing lines of code.
Has the following form for the expression using the ternary
operator:
(test-expression) ? T-expression : F-expression;

Ver. 1.0

Slide 67 of 53

Programming in C
Ternary Operator (Contd.)

Consider the following example:


if(condition)
{ Statements if condition is true }
else
{ Statements if condition is false }

Can be rewritten using the shorthand operator as follows:


larger_of_the_two = ( x > y ) ? x : y;

Ver. 1.0

Slide 68 of 53

Programming in C
Practice: 2.5

1. State whether True or False:


In the general form of an expression that uses a ternary operator,
the test expression will be checked. If it is true, the T-expression
will be evaluated, otherwise the F-expression will be evaluated.

2. What will the following statement do?


quotient = (b==0) ? 0 : (a/b); /*a, b, and
quotient are ints*/

3. Can the preceding statement be written as follows?


quotient = (b) ? (a/b) : 0;

4. What will the following statement do?


always_negative = (j>0) ? j : (-j);

Ver. 1.0

Slide 69 of 53

Programming in C
Practice: 2.5 (Contd.)

Solution:
1. True.
2. If b is non-zero, it will determine the quotient of a and b. If b
equals zero, quotient is set to 0.
3. Yes. Note that if b is non-zero, the test expression (b)
evaluates to true and hence quotient is set to (a/b).
4. The variable always_negative will always take on a nonnegative value, i.e. it will be assigned the absolute value of j.
The name of the variable always_negative is just a red
herring. Remember that self-documenting variable names will
help in writing programs that are readable. Note the unary
operator (-j).

Ver. 1.0

Slide 70 of 53

Programming in C
Compound Assignment Operators

Compound Assignment Operators:


Are useful especially when long variable names are used.
Has the following general form:
left-value op= right-expression;

Here op can be either + (add), - (subtract, * (multiply), /


(divide), and % (modulo).

Consider the following example:


a_very_long_identifier=a_very_long_identifier + 2;

It can be written as:


a_very_long_identifier += 2;

Ver. 1.0

Slide 71 of 53

Programming in C
Increment / Decrement Operators

Increment / Decrement Operators:


Are used to increase or decrease the value of a variable by 1.
Has the following two forms:
The ++ (two plus symbols without a space), called the increment
operator while that in ++ before the variable is called the pre
increment operator and after the variable is called the post
increment operator.
The -- (two minus symbols without a space), called the decrement
operator while that in ++ before the variable is called the pre
decrement operator and after the variable is called the post
increment operator.

Ver. 1.0

Slide 72 of 53

Programming in C
Increment / Decrement Operators (Contd.)

Consider the following code snippet:


total = sum++;
total = ++sum;

/* statement A */
/* statement B */

The first statement is equivalent to:


total = sum; sum = sum + 1;

While the second is the same as:


sum = sum + 1; total = sum;

Ver. 1.0

Slide 73 of 53

Programming in C
Practice: 2.6

1. Consider the following code snippet:


int sum
total =
total =
total =
total =

= 3, total = 5;
sum++;
++sum;
/*statement A */
sum
--sum;
/*statement B */

What will be the values of total and sum after:


a. statement A is executed?
b. statement B is executed?

Ver. 1.0

Slide 74 of 53

Programming in C
Practice: 2.6 (Contd.)

2. State whether True or False:


The following statement:
for(i = 0; i< 100); i = i + 1)
{
Some statements
}
can be written as:
for (i = 0; i < 100; i++)
{
Some statements
}

Ver. 1.0

Slide 75 of 53

Programming in C
Practice: 2.6 (Contd.)

3. State whether True or False:


The for statement in #2 can also be written as:
fori = 0; i < 100; ++i)/*Note: ++i and not i++*/
{
Some statements
}

4. Write a program, which reads in a year and reports on


whether it is a leap year or not (centuries should also be
considered).

Ver. 1.0

Slide 76 of 53

Programming in C
Practice: 2.6 (Contd.)

Solution:
1. total=5, sum=5
total=3, sum=3
quite a complicated way of reducing total by 2.
2. True. i+1 is equivalent to i++.
3. True. i+1 is equivalent to 1+i.
4.

Ver. 1.0

Slide 77 of 53

Programming in C
Using Loops
The while and dowhile looping constructs are generally
used in situations where the number of execution of the loop
is not known.
The for loop construct is used when the number of
execution of the loop is known.

Ver. 1.0

Slide 78 of 53

Programming in C
The for Loop Construct

The for loop construct:


Has three components in the loop control:
Initialization
Condition
Re-initialization (increment/decrement)

Has the following sequence of execution:


Initialization
Evaluation of loop condition
Body of loop
Re-initialization

Ver. 1.0

Slide 79 of 53

Programming in C
The for Loop Construct (Contd.)

The sequence of execution of a complete for loop construct


is shown in the following figure.
INITIALIZATION

FALSE
EVALUATE
CONDITION

TRUE
BODY OF LOOP

REINITIALIZATION

Ver. 1.0

Slide 80 of 53

Programming in C
The for Loop Construct (Contd.)

In a for loop construct:


Multiple initializations and/or multiple re- initializations, are
separated by commas.
Multiple conditions are specified using logical operators.

Ver. 1.0

Slide 81 of 53

Programming in C
Practice: 2.7

1. Write a function to accept twenty characters from the


character set, and to display whether the number of lowercase characters is greater than, less than, or equal to
number of upper-case characters. Display an error message
if the input is not an alphabet.
2. Modify the function to accept characters endlessly until the
character ! is input from keyboard.

Ver. 1.0

Slide 82 of 53

Programming in C
Practice: 2.7 (Contd.)

Solution:
1.

2.

Ver. 1.0

Slide 83 of 53

Programming in C
Controlling the Loop Execution

At times there is a need to exit from a loop before the loop


condition is re-evaluated after iteration.
To exit from loop control, break and continue statements
are used.

Ver. 1.0

Slide 84 of 53

Programming in C
Practice: 2.8

Write a function, which accepts numbers until 0 is entered or


10 numbers have been accepted. The function prints the
total number of entries, the number of positive entries, and
the sum of all the positive numbers.

Ver. 1.0

Slide 85 of 53

Programming in C
Practice: 2.8 (Contd.)

Solution:

Ver. 1.0

Slide 86 of 53

Programming in C
Using Formatted Input-Output Functions

C provides the following functions for formatted input-output:


printf()
scanf()

Ver. 1.0

Slide 87 of 53

Programming in C
Formatted Output

Syntax of the formatted output function printf() is:


printf (format, data1, data 2, .);

Consider the following example:


printf(%c, inp);

The character specified after % is called a conversion


character.
The conversion character allows one data type to be
converted to another type and printed.

Ver. 1.0

Slide 88 of 53

Programming in C
Formatted Output (Contd.)

The conversion characters and their meanings are shown in


the following table.
Character

Ver. 1.0

Meaning

the data is converted to decimal (integer)

the data is taken as a character

the data is a string and characters from


the string are printed until a NULL
character is reached

the data is output as a double or float with


a default precision to 6

Slide 89 of 53

Programming in C
Practice: 2.9

What is the output of the statement:


printf(Integer is: %d; Alphabet is: %c\n,
inum, inp);

where inum contains 15 and inp contains Z.

Ver. 1.0

Slide 90 of 53

Programming in C
Practice: 2.9 (Contd.)

Solution:
Integer is: 15; Alphabet is Z.

Ver. 1.0

Slide 91 of 53

Programming in C
Formatted Input

The scanf() function is used for formatted input.


The syntax for the scanf() functions is as follows:
scanf (format, data1, data2);

Here
format
- The format-specification string
data1, data2 - Data names where the input data
is to be stored as per the
format-specification string

Ver. 1.0

Slide 92 of 53

Programming in C
Formatted Input (Contd.)

The format-specification string in scanf() consists of:


Blanks, tabs, (also called white space characters).
New line which are ignored.
Conversion consisting of %, an optional number specification
specifying the width and a conversion character.

While accepting strings using scanf(), a space is


considered as a string terminator.

Ver. 1.0

Slide 93 of 53

Programming in C
Practice: 2.10

Write a function to accept and display the element number


and the weight of a Proton. The element number is an
integer and weight is fractional.

Ver. 1.0

Slide 94 of 53

Programming in C
Practice: 2.10 (Contd.)

Solution:
#include<stdio.h>
main()
{
int e_num;
float e_wt;
printf(Enter the Element No. and Weight of a
Proton\n);
scanf(%d %f, &e_num, &e_wt);
fflush(stdin);
printf(The Element No. is: , e_num);
printf(The weight of a Proton is: %f\n,
e_wt);
}
Ver. 1.0

Slide 95 of 53

Programming in C
Practice: 2.11

Write a function to input a string of continuous characters


with no white space as part of the input. The function should
assign the input to variables of the types specified in the
following table.
Position of character from
start of string

Number of
characters

Type of argument to
assign

int

float

char (string)

int

The function should also print out each of the assigned data
items in separate lines.

Ver. 1.0

Slide 96 of 53

Programming in C
Practice: 2.11

Solution:
#include<stdio.h>
main()
{
int i,j;
char str[3];
float fnum;
printf(Enter a string of 11 chrs\n);
/*why
11: because 11 is the total length of */
/*input.*/
scanf(%2d %4f %2s %3d,&i, &fnum, str, &j);
fflush(stdin);
printf(%2d\n %4f\n %2s\n %3d\n, i, fnum,
str, j);
}
Ver. 1.0

Slide 97 of 53

Programming in C
Summary

In this session, you learned that:


An operator is a symbol that is used to command the computer
to do mathematical or logical manipulations.
The operators in C language are classified into the following
categories:
Logical operators
Unary operators
Binary operators
Ternary operator
Compound assignment operators
Increment/Decrement operators

Ver. 1.0

Slide 98 of 53

Programming in C
Summary (Contd.)

The logical operators of C and their notations are as follows.


Operator

Notation

OR

||

AND

&&

NOT

The unary operator prefixed to an integer constant or variable


tells the compiler to reverse the sign by subtracting the value
or variable from zero.
Binary operators in C language are + (add), - (subtract), *
(multiply), / (divide), and % (modulo).
Ternary operator offers a shorthand way of writing the
commonly used ifelse construct.

Ver. 1.0

Slide 99 of 53

Programming in C
Summary (Contd.)

The syntax for using the ternary operator is:


(test-expression) ? T-expression : F-expression;

Compound assignment operators simplify the statements.


Increment / Decrement operators are used to
increment/decrement a variable by 1.
A for loop is used when the number of execution of the loop
is known.
The components of a for loop construct are:
initialization
loop condition
reinitialization (increment/decrement)

Ver. 1.0

Slide 100 of 53

Programming in C
Summary (Contd.)

The sequence of execution of a complete for loop is:


initialization
evaluation of the loop condition
the body of the loop
reinitialization

The break and continue statements are used to exit from


loop control.
The break statement is used to exit from all loop constructs
(while, do...while, and for) and switch...case
statements.
The continue statement is used to skip all subsequent
instructions and brings the control back to the loop.
The function printf() is used for formatted output to
standard output based on a format specification.

Ver. 1.0

Slide 101 of 53

Programming in C
Summary (Contd.)

The syntax of the function printf() is:


printf(format, datal, data 2,,..);

The function scanf() is used for formatted input from


standard input and provides many of the conversion facilities of
the function printf().
The syntax of the function scanf() is:
scanf (format, datal, data2, ...);

Ver. 1.0

Slide 102 of 53

Programming in C
Objectives

In this session, you will do the practice questions of Chapter


1 and Chapter 2.

Ver. 1.0

Slide 103 of 53

Programming in C
Chapter 1

1. Write a function to accept a character and display it 40


times.
2. Write a function that accepts a number from 0 to 9, along
with a string. The string should then be displayed the
number of times specified.

Ver. 1.0

Slide 104 of 53

Programming in C
Chapter 2

1. Write a for loop, which will produce the following output


(Hint: use two nested for loops):
1
22
333
4444
55555
2. Create a C program, which calculates the triangular number
of the users request, read from the keyboard using scanf().
A triangular number is the sum of the preceding numbers,
so the triangular number 7 has the value of 7+6+5+4+3+2+1
(same as a factorial in mathematics, for example, factorial of
7 ---- !7).

Ver. 1.0

Slide 105 of 53

Programming in C
Chapter 2

3. Create a C program to check whether the number entered


by user is even or odd.

Ver. 1.0

Slide 106 of 53

Programming in C
Objectives

In this session, you will learn to:


Work with arrays
Appreciate preprocessor directives

Ver. 1.0

Slide 107 of 53

Programming in C
Working with Arrays

Arrays:
Are a group of similar objects.
Can be defined as a contiguous area in memory.
Can be referred to by a common name.
Has a unique identifier for each element, called as a subscript
or an index.
Can be categorized as:
One-dimensional/Single-dimensional arrays
Multidimensional arrays

Ver. 1.0

Slide 108 of 53

Programming in C
One-Dimensional Arrays

The syntax for declaring a one-dimensional array is:


type arrayname[n];

For Example:
char string [11];
Defines a character array named string to store 10
characters.
string[0] to string[9] are for valid characters.
string[10] for the string-terminator character, \0 (NULL).

Similarly:
int numbers [11];

Defines an integer type array called numbers to store 11


integers.
Integers are stored in numbers[0] to numbers[10].

Ver. 1.0

Slide 109 of 53

Programming in C
Practice: 3.1

1. Write the array definition statements for storing the following


data:
a. Ten amounts with paisa.
b. Five ages to be stored in years and six non-fractional
quantities.
c. A thirty character long name.

Ver. 1.0

Slide 110 of 53

Programming in C
Practice: 3.1 (Contd.)

Solution:
a. float fnum[10];
b. int age[5], qty[6];
c. char name[31];

Ver. 1.0

Slide 111 of 53

Programming in C
One-Dimensional Arrays (Contd.)

Initializing Arrays:
An array can be initialized, when declared.
Initialization at the time of declaration is possible only outside a
function unless it is declared static.
Direct initialization is possible in the following ways:
char strl[7]={E,X,O,D,U,S,\0};
char str2[7]={"EXODUS"};
In the first case, individual elements have been moved into the
array. Therefore, it is essential that the string terminator be
specified explicitly. While in the second case, the string
terminator gets attached automatically because a string has
been assigned.

Ver. 1.0

Slide 112 of 53

Programming in C
Practice: 3.2

1. Write a function that stores the alphabets A to Z in an array


by applying arithmetic on ASCII codes, given that the ASCII
code of character A is 65. The function should display the
string also.
2. In a file-delete utility program for 256 files the user response
to whether a file is to be deleted or not is to be stored in an
array as Y for yes and N for no for all files. By default the
user response should be N for all files. Write a function that
sets up an array and accepts user-responses.

Ver. 1.0

Slide 113 of 53

Programming in C
Practice: 3.2 (Contd.)

Solution:

Ver. 1.0

Slide 114 of 53

Programming in C
One-Dimensional Arrays (Contd.)

Array elements:
Are referenced by using subscripts.
Are integers, therefore array manipulation is possible through
the use of variables.

Ver. 1.0

Slide 115 of 53

Programming in C
Practice: 3.3

1. Write a function to convert a character string into


lower-case.
2. Write a function to compare two strings and to print the
larger one. The strings may be compared in terms of ASCII
code of each character in the strings.

Ver. 1.0

Slide 116 of 53

Programming in C
Practice: 3.3 (Contd.)

Solution:

Ver. 1.0

Slide 117 of 53

Programming in C
Practice: 3.4

1. Write a function to accept up to 25 numbers and to display


the highest and lowest numbers along with all the numbers.

Ver. 1.0

Slide 118 of 53

Programming in C
Practice: 3.4 (Contd.)

Solution:

Ver. 1.0

Slide 119 of 53

Programming in C
One-Dimensional Arrays (Contd.)

Array Addressing:
To arrive at a particular element, the following formula is
applied:
Starting address + ( Offset number * Scaling
factor) of the array

Here,
Scaling factor is the number of bytes of storage space required
by the specific data type.
Offset number * Scaling factor gives the number of bytes
to be added to the starting address of the array to get to a desired
element.

Ver. 1.0

Slide 120 of 53

Programming in C
Practice: 3.5

1. Write a program in C to extract a substring from a specified


position containing a specified number of characters from
an input string.

Ver. 1.0

Slide 121 of 53

Programming in C
Practice: 3.5 (Contd.)

Solution:

Ver. 1.0

Slide 122 of 53

Programming in C
Multidimensional Arrays

C also supports multidimensional arrays.


A two-dimensional array is the simplest form of the
multidimensional array.
A two-dimensional array is an array of one-dimensional
arrays.
A two-dimensional array is also known as a two-d array.
A two-d array is declared as follows:
type arrayname[Row][Col];

Rules for initializing a two-d array are same as that of a


one-dimensional array.
The row subscript may be left blank for a more flexible
declaration.

Ver. 1.0

Slide 123 of 53

Programming in C
Practice: 3.6

1. State whether True or False:


If the number of salesmen is 5, then the declaration of the
two-dimensional array and its initialization to zero would be:
int

s_p_array [5][4] = {
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},

};

Ver. 1.0

Slide 124 of 53

Programming in C
Practice: 3.6 (Contd.)

Solution:
1. False. Note that since there are 5 salesman with 4 products,
there should be 5 sets of {}, each containing four zeroes. The
correct initialization is:
int s_p_array [5][4] = {
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
};

Ver. 1.0

Slide 125 of 53

Programming in C
Multidimensional Arrays (Contd.)

Two-Dimensional Character Arrays:


Are typically used to create an array of strings.
Use two subscripts, one for row and the other for column.
Are declared as:
char err_msg [row] [col];

Can be initialized at the time of declaration.

Ver. 1.0

Slide 126 of 53

Programming in C
Practice: 3.7

1. Based on the books array, predict the output of the following


commands:
a. printf(%c, books[2][5]);
b. printf(%s,books[3]);
c. printf(%d,books[4][7]);

Ver. 1.0

Slide 127 of 53

Programming in C
Practice: 3.7 (Contd.)

Solution:
a. M
b. Birds, Beasts, and Relatives
c. 97

Ver. 1.0

Slide 128 of 53

Programming in C
Practice: 3.8

1. Write the program segment to calculate the class average


across students in each subject.
2. Assume that the data exists in the arrays and averages
have been calculated. Write program segments, which will
allow the user to query on the arrays to:
a. Display Student Names and Average Marks.
b. Display Subjects and Class Averages.

Ver. 1.0

Slide 129 of 53

Programming in C
Practice: 3.8 (Contd.)

c. Display Marks of a specific Student in a specific Subject.


d. Display Subject wise marks of all students whose average is
above 80.

For each option the following action needs to be taken.


OPTION

Ver. 1.0

ACTION

a.

Display each student's name along with his average marks.

b.

Display each subject along with class average on the subject.

c.

Display list of students and list of subjects. Allow the user to


choose one from each. Based on the numbers chosen, display
the appropriate marks. Remember, subscripting in C starts from
zero.

d.

Check the average of each student. Wherever average exceeds


80, display the student name and the subject name and marks
in each subject.

Slide 130 of 53

Programming in C
Practice: 3.8 (Contd.)

Solution:

Ver. 1.0

Slide 131 of 53

Programming in C
Appreciating Preprocessor Directives

Preprocessor directives:
Are instructions to the compiler in the source code of a C
program.
Are not actually a part of the C language.
Expand the scope of the C programming environment.
Begin with a #.

#include is also a preprocessor directive.


#include instructs the compiler to include the specified
source file into the one which contains the #include
directive.
#define defines an identifier and a string constant that will
be substituted for the identifier each time it is encountered in
the file.

Ver. 1.0

Slide 132 of 53

Programming in C
Appreciating Preprocessor Directives (Contd.)

It helps in reducing the chances of inconsistency within the


program and also makes the program easy to modify.
Consider the following macro definition:
#define TRUE 1
No semicolon is required after the statement.
Every time the compiler encounters the string TRUE in the
program, it substitutes it with the value 1.
No text substitution will occur if the identifier is enclosed
within quotes.

Ver. 1.0

Slide 133 of 53

Programming in C
Summary

In this session, you learned that:


An array can be defined as a contiguous area in memory,
which can be referred to by a common name.
In C, arrays can be categorized as:
One-dimensional/Single-dimensional arrays
Multidimensional arrays

The syntax for declaring a one-dimensional array is as follows:


type arrayname[n];

Array elements are referenced by using subscripts.


The last element in a character array is reserved to store the
string terminator character \0 (NULL).
An array can be initialized, when declared, by specifying the
values of some or all of its elements.
Initialization can also be done inside the function, after the
array has been declared, by accepting the values.
Ver. 1.0

Slide 134 of 53

Programming in C
Summary (Contd.)

To arrive at the particular element, the following formula is


applied:
Starting address + ( Offset number * Scaling
factor) of the array

C supports multidimensional arrays.


The simplest form of the multidimensional array is the
two-dimensional (two-d) array.
The general form of declaration of the two-d array would be:
type arrayname[x][y];

Two-dimensional integer arrays are very much like


one-dimensional integer arrays, the only difference being that
two-dimensional arrays have two indices.
Initialization of two-dimensional arrays can be done at the time
of declaration itself.
A better way to initialize a two-dimensional array is using the
for statement.
Ver. 1.0

Slide 135 of 53

Programming in C
Summary (Contd.)

Two-dimensional character arrays are declared in the same


way as two-dimensional integer arrays:
The first index specifies the number of strings.
The second index specifies the length of the longest string plus
one.

Initialization can be done along with declaration, if done


outside main().
Preprocessor directives are not actually a part of the C
language; they expand the scope of the C programming
environment.
The preprocessor directives normally begin with a #.
#include is also a preprocessor directive. It instructs the
compiler to include the specified source file into the one which
contains the #include directive.

Ver. 1.0

Slide 136 of 53

Programming in C
Summary (Contd.)

The #define statement can be used to declare a variable with


a constant value throughout the program. It helps in:
Reducing the chances of inconsistency within the program.
Making modification easier, as the value has to be changed only
at one place.

Ver. 1.0

Slide 137 of 53

Programming in C
Objectives

In this session, you will learn to:


Declare and manipulate pointers
Use pointers to manipulate character arrays

Ver. 1.0

Slide 138 of 53

Programming in C
Declaring and Manipulating Pointers

Every stored data item occupies one or more contiguous


memory cells.
Every cell in the memory has a unique address.
Any reference to a variable, declared in memory, accesses
the variable through the address of memory location.
Pointers are variables, which contain the addresses of other
variables (of any data type) in memory.

Ver. 1.0

Slide 139 of 53

Programming in C
Declaring Pointers

A pointer variable must be declared before use in a


program.
A pointer variable is declared preceded by an asterisk.
The declaration:
int *ptr; /* ptr is pointing to an int */

Indicates that ptr is a pointer to an integer variable.


An uninitialized pointer may potentially point to any area of
the memory and can cause a program to crash.
A pointer can be initialized as follows:
ptr= &x;
In the preceding initialization, the pointer ptr is pointing to x.

Ver. 1.0

Slide 140 of 53

Programming in C
Practice: 4.1

1. In the following declaration:


float *ptr_to_float;

The pointer variable ptr_to_float is pointing to a


variable of type ____________.
2. Is the following declaration valid?
*ptr_to_something;

3. State whether True or False:


An integer is declared In the following declaration:
int *ptr_to_int;

4. Is the following declaration valid?


int some_int, *ptr_to_int;

Ver. 1.0

Slide 141 of 53

Programming in C
Practice: 4.1 (Contd.)

Solution:
1. float
2. No. When a pointer variable is being declared, the type of
variable to which it is pointing to (int, float, or char)
should also be indicated.
3. False. A pointer to an integer is being declared and not an
integer.
4. Yes. It is okay to club declaration of a certain type along with
pointers to the same type.

Ver. 1.0

Slide 142 of 53

Programming in C
Manipulating Pointers

Pointers can be manipulated like variables.


The unary operator * gives value of the variable a pointer is
pointing to.
The unary operator * is also termed as the indirection
operator.
The indirection operator can be used only on pointers.

Ver. 1.0

Slide 143 of 53

Programming in C
Practice: 4.2

1. The symbol _________ is used to obtain the address of a


variable while the symbol__________ is used to obtain the
value of the variable to which a pointer is pointing to.
2. With the following declarations:
int x, y, *ptr;
Which of the following are meaningful assignments?
a.
b.
c.
d.
e.
f.

Ver. 1.0

x = y;
y=*ptr;
x = ptr;
x = &.ptr;
ptr = &x;
x = &y;

Slide 144 of 53

Programming in C
Practice: 4.2 (Contd.)

3. Consider the following sequence of statements and


complete the partially-filled table:
int x, y, *ptrl, *ptr2;
x = 65;
y = 89;
ptr1 = &x; /*ptrl points to x */
ptr2 = &y/;
/* ptr2 points to y */
x = *ptr1; /* statement A*)
ptr1 = ptr2:
/* statement B */
x = *ptr1; /* statement C*/

After statement
A
B
C
Ver. 1.0

&x
1006

&y
1018

ptr1

ptr2

Slide 145 of 53

Programming in C
Practice: 4.2 (Contd.)

4. What is the output of the following sequence of statements:


int x, y, temp,*ptrl, *ptr2;
/* declare */
x = 23;
y = 37;
ptrl = &x;/* ptrl points to x */
ptr2 = &y;/* ptr2 points to y */
temp = *ptrl;
*ptr1 = *ptr2;
*ptr2 = temp;
printf(x is %d while y is %d, x, y);

Ver. 1.0

Slide 146 of 53

Programming in C
Practice: 4.2 (Contd.)

Solution:

Ver. 1.0

Slide 147 of 53

Programming in C
Pointer Arithmetic

Pointer Arithmetic:
Arithmetic operations can be performed on pointers.
Therefore, it is essential to declare a pointer as pointing to a
certain datatype so that when the pointer is incremented or
decremented, it moves by the appropriate number of bytes.
Consider the following statement:
ptr++;
It does not necessarily mean that ptr now points to the next
memory location. The memory location it will point to will
depend upon the datatype to which the pointer points.
May be initialized when declared if done outside main().
Consider the following example:
#include <stdio.h>
char movie[]= Jurassic Park;
main() {
char *ptr;
Ver. 1.0

Slide 148 of 53

Programming in C
Pointer Arithmetic (Contd.)

Consider the following example:


#include <stdio.h>
char movie[]= Jurassic Park;
main() {
char *ptr;
ptr=movie;
printf(%s, movie); /* output: Jurassic Park */
printf(%s,ptr); /* output: Jurassic Park */
ptr++;
printf(%s,movie); /* output: Jurassic Park */
printf(%s",prr); /* output: urassic Park */
ptr++;
printf(%s,movie); /* output; Jurassic Park */
printf(%s,ptr); /* output: rassic Park */
/* Note that the incrementing of the pointer ptr
does not in any way affect the pointer movie */
}

Ver. 1.0

Slide 149 of 53

Programming in C
Practice: 4.3

1. Consider the following code snippet:


#include <stdio.h>
int one_d[] = {l,2,3};
main(){
int *ptr;
ptr = one_d;
ptr +=3; /* statement A*/
printf(%d\n, *ptr); /*statement B */
}
a. After statement A is executed, the new address of ptr will be
____ bytes more than the old address.
b. State whether True or False:
The statement B will print 3.

Ver. 1.0

Slide 150 of 53

Programming in C
Practice: 4.3 (Contd.)

Solution:
a. 12 ( Size of integer = 4*3)
b. False. Note that ptr is now pointing past the one-d array. So,
whatever is stored (junk or some value) at this address is
printed out. Again, note the dangers of arbitrary assignments
to pointer variables.

Ver. 1.0

Slide 151 of 53

Programming in C
Using Pointers to Manipulate Character Arrays

Array name contains the address of the first element of the


array.
A pointer is a variable, which can store the address of another
variable.
It can be said that an array name is a pointer. Therefore, a
pointer can be used to manipulate an array.

Ver. 1.0

Slide 152 of 53

Programming in C
One-Dimensional Arrays and Pointers

One-Dimensional Arrays and Pointers:


Consider the following example:
#include <stdio.h>
char str[13]={Jiggerypokry};
char strl[]={ Magic};
main() {
char *ptr;
printf(We are playing around with %s", str);
/* Output: We are playing around with Jiggerypokry*/
ptr=str ; /* ptr now points to whatever str is
pointing to */
printf(We are playing around with %s" ,ptr);
/* Output: We are playing around with Jiggerypokry */
}

Ver. 1.0

Slide 153 of 53

Programming in C
One-Dimensional Arrays and Pointers (Contd.)

In the preceding example the statement:


ptr=str;

Gives the impression that the two pointers are equal. However,
there is a very subtle difference between str and ptr. str is a
static pointer, which means that the address contained in str
cannot be changed. While ptr is a dynamic pointer. The address
in ptr can be changed.

Ver. 1.0

Slide 154 of 53

Programming in C
Practice: 4.4

1. Given the declaration:


char some_string [10];
some_string points to _________.

2. State whether True or False:


In the following declaration, the pointer err_msg contains a
valid address:
char *err_msg = Some error message;

3. State whether True or False:


Consider the following declaration:
char *err_msg = Some error message;
It is more flexible than the following declaration:
char err_msg[19]=Some error message;

Ver. 1.0

Slide 155 of 53

Programming in C
Practice: 4.4 (Contd.)

Solution:
1. some_string [0]
2. True
3. True. Note that one does not have to count the size of the
error message in the first declaration.

Ver. 1.0

Slide 156 of 53

Programming in C
Two-Dimensional Arrays and Pointers

Two-dimensional arrays can be used to manipulate multiple


strings at a time.
String manipulation can also be done by using the array of
pointers, as shown in the following example:
char *things[6]; /* declaring an array of 6
pointers to char */
things[0]=Raindrops on roses;
things[1]=And Whiskers on kettles;
things[2]=Bright copper kettles;
things[3]=And warm woolen mittens;
things[4]=Brown paper packages tied up with
strings;
things[5]=These are a few of my favorite
things;
Ver. 1.0

Slide 157 of 53

Programming in C
Two-Dimensional Arrays and Pointers (Contd.)

The third line of the song can be printed by the following


statement:
printf(%s, things[2]);
/*Output: Bright copper kettles */

Ver. 1.0

Slide 158 of 53

Programming in C
Practice: 4.5

1. State whether True or False:


While declaring two-dimensional character arrays using
pointers, yon do not have to go through the tedium of
counting the number of characters in the longest string.
2. Given the following error messages:
All's well
File not found
No read permission for file
Insufficient memory
No write permission for file

Write a program to print all the error messages on screen,


using pointers to array.

Ver. 1.0

Slide 159 of 53

Programming in C
Practice: 4.5 (Contd.)

Solution:
1. True. New strings can be typed straight away within the {}. As
in:
char *err_msg_msg[]= {
All's well,
File not found,
No read permission for file,
Insufficient memory,
No write permission for file
};

The number of strings will define the size of the array.

Ver. 1.0

Slide 160 of 53

Programming in C
Practice: 4.5 (Contd.)

2.

The program is:


# include<stdio.h>
# define ERRORS 5
char *err_msg[]= { /*Note the missing index*/
All's well,
File not found,
No read permission for file,
Insufficient memory,
No write permission for file };
main() {
int err_no;
for ( err_no = 0; err_no < ERRORS; err_no++ ) {
printf ( \nError message %d is : %s\n, err_no +
1, err_msg[err_no]); } }

Ver. 1.0

Slide 161 of 53

Programming in C
Two-Dimensional Arrays and Pointers (Contd.)

Consider the following two-d array declaration:


int num[3][4]= {
{3, 6, 9, 12},
{15, 25, 30, 35},
{66, 77, 88, 99}
};
This statement actually declares an array of 3 pointers (constant)
num[0], num[l], and num[2] each containing the address of
the first element of three single-dimensional arrays.
The name of the array, num, contains the address of the first
element of the array of pointers (the address of num[0]).

Here,
*num is equal to num[0] because num[0] points to num[0][0].
*(*num) will give the value 3.
*num is equal to num[0].

Ver. 1.0

Slide 162 of 53

Programming in C
String-Handling Functions Using Pointers

Pointers can be used to write string-handling functions.


Consider the following examples:
/* function to calculate length of a string*/
#include <stdio.h>
main() {
char *ptr, str[20];
int size=0;
printf(\nEnter string:);
gets(str);
fflush(stdin);
for(ptr=str ; *ptr != '\0'; ptr++) {
size++;
} printf(String length is %d, size);
}

Ver. 1.0

Slide 163 of 53

Programming in C
Using Pointers to Manipulate Character Arrays (Contd.)

/*function to check for a palindrome */


# include <stdio.h>
main() {
char str[50],*ptr,*lptr;
printf(\nEnter string :);
gets(str); fflush(stdin);
for(lptr=str; *lptr !=\0'; lptr++);
/*reach
the string terminator */
lptr--; /*position on the last character */
for(ptr=str; ptr<=lptr; lptr--,ptr++) {
if(*ptr != *lptr)
break;}
if(ptr>lptr)
printf(%s is a palindrome );
else
printf(%s is not a palindrome");
}
Ver. 1.0

Slide 164 of 53

Programming in C
Summary

In this session, you learned that:


A pointer is a variable, which contains the address of some
other variable in memory.
A pointer may point to a variable of any data type.
A pointer can point to any portion of the memory.
A pointer variable is declared as:
datatype *<pointer variable name>

A pointer variable is initialized as:


pointer variable name> = &<variable name to which
the pointer will point to>

The & returns the address of the variable.


The * before a pointer name gives the value of the variable to
which it is pointing.

Ver. 1.0

Slide 165 of 53

Programming in C
Summary (Contd.)

Pointers can also be subjected to arithmetic.


Incrementing a pointer by 1 makes it point to a memory
location given by the formula:
New address = Old address + Scaling factor

One-dimensional character arrays can be declared by


declaring a pointer and initializing it.
The name of a character array is actually a pointer to the first
element of the array.
Two-dimensional character arrays can also be declared by
using pointers.

Ver. 1.0

Slide 166 of 53

Programming in C
Objectives

In this session, you will learn to:


Implement modular approach in C programs
Use library functions for string manipulation
Work with data storage types

Ver. 1.0

Slide 167 of 53

Programming in C
Implementing Modular Approach in C Programs

Functions are the building blocks of C.


Every C program must consist of at least one function,
main().
The main() function is the entry point of a C program.

Ver. 1.0

Slide 168 of 53

Programming in C
Advantages of Functions

Functions:
Allow reusability of code and structuring of programs.
Provide programmers a convenient way of designing
programs.

Ver. 1.0

Slide 169 of 53

Programming in C
Parameters of Functions

A parameter:
Is the data that the function must receive when called from
another function.
May or may not be present in a function.
Of a user-defined function is declared outside the {} of that
function.

Ver. 1.0

Slide 170 of 53

Programming in C
Practice: 5.1

1. From the following program, identify the functions invoked


from main(), and state which functions have parameters.
Also state the parameters.

Ver. 1.0

Slide 171 of 53

Programming in C
Practice: 5.1 (Contd.)

Solution:
1. The standard functions used in this program within main() are
as follows:
scanf() parameters are format of input, and pointers to the
variable(s) in which the input must be stored
fflush() parameter is stdin
The user-defined functions are:
output() no parameters
calc() one parameter, g, an int type data

Ver. 1.0

Slide 172 of 53

Programming in C
Invoking Functions

Functions that have parameters are invoked in one of the


following ways:
Call by value: In call by value, the called function cannot refer
to the variables of the caller function directly, but creates its
own copy of the values in different variables.
Call by reference: In call by reference, the called function
should be able to refer to the variables of the caller function
directly, and does not create its own copy of the values in
different variables. It is possible only if the addresses of the
variables are passed as parameters to a function.

Ver. 1.0

Slide 173 of 53

Programming in C
Passing Arrays to Functions

Arrays are inherently passed to functions through call by


reference method.
An array can be passed to a function in the following way:
Function name (array name);

Ver. 1.0

Slide 174 of 53

Programming in C
Practice: 5.2

1. If the variable avar is passed to a function by a call by


reference, can the value of the variable avar be modified in
the called function? Give reasons for your answer.
2. State whether True or False:
When an array is passed to a function, the array elements
are copied into the parameter of the function.
3. Consider the program code given in the following file.

Ver. 1.0

Slide 175 of 53

Programming in C
Practice: 5.2 (Contd.)

Based on the code, answer the following questions:


a. The function (max() / min()) is invoked by a call by value.
b. The function (max() / min()) is invoked by a call by reference.
c. After the function max() is executed, where does the control go to:
i. The min() function.
ii. The first line of the main() function.
iii. The first line of the main() following the line on which max() was invoked.

d. After execution of the function min(), program execution:


i. Stops without returning to main().
ii. Goes back to the main() function.

e. If the values of i and j were to be printed after the function max()


and again after the function min(), what values would be displayed?

Ver. 1.0

Slide 176 of 53

Programming in C
Practice: 5.2 (Contd.)

4. Write a program that calls a function called power(m,n),


which displays the nth power of the integer m (m and n are
parameters). The function must be invoked by a call by
reference.

Ver. 1.0

Slide 177 of 53

Programming in C
Practice: 5.2 (Contd.)

Solution:
1. Yes, because the addresses of the variables are passed in by
using call by reference, the memory locations of the variables
are known to the function. Using pointers to the variables, their
values can be modified.
2. False. Values of variables are copied into the parameters only
in the case of a call by value.
3. a. max()
b. min()
c. iii
d. ii
e. After max() is executed, the values of i and j printed out
would be the same as those entered during execution. After
min() is executed, the value of i would still be the same, but
j would increase by 5 (since b is a pointer to the variable j).
Ver. 1.0

Slide 178 of 53

Programming in C
Practice: 5.2 (Contd.)
4.main() {
int x, y;
printf(Enter Number: );
scanf(%d, &x);
fflush(stdin);
printf(Enter power raise to : );
scanf(%d, &y);
fflush(stdin);
power(&x, &y); }
power(m,n)
int *m, *n; /* power is pointed to by n,
value is pointed to by m */
{ int i=1,val=1;
while(i++<= *n)
val = val ** m;
printf(%d the power of %d is %d\n, *n,*m,
val);}
Ver. 1.0

Slide 179 of 53

Programming in C
Returning Values from a Function

A function can return a value to the caller function.


The return statement is used to send back a value to the
caller function.
The return statement also transfers control back to calling
function.
The default return value is int type.
The return statement can return only one value.
The syntax for the return statement is:
return[expression]

A function can also return an array. This could be done by:


return [array name]

Ver. 1.0

Slide 180 of 53

Programming in C
Practice: 5.3

1. Point out the error(s), if any, in the functions given in the


following file:

2. The following program should calculate the square of any


float value, using a function called square(). The float value
is an input to the program. The program is incomplete. Put
in the appropriate statements in the program given in the
following file:

Ver. 1.0

Slide 181 of 53

Programming in C
Practice: 5.3 (Contd.)

3. The function, makeint(), was coded to convert any


number entered into a char array to integer type. The
function takes the string as parameter and returns the value,
as given in the following file:

Ver. 1.0

Slide 182 of 53

Programming in C
Practice: 5.3 (Contd.)

Solution:

Ver. 1.0

Slide 183 of 53

Programming in C
Command-Line Arguments

Command-line arguments:
Are the parameters that the main() function can receive from
the command line.
Are passed as information from the OS prompt to a program.

The main() function has 2 arguments, argc and argv.


The format of the main() function with parameters is as
follows:
main(argc, argv)
int argc;
char *argv[];
{
:
}

Here, argc is integer and argv is a character array of


unlimited size (hence [ ] in the declaration).
Ver. 1.0

Slide 184 of 53

Programming in C
Practice: 5.4

1. Given that a C program called temp is executed by the


following command:
temp start 6

match the following:


a.
b.
c.
d.

value of argc
argv [0]
argv [1]
argv[2]

1.
2.
3.
4.

points to array "6"


points to arrm/ "start"
3
points to array "temp"

2. Modify the program upper so that it first checks the number


of arguments entered on the command line. The program
should display an error message if no arguments have been
entered and also allow conversion of as many strings to
upper-case as have been specified as arguments on the
command line.
Ver. 1.0

Slide 185 of 53

Programming in C
Practice: 5.4 (Contd.)

3. Consider the following program to calculate the sum of 2


integers specified on the command line:
main (argc, argv)
int argc;
char *argv [ ];{
sum (argv [1], argv [2]);
}
sum (num1, num2)
int numl, num2;{
return numl + num2;
}
The program has some logical errors. Point out the errors and
correct the code.

Ver. 1.0

Slide 186 of 53

Programming in C
Practice: 5.4 (Contd.)

Solution:

Ver. 1.0

Slide 187 of 53

Programming in C
Using Library Functions for String Manipulation

Library functions:
Are also known as built-in functions.
Can be used by including the concerned header files.

Ver. 1.0

Slide 188 of 53

Programming in C
Standard String-Handling Functions

Some of the standard string-handling functions are:


strcmp(): Compares 2 strings (its parameters) character by
character (ASCII comparison).
strcpy(): Copies the second string to the first string named
in the strcpy() parameters.
strcat(): Appends the second string passed at the end of
the first string passed to it .
strlen(): Returns the number of characters in the string
passed to it.

Ver. 1.0

Slide 189 of 53

Programming in C
Practice: 5.5

1. What will the following function call return?


x = strcmp(Cada, CADA);
What should the declaration of x be?

2. Assume that array contains the string 846*.


What will array contain when the following statement is executed?
strcat(array,>);

3. State whether True or False:


The following statement returns a value of 4 to x.
x = strlen ("abc");

Ver. 1.0

Slide 190 of 53

Programming in C
Practice: 5.5 (Contd.)

Solution:
1. Value returned - 32
Declaration - int x;
2. 846*>
3. False

Ver. 1.0

Slide 191 of 53

Programming in C
String to Numeric Conversion Functions

Conversion functions:
Are available as a part of the standard library.
Are used to convert one data type into another.

The following functions are used to convert a string to a


numeric value:
atoi(): Returns the int type value of a string passed to it
and the value 0 in the case the string does not begin with a
digit.
atof(): Returns the double type value of a string passed to it
and the value 0 in the case the string does not begin with a
digit or a decimal point.

Ver. 1.0

Slide 192 of 53

Programming in C
Practice: 5.6

1. What value will the variable val contain in each of the


following situations?
a. val = atoi ("A345"); /* val is int type */
b. val = atof ("345A"); /* val is double type */

Ver. 1.0

Slide 193 of 53

Programming in C
Practice: 5.6 (Contd.)

Solution:
1. a. 0
b. 345.000000

Ver. 1.0

Slide 194 of 53

Programming in C
Functions for Formatting Data in Memory

The formatting functions are available as a part of the


standard library.
The following functions are used to format data in memory:
sprintf():
Writes to a variable in the memory and stores the data in different
variables specified.
Are used for transferring data between variables in a specific
format.
Has the following syntax:
sprintf(string, format-specification, data, .);

sscanf():
Performs formatted input from a string.
Has the following syntax:
sscanf(string, format-specification, data, .);

Ver. 1.0

Slide 195 of 53

Programming in C
Practice: 5.7

1. What data is assigned to the variable string by each of the


following?
a. sprintf(string,"%04d%3.2f%2s",21,4.576, "Hi);
b. sprintf (string, "%10s", "ABC");
c. sscanf ("0987APZ", "%4d%s", &num, string);

2. What is the error, if any, in the instructions given below


against each purpose? Give the correct instruction in case
of an error.

Ver. 1.0

Purpose

Instruction

Accept a name from keyboard

printf(%s, name);

Format the contents of variables


i_num(int) and f_num(float), and store
them into a character array called string.

printf (string,"%d%f, i_num,f_num)

Slide 196 of 53

Programming in C
Practice: 5.7 (Contd.)

Solution:

Ver. 1.0

Slide 197 of 53

Programming in C
Working with Data Storage Types

C language provides the following data storage types:


auto: Variables of this type retain their value only as long as
the function is in the stage of execution.
static: Variables of this type retain its value even after the
function to which it belongs has been executed.
extern: Variables of this type are declared at the start of the
program and can be accessed from any function.

Ver. 1.0

Slide 198 of 53

Programming in C
Practice: 5.8

1. Given the following declarations:


float area;
static float val;
auto char number;
State which variable(s) will be:
a. Created each tune the function is invoked.
b. Created only once.

2. A numeric array has to store 4 values - 2.5, 6,3, 7.0 and 8.0.
This array is to be declared and used in a function called
compute(). Which of the following is/are correct
declarations of this array?
a.
b.
c.
d.
Ver. 1.0

static int values[4] = {2.5,6.3,7.0,8.0};


auto float values[4] = {2.5,6.3,7.0,8.0 };
float values [4]= {2.5,6.3,7.0,8.0};
static float values [4] = {2.5,6.3,7.0,8.0};
Slide 199 of 53

Programming in C
Practice: 5.8 (Contd.)

Solution:
1. a. area, number
b. val
2. (a) Is invalid because the array should be float or double type.
(b) Is invalid because it is declared as auto type.
(c) Is invalid because it is declared as auto type.
(d) Is correct.
.

Ver. 1.0

Slide 200 of 53

Programming in C
Practice: 5.9

1. If the variable val is declared as global in the program B,


just illustrated, how would program A be modified? Give the
appropriate declarations required in both programs.
2. Consider the following 2 program files:
Program A
float x;
calc() {
int i;
: } printout()
{ static char z;
: }

Program B
char numarray[5];
main() {
char c ;
: }
Ver. 1.0

Slide 201 of 53

Programming in C
Practice: 5.9 (Contd.)

Based on this code, answer the following:


a. The variable z can be accessed in the function(s)
____________________.
b. The variable(s) that can be accessed from functions of both program
files is/are
___________.
c. Slate whether True or False:
The variable i can be used in the function printout().
d. Memory for variable z is reserved each time the function printout()
is invoked. State whether true or false.
e. If the function printout() has to access the variable x, does x have
to be declared within the function printout()?
If so, give the declaration.
f. The auto variable(s) in these programs is/are _________________.

Ver. 1.0

Slide 202 of 53

Programming in C
Practice: 5.9 (Contd.)

Solution:
1. In program B, val would be declared as follows:
int val;
calc(){
:}
In program A, the declaration would be as follows:
main()
{ extern int val;
:}

2. a. printout() only (Since it is declared within the function


printout() and hence is not global)
x and numarray (if proper extern statements are coded).
b. False (Since it is declared within the function calc(), and
hence it is not global)

Ver. 1.0

Slide 203 of 53

Programming in C
Practice: 5.9 (Contd.)

c. False (Since z is a static variable, it is created only


once the function printout() is invoked.)
d. No (Since x is declared as global in program A, and
printout() is defined in the same program file. However,
declaring it as extern while within printout() is wrong.)
e. The variable i defined in calc() and the variable c defined
in main().

Ver. 1.0

Slide 204 of 53

Programming in C
Practice: 5.10

1. The following file contains a C program called remdigit.c


and a list of errors in the program indicated by the compiler.
Go through the error list and correct the program. Since the
C compiler does not always give very meaningful error
messages, go through the program given in the following file
carefully.

Ver. 1.0

Slide 205 of 53

Programming in C
Practice: 5.10 (Contd.)

2. Write a program to display all the positions at which a


character occurs in a string. Both the character to be located
and the string to be searched should be passed to a
function called nextpos (findchar, searchstr).
Each time the function locates the diameter, it should pass
back the position.
After searching the entire string, the function should return
the value -1.

Ver. 1.0

Slide 206 of 53

Programming in C
Practice: 5.10 (Contd.)

Solution:
Work out your answers. A discussion on these follows in the
Classroom.

Ver. 1.0

Slide 207 of 53

Programming in C
Summary

In this session, you learned that:


Functions provide advantages of reusability and structuring of
programs.
A parameter of a function is the data that the function must
receive when called or invoked from another function.
Functions that have parameters are invoked in one of the
following two ways:
Call by value
Call by reference

Call by value means that the called function creates its own
copy of the values in different variables.
Call by reference means that the called function should be able
to refer to the variables of the caller function directly, and does
not create its own copy of the values in different variables.

Ver. 1.0

Slide 208 of 53

Programming in C
Summary (Contd.)

Arrays are passed to functions by the call by reference


method.
Functions can return values by using the return statement.
The main() function can have parameters, argc and argv.
argc is integer type while argv is a string.
The information that is passed to a program from the OS
prompt is known as command-line arguments.
Some of the standard string-handling functions are:
strcmp(): Compares two strings.
strcpy(): Copies the second string to the first string.
strcat(): Appends the second string passed at the end of the
first string passed as parameters.
strlen(): Returns the number of characters in the string
passed as a parameter.

Ver. 1.0

Slide 209 of 53

Programming in C
Summary (Contd.)

atoi(): Returns the int type value of a string passed to it.


aof(): Returns the double type value of a string passed to it.

The following functions are used to format data in memory:


sprintf()
sscanf()

C language provides the following data storage types:


auto: Variables of this type retain their value only as long as the
function is in the stage of execution.
static: Variables of this type retain its value even after the
function to which it belongs has been executed.
extern: Variables of this type are declared at the start of the
program and can be accessed from any function.

Ver. 1.0

Slide 210 of 53

Programming in C
Objectives

In this session, you will do the practice questions of Chapter


4 and Chapter 5.

Ver. 1.0

Slide 211 of 53

Programming in C
Chapter 4

1. Modify the program that determines the length of a string


so that it allows input of the string from the user and
displays its length. (Maximum size of the input string is 80).
2. Modify the string comparison program so that it allows
input of strings and reports on whether they are the same
or not.

Ver. 1.0

Slide 212 of 53

Programming in C
Chapter 4 (Contd.)

3. A program can be easily understood if it is indented


properly. This has one drawback, in terms of the size of the
program on the disk. One simple way of cutting down the
size significantly is described here.
Assume the following piece of code:
123456789012345678901234567890 (indicates column)
printf("This is the last straw");
The 15 blanks at the start of the line can be replaced by the
number 15 so that the line of code is now:
123456789012345678901234567890 (indicates column)
15printf("This is the last straw");
Note that a saving of 13 bytes (15 - 2) has been
accomplished at one shot.

Ver. 1.0

Slide 213 of 53

Programming in C
Chapter 4 (Contd.)

Write a program, which takes in a line of code from the user


(maximum length of 80 characters) and prints out the
condensed string (with the number of spaces occupying the
first two characters in the condensed string).

Ver. 1.0

Slide 214 of 53

Programming in C
Chapter 5

1. Alcatel Automatics is a company known for its marketing


success. This success has been largely due to its superb
data analysis programs.
The product manager wants some modifications to the
existing programs. When running the program, he should be
able to specify any of the following with the run command
itself:
%s: for displaying the product sales by each salesman as a
percentage of the total salesman sales.
%p: for displaying the product sales by each salesman as a
percentage of the total product sales.
%i: for displaying the product sales as an index of total sales of
all products

Ver. 1.0

Slide 215 of 53

Programming in C
Chapter 5 (Contd.)

He should also be shown some help message to assist him


in case he forgets what to specify with the command and
should then be able to give the command again.
Since the calculations will be coded in separate functions,
which are stored together in one file called func.c,
separate from the main() function. The function available
in this file are:
intdat(): Displays the data as an index of total sales.
proddata(): Displays the data as a percentage of total
product sales.
calcprodtot(): Calculates the salesman-wise totals.

Ver. 1.0

Slide 216 of 53

Programming in C
Chapter 5 (Contd.)

The contents of func.c are as follows:

Ver. 1.0

Slide 217 of 53

Programming in C
Objectives

In this session, you will learn to:


Read and write contents in a file
Use random access in files

Ver. 1.0

Slide 218 of 53

Programming in C
Reading and Writing Contents in a File

File inputs-outputs is similar to input from/to the terminal.


Files are treated as streams of characters.
Function are available for single character as well as
multiple character input-output from/to files.

Ver. 1.0

Slide 219 of 53

Programming in C
Opening Files

A file needs to be opened to read or to write contents in it.


The fopen() function is used to open a file.
The fopen() function returns a pointer of the FILE type
data.
The fopen() function opens a file in a specific access
mode.
The various modes in which a file can be opened are:
r - Read-Only Mode
w - Write-Only Mode
a - Append Mode
r+ - Read + Write Mode
w+ - Write + Read Mode
a+ - Read + Append Mode

Ver. 1.0

Slide 220 of 53

Programming in C
FILE Type Pointers

The FILE type pointer is:


Returned when a file is opened by using the fopen()
function.
Used to manipulate a file.
Used to check whether a file has opened successfully.

The stdin, stdout, and stderr FILE pointers refer to


the standard input device (keyboard) and standard output
and error device (VDU).

Ver. 1.0

Slide 221 of 53

Programming in C
The exit() Function

The exit() Function:


Is used to terminate a program execution.
Is used as shown in the following code snippet:
if (argc ! = 3)
{
print (invalid arguments \n);
exit ();
}

Ver. 1.0

Slide 222 of 53

Programming in C
Character Input-Output with Files

The functions used for character input-output with files are:


fgetc(): Reads one character at a time from a file, assigns it
to a character variable, and moves the file pointer to the next
character. It returns an integer type of value.
fputc(): Writes one character at a time in a file.

Ver. 1.0

Slide 223 of 53

Programming in C
Closing Files

The fclose() function is used to close files.


Closing the file release the resources.
The syntax of the fclose() function is:
fclose (ptr1);
Where ptr1 is a FILE pointer.

Ver. 1.0

Slide 224 of 53

Programming in C
Practice: 6.1

1. What does the following code do?


while((c = fgetc (fp)) != EOF) {
if ((c >= a) && (c <= z))
c -= 32;
fputc(c, stdout); }

2. Write a program called append, which appends the contents


of the first file to the second file specified on the command
line. The program should also terminate in the following
situations:
a. 2 arguments are not specified on the command line. In this
case, the following message must be displayed:
Usage: append file1 file2

b. In case the file to be read cannot be opened, the following


message may be displayed:
Cannot open input file
Ver. 1.0

Slide 225 of 53

Programming in C
Practice: 6.1 (Contd.)

Solution:

Ver. 1.0

Slide 226 of 53

Programming in C
Practice: 6.2

1. Point out the errors in the following code:


a. /* this program creates the file emp.dat */
main() {
FILE point;
fopen(w, emp.dat);
:
fclose(emp.dat);
}
b. /* this program reads the file emp.dat */
main() {
#include<stdio.h>
file*ptr;
ptr = fopen(emp.dat);
:
ptr= fclose();
}
Ver. 1.0

Slide 227 of 53

Programming in C
Practice: 6.2 (Contd.)

2. Given the following statements of a C program:


fopen(man.txt, r);
fclose(fileptr);

What will the FILE declaration statement of this program


be?
3. Point out the error(s) in the following code:
#include<stdio.h>
main() {
char emp;
FILE *pointer1;
pointer1= fopen(man1.txt,w);
while((inp = fgetc(pointer1)) != eof) {
printf(?%c, inp);
} }
Ver. 1.0

Slide 228 of 53

Programming in C
Practice: 6.2 (Contd.)

4. The copy command of DOS copies the contents of the first


file named on the command line to the second file. Make
appropriate changes to the file-copy program so that it
works identical to the copy command.

Ver. 1.0

Slide 229 of 53

Programming in C
Practice: 6.2 (Contd.)

Solution:

Ver. 1.0

Slide 230 of 53

Programming in C
Line Input and Output with Files

The functions used for line input and output with files are:
fgets():
Is used to read number of specified characters from a stream.
Reads number of characters specified 1 characters.
Has the following syntax:
fgets(str, 181, ptr1);
Str Character array for storing the string
181 Length of the string to be read
ptr1- FILE pointer

fputs():
Is used to output number of specified characters to a stream.
Has the following syntax:
fputs(str, ptr1);
Str Character array to be written
ptr1- FILE pointer

Ver. 1.0

Slide 231 of 53

Programming in C
Practice: 6.3

1. State whether True or False:


Files created using the fputs() function will always have
records of equal length.
2. Consider the following C statement to input a record from a
file called number-list:
fgets (line, MAXLEN, file_ind);

Given that MAXLEN is a #define and that all lines in the file
number-list are 25 characters long what will the declaration
statements for the parameters of fgets() be?
3. Assume that the file number_list contains the following
records:
120
1305

Ver. 1.0

Slide 232 of 53

Programming in C
Practice: 6.3 (Contd.)

Given that the file has been opened and the first input
statement executed is as follows:
fgets(line, 3, file_ind);

Which of the following will the array called line contain?


a. 1 followed by \0.
b. 12 followed by \0.
c. 120 followed by \0.

4. Match the following functions with the values they can


return:
a. fgets() 1. NULL
b. fgetc() 2. EOF
c. fopen() 3. FILE type pointer

Ver. 1.0

Slide 233 of 53

Programming in C
Practice: 6.3 (Contd.)

If a function can return more than one type of these values,


state the conditions under which the values are returned.
5. A utility called hprint has to be written in C, which will
allow a user to display, on screen, any number of lines from
the beginning of any file. The user has to specify both the
number of lines and the file name on the command line in
the following format:
hprint number file-name

The maximum line length is 80 characters. The program


should handle possible errors.

Ver. 1.0

Slide 234 of 53

Programming in C
Practice: 6.3 (Contd.)

Solution:
1. False. fputs() writes the contents of a string onto a file. So
even if a string has size 100, but contains only 20 characters
before a \0, only 20 characters get written.
2. The declarations are:
#define MAXLEN 26/* macro definition outside
main() */
char line[26];
3. b. fgets() will read either 3 - 1 characters , i.e. 2 characters,
or until it comes across a newline character. Since the newline
occurs after the third character, it will read in 2 characters from
the first record.

Ver. 1.0

Slide 235 of 53

Programming in C
Practice: 6.3 (Contd.)

4. a. 1
b. 2
c. 1 and 3. (NULL in case file cannot be opened; FILE type
pointer in case of successful open)
5. The answer to this practice will be discussed in class. Work
out your solution.

Ver. 1.0

Slide 236 of 53

Programming in C
Formatted Input and Output with Files

The functions for formatted input and output with files are:
fscanf():
Scans and formats input from a stream.
Is similar to scanf().
Has the following syntax:
int fscanf(FILE *Stream, const char
*format[,address,..]);

fprintf():
Sends formatted output to a stream.
Is similar to printf().
Has the following syntax:
int fprintf(FILE *Stream, const char
*format[,address,..]);

Ver. 1.0

Slide 237 of 53

Programming in C
Practice: 6.4

1. Rewrite the following printf() statement using the


function fprintf():
printf(The test value is %d, x);

2. The following statement is written to input 2 fields from the


keyboard:
scanf( %6s%d, array, &num);

It is rewritten as:
fscanf(%6s%d, array, &num);

This statement is erroneous. Give the correct fscanf()


statement.

Ver. 1.0

Slide 238 of 53

Programming in C
Practice: 6.4 (Contd.)

3. Write the appropriate statements to input fields from a


record of a file called alpha-doc, the first field being a
float value, and the second field a string of size 10. In
case the file does not have he required data, and the endof-file occurs, the following message should be displayed:
End of file encountered.

Ver. 1.0

Slide 239 of 53

Programming in C
Practice: 6.4 (Contd.)

4. A utility called format is required to create a formatted report


from a file called manufact. This report is also to be stored
on disk with suitable report headings. The name of the file to
be created should be accepted during program execution.
The program should also ask for a report title, which should
appear after every 60 record of the file manufact.
The file manufact contains the following 3 fields separated
by space.
Field
Manufacturer Code
Name
Address

Size
4
20
60

In the output file, the fields should be separated by one tab


character.
Ver. 1.0

Slide 240 of 53

Programming in C
Practice: 6.4 (Contd.)

Solution:

Ver. 1.0

Slide 241 of 53

Programming in C
Using Random Access in Files

A file can be accessed using sequential access or random


access.
In sequential access, the file is always accessed from the
beginning.
In random access the file can be accessed arbitrarily from
any position.

Ver. 1.0

Slide 242 of 53

Programming in C
The fseek () Function

The fseek() function:


Is used for repositioning the current position on a file opened
by the fopen() function.
Has the following syntax:
rtn = fseek (file-pointer, offset, from-where);

Here:
int rtn is the value returned by fseek()(0 if successful and 1 if
unsuccessful).
file-pointer is the pointer to the file.
offset is the number of bytes that the current position will shift on a
file.
from-where is the position on the file from where the offset would be
effective.

Ver. 1.0

Slide 243 of 53

Programming in C
The rewind () Function

The rewind() function:


Is used to reposition the current position to the beginning of a
file.
Is useful for reinitializing the current position on a file.
Has the following syntax:
rewind(file-pointer);

Here:
file-pointer is the pointer returned by the function fopen().
After rewind() is executed, current position is always 1,
i.e. beginning of file.

Ver. 1.0

Slide 244 of 53

Programming in C
Practice: 6.5

1. Write the equivalent of the function rewind() using


fseek().
2. Assume the following representation of the first 30 bytes of
a file.

1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0

Ver. 1.0

Slide 245 of 53

Programming in C
Practice: 6.5 (Contd.)

What will the current position on the file be after the


following instructions are performed in sequence?
a.
b.
c.
d.
e.

Ver. 1.0

fp = fopen ("FOR DEMO.DAT", r);


fseek(fp, 29L, 1);
rewind(fp);
fgets(buffer, 20L, fp);
fseek(fp, 4L, 1);

Slide 246 of 53

Programming in C
Practice: 6.5 (Contd.)

Solution:
1. fseek(fp, 0L, 0);
2. The following current positions are relative to the beginning of
the file:
a.
b.
c.
d.
e.

Ver. 1.0

1
30
1
20
24

Slide 247 of 53

Programming in C
Practice: 6.6

1. Write a function to update the field balance in the file


SAVINGS.DAT based on the following information.
If balance is
< Rs 2000.00
Between Rs. 2000.00
and Rs 5000.00
<Rs 5000.00

Increment balance by
Rs 150.50
Rs 200.00

Rs 300.40

The structure of the file SAVINGS.DAT is as follows.


Account number
Account holder's name
(5 bytes)
(20 bytes)
(5 bytes)

Ver. 1.0

Balance

Slide 248 of 53

Programming in C
Practice: 6.6 (Contd.)

Solution:

Ver. 1.0

Slide 249 of 53

Programming in C
Practice: 6.7

1. Go through the following program called inpcopy.c and its


error listing on compilation and then correct the program:
1
#include <stdio.h>
2
main()
3
{
4
file fp;
5
char c;
6
7
fp = fopen(file, w);
8
9
while (( c = fgetc(stdin)) != EOF)
10
fputc(c,fp);
11
12
fclose(fp);
13 }

Ver. 1.0

Slide 250 of 53

Programming in C
Practice: 6.7 (Contd.)

Error listing:

"inpcopy/.c", line 4: file undefined


"inpcopy/.c". line 4: syntax error
"inpcopy/.c", line 7: fp undefined
"inpcopy/.c", line 7: w undefined
"inpcopy/.c", line 7: learning: illegal
pointer/integer combination, op = "inpcopy/.c",
line 9: c undefined

Ver. 1.0

Slide 251 of 53

Programming in C
Practice: 6.7 (Contd.)

Solution:
1. Work out for your answer. The solution will be discussed in the
classroom session.

Ver. 1.0

Slide 252 of 53

Programming in C
Summary

In this session, you learned that:


C treats file input-output in much the same way as input-output
from/to the terminal.
A file needs to be opened to read or to write contents in it.
The fopen() function is used to open a file.
C allows a number of modes in which a file can be opened.
When a file is opened by using the fopen() function, it
returns a pointer that has to be stored in a FILE type pointer.
This FILE type pointer is used to manipulate a file.
The exit() function is used to terminate program execution.
The fgetc() and fputc() functions are used for character
input-output in files.
After completing the I/O operations on the file, it should be
closed to releases the resources.

Ver. 1.0

Slide 253 of 53

Programming in C
Summary (Contd.)

The fclose() function is used to close a file.


The fgets() and fputs() functions are used for string
input-output in files.
The fscanf() and fprintf() functions are used for
formatted input-output in files.
In sequential access, the file is always accessed from the
beginning.
In random access the file can be accessed arbitrarily from any
position.
C provides the fseek() function for random access.
The function rewind() is used to reposition the current
position to the beginning of a file.

Ver. 1.0

Slide 254 of 53

Programming in C
Objectives

In this session, you will learn to:


Work with structures
Use structures in file handling

Ver. 1.0

Slide 255 of 53

Programming in C
Working with Structures

Structures:
Are collection of heterogeneous data types.
Are also known as records.
Are used to define new data types.
Are defined using the struct keyword.

Ver. 1.0

Slide 256 of 53

Programming in C
Defining Structures

A structure is defined by using the struct keyword.


Consider the following example:
struct {
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of_sale;
}
salesrec;
All the variables in the record are treated as one data structure
salesrec.

Ver. 1.0

Slide 257 of 53

Programming in C
Practice: 7.1

1. State whether True or False:


The members of a structure must be of the same data type.

2. a. Give the declaration for a structure called date with the


following members.
day (2 digits)
month (2 digits)
year (4 digits)

b. Give appropriate statements to accept values into the


members of the structure date and then print out the
date as mm/dd/yyyy.

Ver. 1.0

Slide 258 of 53

Programming in C
Practice: 7.1 (Contd.)

Solution:
1. False
2. a. The structure declaration should be:
struct {
int day;
int month;
int year;
} date;

b. The statements could be:


scanf(%d%d%d, &date, &date.month, &date.year);
printf(%d/%d/5d, date.month, date.day,
date.year);

Ver. 1.0

Slide 259 of 53

Programming in C
Defining Structures (Contd.)

Defining a label structures:


Structure label may be declared as:
struct salesdata {
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of-sale;
};
struct salesdata salesrec;

Here, salesdata is the label and salesrec is the data item.

Ver. 1.0

Slide 260 of 53

Programming in C
Practice: 7.2

Given the following declarations:


struct date_type{
struct {
int day;
int month;
int year;
};
}

int day;
int month;
int year;
date;

Declaration 1
Declaration 2
Answer the following questions:
1. Memory is allocated for the structure (date_type/ date).
2. Which of the following is/are the correct way(s) of referring to
the variable day?
a. day.date
b. date_type.day

Ver. 1.0

Slide 261 of 53

Programming in C
Practice: 7.2 (Contd.)

3. What change(s) should be made to the first declaration so that


the structure date is created of type date_type?

4. Is the following statement valid in case of the second


declaration? If not, why?
struct date another_date;

Ver. 1.0

Slide 262 of 53

Programming in C
Practice: 7.2 (Contd.)

Solution:
1. date (date_type is only a structure type)
2. a. Invalid because the structure name precedes the variable
name.
b. Invalid because date_type is not actually created in
memory, it is only a label.
3. The following statement should be added after the struct
declaration:
struct date_type date;

4. This is invalid because date is not a structure type but an


actual structure in memory.

Ver. 1.0

Slide 263 of 53

Programming in C
Passing Structures to Functions

Passing Structures to Functions:


Structures may be passed to functions either by value or by
reference.
Usually methods pass the address of the structure.
The name of the variable being referenced is preceded by the
symbol .

Ver. 1.0

Slide 264 of 53

Programming in C
Practice: 7.3

1. Consider the following code:


struct date_type
{
int day;
int month;
int year;
}; struct date_type date,

*ptr;

a. How can the pointer variable ptr be assigned the address of


the structure date?
b. Is the following statement valid?
ptr = &date_type;
c. Give alternative ways of referring to:
i. &date.day
ii. date.month
Given that ptr has been assigned the address of the structure
date.
Ver. 1.0

Slide 265 of 53

Programming in C
Practice: 7.3 (Contd.)

2. Consider the incomplete code of a program that is given in


the following file. The code uses a function called
printmonth() that displays the month name
corresponding to any month number. The month number is
accepted into the member month of the structure date. The
blanks have to be filled in appropriately.

Ver. 1.0

Slide 266 of 53

Programming in C
Practice: 7.3 (Contd.)

Solution:
1. a. By using the following statement:
ptr = &date;

b. No. because date_type is not created in memory; it is


only a label.
c. i. &(ptr-> date)
ii. ptr-> month
2. The statement to invoke printmonth() could be:
printmonth(&date); /*invoke printmonth() by
passing structure */
The missing lines in the code for printmonth() are:
printmonth(point)
struct date_type *point;
point is the parameter of the function since it is used within
the function to access members of the structure date.
Ver. 1.0

Slide 267 of 53

Programming in C
Arrays of Structures

Arrays of structures can also be created.


It works in the same way as any other data type array.
Consider the following example:
struct prod data{
char prodname[8];
int no_of_sales;
float tot_sale;
};
An array for the preceding structure can be declared as:
struct proddata prod_field[4];

The elements of the structure can be accessed as:


prod_field [0].prodnam[0];

Ver. 1.0

Slide 268 of 53

Programming in C
Practice: 7.4

1. Declare a structure which will contain the following data for


3 employees:
Employee code
First name
Middle initial
Last name

(3 characters)
(20 characters)
(1 character)
(20 characters)

The employee codes to be stored in this structure are E01,


E02, and E03.
2. Write the code to input for all 3 employees, and print out the
initials of each (e.g. Ashraf A Kumar would be printed as
AAK) along with their codes.

Ver. 1.0

Slide 269 of 53

Programming in C
Practice: 7.4 (Contd.)

Solution:

Ver. 1.0

Slide 270 of 53

Programming in C
Working with Structures (Contd.)

A structure can be used as a valid data type within another


structure. For example, if date has been defined as:
struct
int
int
int
};

date{
dd;
mm;
yy;

The date structure can be used in another structure as:


struct trans_rec{
char transno[4];
char type;
float amount;
struct date tran_date;
};
Ver. 1.0

Slide 271 of 53

Programming in C
Practice: 7.5

1. What will the following declaration do?


typedef char sentence[50];
sentence complex[10];

Ver. 1.0

Slide 272 of 53

Programming in C
Practice: 7.5 (Contd.)

Solution:
1. The first statement defines sentence as a data type consisting
of an array of 50 characters. The second statement declares
complex as a two-dimensional array, (an array of ten arrays of
50 characters each).

Ver. 1.0

Slide 273 of 53

Programming in C
Using Structures in File Handling

To store data permanently, it needs to be stored in a file.


Mostly, the data, to be written in the file, is a logical group of
information i.e. records.
These records can be stored in structure variables. Hence,
you need to write structures onto a file.

Ver. 1.0

Slide 274 of 53

Programming in C
Writing Records onto a File Using Structures

The fwrite() function is used to write structures onto a


file.
The fwrite() function has the following syntax:
fwrite (constant pointer, sizeof (datatype), 1,
FILE pointer);

The first parameter is a pointer to the data to be written.


The second parameter is the size of data to be written.
The third parameter is the number of objects or data to be
written.
The fourth parameter is the pointer to file.

Ver. 1.0

Slide 275 of 53

Programming in C
Practice: 7.6

Now that various assets of the transaction data entry


program have been explained, these have to be
consolidated and the entire program coded. The problem
statement is repeated below.
A transaction data entry program called dataent, used at
the familiar Alcatel Automatics Company, has to be coded.
The transaction file stores the data on transactions made by
the salesmen of the company. The records consist of the
following fields.
Transaction number
Salesman number
Product number (numbered 1 to 4)
Units sold
Value of sale
Value of sale is calculated in the program.
Ver. 1.0

Slide 276 of 53

Programming in C
Practice: 7.6 (Contd.)
The program should allow the user to indicate when he
wants to stop data entry (i.e. it should keep accepting
records until the user indicates that there are no more
records).
After all records have been entered, a report on the total
number of sales and the total sale value for each product is
to be printed in the following format (for each product).
Product number
Product name
Total number of sales
Total sale value

: ___________________
: ___________________
: ___________________
: ___________________

Use the structures salesrec, salesdata, prodata, and


prod_field defined earlier and code for the report printing
within main(). Also use the code provided on page 7.2 and
7.3 in your solution.
Ver. 1.0

Slide 277 of 53

Programming in C
Practice: 7.6 (Contd.)
Solution:

Ver. 1.0

Slide 278 of 53

Programming in C
Reading Records from Files Using Structures

The fread() function is used to read data from a stream.


The fread() function has the following syntax:
fread (ptr, sizeof, 1, fp);

The first parameter is a pointer to the variable where the data


is to be fetched.
The second parameter is the size of data to be read.
The third parameter is the number of objects or data to be
read.
The fourth parameter is the pointer to file.

Ver. 1.0

Slide 279 of 53

Programming in C
Practice: 7.7

1. Is the following statement to read the first 5 records of the


file trans.dat valid?
fread (ptr, (sizeof(salesrec) *5), 1, fp);

If not state why and give the correct statement. No checks


are to be done for an unsuccessful read.
2. Modify the above fread() statement to include an end-offile check and also check whether the records have been
read successfully. In case of end-of-file, display the
message:
End-of-file encountered

and in case of other errors, display the message and exit:


Unsuccessful read

In case of a successful read, display the salesman number


and transaction number of each record. Give all the
structure declarations required.
Ver. 1.0

Slide 280 of 53

Programming in C
Practice: 7.7 (Contd.)

Solution:

Ver. 1.0

Slide 281 of 53

Programming in C
Practice: 7.8

1. Debug the following program called dat.c using the error


listing provided in the following file.

Ver. 1.0

Slide 282 of 53

Programming in C
Practice: 7.8 (Contd.)

Solution:
1. The solution to this practice will be discussed in class. Work
out your answer.

Ver. 1.0

Slide 283 of 53

Programming in C
Summary

In this session, you learned that:


Records can be defined in C by using structures.
Structure members can be of the same/different data type.
Memory is not reserved when a structure label is declared. A
structure is created when it is declared as a struct of the
same type as the structure label.
A member of a structure can be accessed as follows:
structure-name.member-name

A pointer to a structure can be used to pass a structure to a


function. Using pointers, the structure members are accessed
as follows:
pointer-name->member-name

Arrays of structures can be defined and initialized (if global or


static). To access any member, an index has to be used after
the structure name, as follows:
structure-name [index ].member-name
Ver. 1.0

Slide 284 of 53

Programming in C
Summary (Contd.)

The typedef statement can assign names to user-defined


data types. These are treated the same way as data types
provided by C.
The fread() function can read records from a file into a
structure/array of structures. The format of the function is:
fread (pointer, size of structure, number of
objects to be read, file pointer);

The fread() function returns the number of objects read from


the file. It does not return any special value in case of
end-of-file. The feof() function is used in conjunction with
fread() to check for end-of-file.
The fwrite() function can write a structure array of
structures onto a file. All numeric data is written in compressed
form. Usually, fread() and fwrite() are used in
conjunction.

Ver. 1.0

Slide 285 of 53

Programming in C
Objectives

In this session, you will learn to:


Differentiate between high-level and low-level input/output
Work with low-level input/output functions
Use random access in files

Ver. 1.0

Slide 286 of 53

Programming in C
Differentiating Between High-Level and Low-Level Input/Output

In C, files and devices can be accessed by using two groups


of functions:
High-level I/O or stream-level I/O
Low-level I/O

Ver. 1.0

Slide 287 of 53

Programming in C
Difference Between High-level I/O and Low-level I/O

High-level or Stream-level I/O:


Is more flexible and convenient.
Hides complexity from the programmer.
Is slower.

Low-level I/O:
Provides direct access to files and devices.
Is complex (buffer management is to be done by the
programmer).
Is faster.
Uses a file descriptor to track the status of the file.

Ver. 1.0

Slide 288 of 53

Programming in C
Practice: 8.1

Which of the following statements is true?


In C, there are many interfaces between a program and
peripheral devices.
A file descriptor is a non-negative integer.
When you perform an operation on a file, the system uses the
name of the file to identify it.

Ver. 1.0

Slide 289 of 53

Programming in C
Practice: 8.1 (Contd.)

Solution:
A file descriptor is a non-negative integer.

Ver. 1.0

Slide 290 of 53

Programming in C
Uses of Low-Level Input/Output

Low-level I/O functions are used for:


Accessing files and devices directly.
Reading binary files in large chunks.
Performing I/O operations quickly and efficiently.

Ver. 1.0

Slide 291 of 53

Programming in C
Working with Low-Level Input/Output Functions

The low-level I/O system in C provides functions that can be


used to access files and devices.
The basic low-level I/O functions are:
open()
close()
read()
write()

Ver. 1.0

Slide 292 of 53

Programming in C
The open() Function

The open() function:


Is used to open an existing file or create a new file.
Returns a file descriptor for the file name passed to it.
Has the following syntax:
int open(char *filename, int flags, int perms
);

Ver. 1.0

Slide 293 of 53

Programming in C
The close() Function

The close() function:


Closes the file that was opened using the open() function.
Takes the file descriptor as a parameter to close the file.
Returns 0 on success and -1 in case of an error.
Has the following syntax:
int close(int filedes);

Ver. 1.0

Slide 294 of 53

Programming in C
The read() function

The read() function:


Reads data from a file.
Starts reading a file from the current file position.
Has the following syntax:
int read (int filedes, char *buffer, int
size);

Ver. 1.0

Slide 295 of 53

Programming in C
The write() function

The write() function:


Enables a user to write contents to a file.
Has the following syntax:
int write (int filedes, char *buffer, int
size);

Ver. 1.0

Slide 296 of 53

Programming in C
Practice: 8.2

1. Which of the following statements is true?


a. At end-of-file, if a function is called repeatedly, it will give error.
b. In a read() function, the value of zero indicates end-of-file.

2. What will happen if you do not call the write() function in


a loop?

Ver. 1.0

Slide 297 of 53

Programming in C
Practice: 8.2 (Contd.)

Solution:
1. In a read() function, the value of zero indicates end-of-file.
2. If you do not call write() function in a loop then the entire
data would not be written.

Ver. 1.0

Slide 298 of 53

Programming in C
Error Handling

Error Handling:
Some of the low-level I/O functions return error flags when
they fail to perform a specified task.
You can find these types of errors using a variable, errno.
The following table lists some values of errno that are
common to the open(), close(), read(), and write()
functions.
errno values

Ver. 1.0

Description

EACCES

Specifies that the program has failed to access one of the directories
in the file.

ENAMETOOLONG

Indicates that the file name is too long.

ENOSPC

Specifies that the disc is out of space and the file can not be created.

EIO

Specifies that there was a hardware error.

EBADF

Specifies that the file descriptor passed to read, write, or close the file
is invalid.

Slide 299 of 53

Programming in C
Error Handling (Contd.)

There are certain errno values that are specific to the


open() function, which are shown with the help of the
following table.
errno values

Ver. 1.0

Description

EEXIST

Specifies that if File already exists, and O_CREAT and O_EXCL are
set, then opening the file would conflict with the existing file and the
file will not open.

EISDIR

Specifies that the file is actually a directory.

ENOENT

Specifies that some of the file components do not exist.

EMFILE

Specifies that too many files are open.

EROFS

Specifies that the file is on a read only systembut either one of the
write permissions O_WRONLY, O_RDWR, or O_TRUNC is set.

Slide 300 of 53

Programming in C
Error Handling (Contd.)

There are certain errno values that are specific to the


write() function, which are shown with the help of the
following table.
errno values

Ver. 1.0

Description

EFBIG

Specifies that the file will become too large if the


data is written on it.

EINTR

Specifies that the write operation is temporarily


interrupted.

Slide 301 of 53

Programming in C
Using Random Access Seek in Files

The read and write operations on files are usually sequential


in nature.
Random access permits non-sequential file access so that a
file can be read or written out of sequence.
Random access in low-level file routines is performed using
the lseek() function.

Ver. 1.0

Slide 302 of 53

Programming in C
The lseek() Function

The lseek() function:


Returns the file position, as measured in bytes from the
beginning of the file.
Has the following syntax:
long lseek (int filedes, long offset, int
origin);

Ver. 1.0

Slide 303 of 53

Programming in C
The lseek() Function (Contd.)

The following table lists the various values of the third


parameter (origin).
Values for origin

Ver. 1.0

Description

SEEK_SET or 0

Specifies that the offset is relative to the beginning


of the file. The offset can only be positive.

SEEK_CUR or 1

Specifies that the offset is relative to the current


position. The offset can be positive or negative.

SEEK_END or 2

Specifies that the offset is relative to the end of


the file. The offset can be positive or negative.

Slide 304 of 53

Programming in C
The lseek() Function (Contd.)

The following table lists some instructions for moving to the


end or beginning of a file.

Ver. 1.0

Instruction

Function used

To get to the end of a file

lseek(filedes,0,2);

To return to the beginning of a file

lseek(filedes,0,0);

Slide 305 of 53

Programming in C
Summary

In this session, you learned that:


In C, files and devices can be accessed by using high-level I/O
or stream-level I/O and low-level I/O.
Low-level I/O functions are those, which provide direct access
to files and peripheral devices.
A file descriptor is a non-negative integer, which is returned by
the open() function and is used in read() and write()
functions. It tells about the permission to access the file.
Low-level input/output functions are used for the following
purposes:
Accessing files and devices directly
Reading the binary files in large chunks
Performing I/O operations quickly and efficiently

The open() function is used to open or create a file.

Ver. 1.0

Slide 306 of 53

Programming in C
Summary (Contd.)

The close() function is used for closing the file.


The read() function reads the existing file up to specified size
and stores it into a character array.
The write() function writes on the file taking input from a
character array up to specified size.
Most of the low-level I/O functions throw errors during file
handling.
errno is the variable that tells about the error occurred during
a low-level I/O operation.
Files and devices can also be accessed randomly.
The lseek() function is used to place the file position to the
desired place.
The lseek() function do not require to read or write the file
for positioning it.

Ver. 1.0

Slide 307 of 53

Programming in C
Practice Questions

In this session, you will do the practice questions of Chapter


7 and Chapter 8.

Ver. 1.0

Slide 308 of 53

Programming in C
Chapter 7

1. You are a part of a database software development team.


The software you are developing is to be used to create
and query on database files. You are assigned the task of
writing a C program, which displays the structure of any
database file, as given in the following file.

Ver. 1.0

Slide 309 of 53

Programming in C
Chapter 8

1. Read a file after the first 10 characters and print it on


screen. (Hint: Create a text file by the name of
Example.txt and write 2-3 lines of content in it.)
2. Write your name 10 character after the end of the file. Also,
use the exit() function to terminate the execution, if you
are unable to write or open the file.

Ver. 1.0

Slide 310 of 53

You might also like