Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

C-Programming Part1 Upto Fucntions

Uploaded by

ravi.sjsgrd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

C-Programming Part1 Upto Fucntions

Uploaded by

ravi.sjsgrd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 261

“Advanced C Programming”

DSSD - August’15
Outline
Day1

1. Introduction to Linux & C


2. Data Types & Operators in C

Day2

3. Control Statements
4. Functions

Day3

5. Data Input & Output


6. Arrays
7. Multidimensional Arrays
Outline
Day 4

8. Introduction to pointers
9. Arrays & Pointers
10.Pointers with Functions

Day5

11.Strings
12.Structures, Unions & Bit-fields

Day6

13.File I/O
14.Preprocessor
Outline

Day 7

15. Code Optimization


16. C and Assembly

Day8

17. Secure Coding practices


Day 1

1. Introduction to Linux & C


2. Data Types & Operators in C
1. Introduction to Linux & C
Introduction to Linux - Outline

 What is Unix?

 What is Linux?

 Linux Distributions

 Linux File System

 Shell and Basic Commands

 vim (vi improved) Editor (vi – visual interactive)


What is Unix?
 Initially, Named as “UNiplexed Information Computing System
(UNICS)”

 Changed the name to “UNIX”

 Developed in 1969 at AT&T‟s Bell Labs by


 Ken Thompson - UNIX

 Dennis Ritchie - C Language

 Douglas Mcllroy - Pipes

 A multi-tasking and multi-user Operating System


 You can have many users logged into a system simultaneously, each
running many programs.

 00:00:00 Hours, Jan 1, 1970 is time zero for UNIX. It is also called as
epoch.
Reference: http://en.wikipedia.org/wiki/History_of_Unix
UNIX

Ken Thompson (Sitting) and Dennis


Ritchie (Standing) working together at
a PDP-11

Ken Thompson and Dennis Ritchie

Reference: http://en.wikipedia.org/wiki/History_of_Unix
What is Linux?
 A clone of UNIX, Developed in 1991 by Linus Torvalds, a
Finnish graduate student (It was his personal project)

 Inspired by and replacement of “Minix (Mini Unix by


Tanenbaum for education)”

 Linus + Minix  Linux

 First kernel (v1.0) was released in 1994 (Under GNU general


public license)

 Consist of

 Linux Kernel

 GNU (GNU is Not Unix) Software

 Software Package management & Others


Linux is everywhere
 Originally developed for X86-32
Bit

 Internet was built around UNIX

 Android & MAC OS are


developed based on Linux
kernel

 Ported to other architectures.

 IBM PowerPC

 Mobile Phones -Nokia


N810, Google Nexus
(Ubuntu), etc.

 Routers, GPS

 Robo
Linux is everywhere
Check www.top500.org to know the power of Linux (June-2015 List)
Why Linux is everywhere?
 Open, Free or Cheap

 Scalable and Portable


 Scalable – In terms of processor count, Number of users, Memory size,
I/O, Resource management etc..

 Portable – It can work efficiently on anything from wristwatch to World‟s


fastest Supercomputer

 Multiuser and multitasking

 Robust – A cluster or a Server can run for years without


rebooting  Reliable
Linux Distributions
 600+ Linux Distributions
 RHEL (Commercial Support)

 Fedora (Free, Majorly used for Desktop)

 Ubuntu (Free, Majorly used for Desktop, From South Africa)

 Slackware (One of the oldest, simple and stable)

 CentOS (free RHEL, From England)

 SuSe (Free and Commercial, From Germany)

 Knoppix (first LiveCD distribution)


Which Linux Distribution…?
 Depends on user requirements
1. Slackware

2. Ubuntu

3. Fedora

4. RHEL

5. CentOS
UNIX/Linux Structure
Linux File System
Details of File System

/  root directory
/boot  files for booting system
/etc  configuration files
/bin  important system binaries
/sbin  contains system admin programs(super user)
/usr  user applications
/lib  dynamic libraries
/home  user home directories
/root  super user home dir
/var  contains variable data constantly generated when
system is running
/dev  device files
Files, Directories and Inodes
 File: A file represents a sequence of bytes.
 Each file will have a name

 Special characters are allowed but need to be used carefully

 Directory: A directory represents a list of files.


 A directory is also a file which contains the list of files containing in it.

 Every directory and file will be listed in its parent directory

 Inode: An inode (Index Node) contains information about a


file (metadata) – File permissions, UID, GID, Size, Time
Stamp etc.
 The information about all the files will be maintained in a table called
“Inode Table”
Users and Groups
 Users: Users can be either people or accounts which exist to use
specific applications of Linux.

 Each user will be given a unique user ID (UID).

 A root user will also be present and he has all the administrave
privileges.

 Groups: Users can be tied together into groups for a common


purpose.

 Example: climate, ssdh, acts

 Each group is associated with a group ID (GID).


Access Permissions
 File Permissions: There are 3 permissions for any file  r, w, x.

1. Read (r) - Indicates that a given category of user can read a file.

2. Write (w) - Indicates that a given category of user can write to a file.

3. Execute (x)- Indicates that a given category of user can execute the file.

 Directory permissions:

1. Read (r) - The direcotry can be read.

2. Write (w) - The directory can be updated, renamed or deleted.

3. Execute (x)- Operations can be perfomred on the files of the directories. This
bit is also called as search bit, it indicates whether you are permitted to
search files under that directory

 Categories of users: All of these three permissions are assigned to three


categories of users – User (U), Group(G), Others(O)
Access Permissions…
File Types
What is Linux Shell?

 The kernel sits on top of the hardware and is the core of the OS; it
receives tasks from the shell and performs them
 The shell is the command line interface through which the user interacts
with the OS. Most commonly used shell is “bash”
 Linux has a kernel and one or more shells – bash, csh, ksh etc.
 When you login to the system the default shell will be given to the user.
Bash is the default shell for Linux (We can change the default shell)
 GUI of Linux is in fact an application program works on the shell.
Shell commands
 Shell Command - A command is a program which interacts with the
kernel to provide the environment and perform the functions called by the
user.

 A command can be: a built-in shell command; an executable shell file,


known as a shell script; or a source compiled, object code file.

 Examples: ls, mkdir, pwd, cd

 Command Structure:

$ command <options> <arguments>

 Multiple commands can be executed one by one using a single line by


separating them with semicolon.

$ ls; mkdir my_dir; ls


Shell Programming
 Shell Script - A series of commands can be written into a text file and
execute that file. This is called as shell script.

 The first line of a shell script must be “#!/bin/Shell-Name”

 In order to execute a shell script we need to give execute permission (x)


to that file using “chmod” comand.

chmod +x users.sh

 Example:

#!/bin/bash

date

who

ps -ax
How to explore?
Man pages

 Manpage
 $ man ls

 $ man 2 mkdir

 $ man man

 $ man -k mkdir

 $manpath

 $ env | grep MANPATH

 /etc/man.config
How to explore…?
Man page sections

1. User-level commands and apps - /bin/mkdir

2. System calls - int mkdir(const char *, …);

3. Library calls - int printf(const char *, …);

4. Device drivers and network protocols - /dev/tty

5. Standard file formats - /etc/hosts

6. Games and demos - /usr/games/fortune

7. Misc. files and docs - man 7 locale

8. System admin. commands - /sbin/reboot


Shell commands

1. File management

2. System information

3. Process and Job management

4. Network

5. Searching

6. System start and stop

7. Compression and decompression

8. Miscellaneous
Shell commands…
1. File management

ls - directory listing

ls -al - formatted listing with hidden files

cd dir - change directory to dir

cd - change to home

pwd - show current directory

mkdir dir - create a directory dir

rm file - delete file

rm -r dir - delete directory dir

rm -f file - force remove file

rm -rf dir - force remove directory dir *

cp file1 file2 - copy file1 to file2

cp -r dir1 dir2 - copy dir1 to dir2; create dir2 if it doesn't exist


Shell commands…
1. File management …

mv file1 file2 - rename or move file1 to file2. If file2 is an


existing dir, moves file1 into directory file2

ln -s file link - create symbolic link link to file

touch file - create or update file

cat > file - places standard input into file

more file - output the contents of file

head file - output the first 10 lines of file

tail file - output the last 10 lines of file

tail -f file - output the contents of file as it grows, starting


with the last 10 lines
Shell commands…
1. File management …

The single most useful command…….

$ man man

Who am I?

$ whoami

Where am I?

$ cd

$ pwd
Shell commands…
1. File management …

What is here?

$ ls

That’s all? Or still more files??

$ ls -a

A file or a directory?

$ ls -F

Want to see the details of all the files/dirs?

$ ls -l
Shell commands…
1. File management …

Want to go to a different directory?

$ cd path_of_dest_dir

Want to go to your parent dir?

$ cd ..

Want to jump into your hom?

$ cd

Want to go to root of entire machine?

$ cd /
Shell commands…
1. File management …

Want to create a new directory?

$ mkdir dir_name

Want to create a directory tree (In the current directory)?

$ mkdir –p dssd/c/day1/linux

Want to copy the contents of one file to another file?

$ cp file1 file2

Want to copy a directory to another directory?

$ cp –r dir1 dir2
Shell commands…
1. File management …

chmod octal file – change the permissions of file to octal, which


can be found separately for user, group, and
world by adding:

● 4 – read (r)

● 2 – write (w)

● 1 – execute (x)

Examples:

chmod 777 – read, write, execute for all

chmod 755 – rwx for owner, rx for group and world

For more options, see man chmod.


Shell commands…
2. System Information

date – Show the current date and time

cal – Show this month's calendar

uptime – Show current uptime

w – Display who is online

whoami – Who you are logged in as

finger user – Display information about user

uname -a – Show kernel information

cat /proc/cpuinfo – CPU information

cat /proc/meminfo – Memory information

df – Show disk usage

du – Show directory space usage

free – Show memory and swap usage


Shell commands…
3. Process and Job management

ps – Display your currently active processes


top – Display all running processes
kill pid – Kill process id pid
killall proc – Kill all processes named proc (use with extreme caution)
bg – Lists stopped or background jobs; resume a stopped job
in the background
fg – Brings the most recent job to foreground
fg n – Brings job n to the foreground
Shell commands…
4. Network commands

ifconfig – List IP addresses for all devices on the local machine


ping host – Ping host and output results
whois domain – Get whois information for domain
dig domain – Get DNS information for domain
dig -x host – Reverse lookup host
wget file – Download file
wget -c file – Continue a stopped download
Shell commands…
5. Searching

grep pattern files – Search for pattern in files


grep -r pattern dir – Search recursively for pattern in dir
command | grep pattern – Search for pattern in the output
of command
locate file – Find all instances of file
find / -name filename – Starting with the root directory, look for
the file called filename
locate filename – Find a file called filename

which filename – Show the subdirectory containing the


executable file called filename
grep TextStringToFind /dir – Starting with the directory called dir,
look for and list all files containing TextStringToFind
Shell commands…
6. System stop and start

shutdown -h now – Shutdown the system now and do not reboot


shutdown -r 5 – Shutdown the system in 5 minutes and reboot
shutdown -r now – Shutdown the system now and reboot
reboot – Stop all processes and then reboot - same as
above
Shell commands…
7. Compression and uncompression

tar cf file.tar files – Create a tar named file.tar containing files


tar xf file.tar – Extract the files from file.tar

tar czf file.tar.gz files – Create a tar with Gzip compression


tar xzf file.tar.gz – Extract a tar using Gzip

tar cjf file.tar.bz2 – Create a tar with Bzip2 compression


tar xjf file.tar.bz2 – Extract a tar using Bzip2

gzip file – Compresses file and renames it to file.gz


gzip -d file.gz – Decompresses file.gz back to file
Shell commands…
8. Miscellaneous

adduser accountname – Create a new user call accountname


passwd accountname – Give accountname a new password
su – Log in as superuser from current login
exit – Stop being superuser and revert to
normal user
How to connect to Linux system?
Quiz - 1
1. List the hidden files in the current directory.
2. Search for a string “DSSD” in a file “dssd.cpp”.
3. Display disk usage statistics in GBs.
4. Display top ten largest files in a given directory.
5. Which command is used to change the file permissions of a file?
6. What is vim?
Overview of C
 C is a general-purpose, procedural, computer programming language
developed in between 1969 and 1973 by Dennis M. Ritchie at the Bell
Telephone Laboratories to develop the UNIX operating system

 UNIX OS, C compiler have been written in C

 C standards
 1989 - ANSI C (C89)

 1990 - C90 (Same as C89, but approved by ISO)

 1999 - C99 Latest


 2011 - C11 (Approved in Dec-2011)

 New features in C11 – Type generic macros, Anonymous structures,


Atomic operations, Bounds-Checked functions etc.

Reference: http://en.wikipedia.org/wiki/C_(programming_language)
Applications of “C”
 Operating Systems
Applications developed using C
 Language Compilers • Google Chrome, Firefox browsers
 Assemblers • Unix/Linux
 Text Editors • MySQL

 Device Drivers • MS Office


• Mozilla Thunderbird (Mail client)
 Modern Programs
• Winamp
 Databases
• VC++ Compiler
 Lang. Interpreters
• JVM
 Utilities
• And many more……
 Libraries

Most widely used & popular system programming Language


Start Working with C

Requirements:

 Editor: vi (or) vim (or) gedit

 Compiler: gcc or icc

 OS: Linux

 Run Time Environment

 Syntax of C
Components of a C Program

Preprocessor #include <stdio.h>

Functions int main()


{
Comments /*My first program in C */

Variables int i,j ; Semicolon

Statements printf("Hello, World! \n");

i=2;
Expressions j=i+5;

return 0;
Whitespaces }
Compilation Phases
Compilation Phases
Compiling and running C programs
How to compile and run if my project has hundreds of
source files?
Make – Utility program
 make: “make” is a utility that automatically builds executable programs
and libraries from source code

 Alternative for make: IDEs (Integrated Development Environment) will do


that automatically for you

 We use GNU make utility

 “make” automatically determines which pieces of a large program need


to be compiled, and issues commands to compile them.

 You need a file called “makefile” to tell “make” what to do

Reference: http://www.gnu.org/software/make/manual/make.html
Simple makefile
 make finds the target prog1 and sees that it

depends on the object files 1.o, 2.o, 3.o


prog1 : 1.o 2.o 3.o
 make next looks to see if any of the three object
cc -o prog1 1.o 2.o 3.o
files are listed as targets. They are so, make looks
1.o : 1.c
at each target to see what it depends
cc -c 1.c
on. make sees that 1.o depends on the files 1.c .
2.o : 2.c
 Now make looks to see if either of these files are
cc -c 2.c
listed as targets and since they aren't it executes
3.o : 3.c
the commands given in 1.o's rule and cc -c 3.c
compiles 1.c to get the object file.
clean :
 make looks at the targets 2.o and 3.o and rm 1.o 2.o 3.o
compiles these object files in a similar fashion.

 make now has all the object files required to

make prog1 and does so by executing the

commands in its rule.


Day 1

1. Introduction to Linux & C


2. Data Types in C & Operators in C
2. (a) Data types
C Language Character Set
 C is a language, hence it requires characters to build its building
blocks.
 Every character has its own ASCII Value
 C character Set contains:
 The uppercase letters A to Z
 The lowercase letters a to z
 The digits 0 to 9
 Certain special characters
Character Set – ASCII Values

ASCII - American Standard Code for Information Interchange

Total – 128 Characters


Printable Characters – 95
Non-printable Control characters - 33
Basics
 Tokens: Individual unit of C program is called as Tokens

 Variable declarations: int i; float f;

 Initialization: char c=’A’; int x=y=10;

 Operators: +,−,∗,/,% and many more….

 Expressions: int x,y,z; x=y∗2+z∗3;

 Functions: int factorial (int n); /∗function takes int , returns int ∗/
Variables
 A variable is a name for a location in memory

 A variable must be declared by specifying the variable's name and the type of
information that it will hold

 Variable should be declared before we use it

data type variable name

int total;
int count, temp, result;

Multiple variables can be created in one declaration


Variable Initialization

 A variable can be given an initial value in the declaration

int sum = 0;
int base = 32, max = 149;

 When a variable is referenced in a program, its current value is used


Variable Assignment

 An assignment statement changes the value of a variable


 The assignment operator is the = sign

total = 55;

 The expression on the right is evaluated and the result is


stored in the variable on the left

• The value that was in total is overwritten


• You can only assign a value to a variable that is consistent
with the variable's declared type
Assignment Through a Function

 y = f(x);

Q = sin(30);

 The assignment operator is still the = sign


Assignment Through scanf()

int variable;

scanf(“%d”, &variable);

 <keyboardinput> 30

 There is not assignment operator in this case


Variables in Memory
Binary Numbers

 Once information is digitized, it is represented and stored in


memory using the binary number system

 A single binary digit (0 or 1) is called a bit

 Devices that store and move information are cheaper and


more reliable if they have to represent only two states

 A single bit can represent two possible states, like a light bulb
that is either on (1) or off (0)

 Permutations of bits are used to store values


Bit Permutations

1 bit 2 bits 3 bits 4 bits


0 00 000 0000 1000
1 01 001 0001 1001
10 010 0010 1010
11 011 0011 1011
100 0100 1100
101 0101 1101
110 0110 1110
111 0111 1111

Each additional bit doubles the number of possible permutations


Bit Permutations

 Each permutation can represent a particular item

 There are 2N permutations of N bits

 Therefore, N bits are needed to represent 2N unique items

1 bit ? 21 = 2 items
How many 2 bits ? 22 = 4 items
items can be 3 bits ? 23 = 8 items
represented by
4 bits ? 4
2 = 16 items
5 bits ? 25 = 32 items
Relationship Between a Byte and a Bit
What is the value of this binary
number?
00101100

0 0 1 0 1 1 0 0

0*27 + 0*26 + 1*25 + 0*24 + 1*23 + 1*22 + 0*21 + 0*20

0*128 + 0*64 + 1*32 + 0*16 + 1*8 + 1*4 + 0*2 + 0*1

0*128 + 0*64 + 1*32 + 0*16 + 1*8 + 1*4 + 0*2 + 0*1

32+ 8 + 4 = 44 (in decimal)


What is the maximum number that can be stored in one
byte (8 bits)?
What is the max.num. that can be stored in one byte (8 bits)?

11111111

1 1 1 1 1 1 1 1

1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20

1*128 + 1*64 + 1*32 + 1*16 + 1*8 + 1*4 + 1*2 + 1*1

128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 (in decimal)

Another way is: 1*28 – 1 = 256 – 1 = 255


What would happen if we try to add 1 to the largest number that
can be stored in one byte (8 bits)?

1 1 1 1 1 1 1 1
+
1
-------------------------------

1 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0
Analogy with car odometers
Analogy with car odometers

[http://www.hyperocity.com/volvo240/images/Volvo/odometerrepair/speedo999999.jpg]
Variables…

Variable Naming Rules:


 Variable names can contain letters, digits and _;
 First character must be a letter
 Variable names should start with letters.
 Keywords (e.g., for, while, do, if, switch etc.) cannot be used as
variable names and are reserved
 Variable names are case sensitive.
Example: int x, X;  x and X are two different variables
Variable Definition & Declaration
Variable Definition: A variable definition means to tell the compiler where and
how much to create the storage for the variable.
Examples:
int i, j, k;
char ch;

Variable Declaration: A variable declaration provides assurance to the compiler


that there is one variable existing with the given type and name so that
compiler proceed for further compilation without needing complete detail about the
variable.
Example:
extern int dssd;  Declaration
int main()
{
int dssd;  Definition
Keywords in C

 Total keywords - 32
 Additional C99 key words (Total -5):
 inline – For writing inline functions (Discuss in functions)
 _imaginary – To declare imaginary values (iy)
 _complex – To declare complex variables (a+ib)
 _Bool – To declare a Boolean type variable (stdbool.h)
 restrict – To declare restricted pointers
Quiz 2

int money$owed; Incorrect

int total_count; Correct

int score2 ; Correct

int 2ndscore; Incorrect

int long; Incorrect

_Bool x; Correct (B must be capital letter or “bool”)


Data Types
 Data type of an object determines:
 Type of values it can have
 Type of operations that can be performed on it

 Data Types:
 Basic data types  int, char, float, double
 Enumerated data types  enum
 Void data type  void
 Derived data types  Arrays, Pointers,
Structures and Unions
Sizes of Basic data types
Type Size Value Range
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 or 4 -32,768 to 32,767 (or)
-2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 0 to 65,535 (or)
0 to 4,294,967,295
Short 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295
Computer Memory

9278
Main memory is divided
9279 into many memory
9280 locations (or cells)
9281
9282
9283 Each memory cell has a
9284 numeric address, which
9285 uniquely identifies it
9286
Storing Information

9278 Each memory cell stores a


9279 10011010 set number of bits (usually
8 bits, or one byte)
9280
9281
Large values are
9282
stored in consecutive
9283 memory locations
9284
9285
9286
Storing a char

9278
char (8 bits = 1 byte)
9279
9280
9281
9282
9283
9284
9285
9286
Storing a short

9278
9279 short (16 bits = 2 bytes)
9280
9281
9282
9283
9284
9285
9286
Storing an int

9278
9279
9280 int (32 bits = 4 bytes)
9281
9282
9283
9284
9285
9286
Storing a long

9278
9279
9280
9281
9282 long (64 bits = 8 bytes)
9283
9284
9285
9286
Storing a float

9278
9279
9280 float (32 bits = 4 bytes)
9281
9282
9283
9284
9285
9286
Storing a double

9278
9279
9280
9281
9282 double (64 bits = 8 bytes)
9283
9284
9285
9286
The sizeof() operator

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])


{
printf("Size of char = %d \n", sizeof(char));
printf("Size of short = %d \n", sizeof(short));
printf("Size of int = %d \n", sizeof(int));
printf("Size of long = %d \n", sizeof(long));
printf("Size of long long = %d \n", sizeof(long long));

printf("Size of float = %d \n", sizeof(float));


printf("Size of double = %d \n", sizeof(double));
printf("Size of long double = %d \n", sizeof(long double));

system("PAUSE");
return 0;
}
Void Data Type
o The type specifier void indicates that no value is available.
o It is an empty data type
o It can be used in the following situations
o Function returns as void
A function with no return value has the return type as void.
Example: void exit (int status);
o Function arguments as void
A function with no parameter can accept as a void.
Example: int rand(void);
o Pointers to void
A pointer of type “void *” represents the address of an object, but not its type. For
example a memory allocation function
Example: void *malloc( size_t size );
It returns a pointer to void which can be casted to any data type.
Symbolic constants for sizes of basic data types
Type Conversions
 Type conversion: It is a way to convert a variable/constant from one
data type to another data type. There are two types:
a) Implicit type conversion
b) Explicit Type conversion
 a) Implicit type conversion: Implicit type conversion, also known
as coercion, is an automatic type conversion by the compiler.

#include <stdio.h>
main()
{
int i = 10; Output: 107.0
char c = „a'; /* ascii value is 97 */
float sum;

sum = i + c;

printf("Value of sum : %f\n", sum );


}
Type Conversions
 b) Explicit type conversion: Converting the data type of a
variable/operand/expression from one data type to another data type
explicitly by the programmer using type cast operator.
 Syntax:
(type_name) expression

#include <stdio.h>

main()
{
int sum = 14, count = 4; Output: 3.5
double mean;

mean = (double) sum / count;

printf("Value of mean : %f\n", mean );


}
<ctype.h>
Type Modifiers
 The modifiers define the amount of storage allocated to the variable.
 short
 long
 signed
 unsigned
 Rule:
 short int <= int <= long int float <= double <= long double
 Syntax:
 short int x;
 long int x;
 unsigned int x;
 unsigned long int x
Type Modifiers…
int main()
{
printf("sizeof(char) == %d\n", sizeof(char));
printf("sizeof(short) == %d\n", sizeof(short));
printf("sizeof(int) == %d\n", sizeof(int));
printf("sizeof(long) == %d\n", sizeof(long));
printf("sizeof(float) == %d\n", sizeof(float));
printf("sizeof(double) == %d\n", sizeof(double));
printf("sizeof(long double) == %d\n", sizeof(long double));
printf("sizeof(long long) == %d\n", sizeof(long long));
return 0;
}

Output: Machine dependent (1, 2, 4, 8, 4, 8, 16, 8)


Type Qualifiers
 A type qualifier is used to refine the declaration of a variable, a
function, and parameters, by specifying whether:
 The value of a variable can be changed.
 The value of a variable must always be read from memory rather than from a
register.

 The standard qualifiers are:


 const: Tells that the variable value can not change after initialisation.
 volatile: Declares a data type that can have its value changed in ways
outside the control or detection of the compiler.
 prevent the compiler from applying any optimizations on objects that can change in ways
that cannot be determined by the compiler.
 values can be changed by code outside the scope of current code at any time.
 The system always reads the current value of a volatile object from the memory location
rather than keeping its value in temporary register
Type Qualifiers
 volatile:
 The possible situations where a volatile variable can change in such a way
that a compiler cannot predict:
 Global variables modified by an interrupt service routine outside the scope
 Global variables within a multi-threaded application – MPI, Shared Memory etc

 If we do not use volatile, the following problems may arise:


 Code may not work as expected when optimization is turned on.
 Code may not work as expected when interrupts are enabled and used.

 Examples:
 const int x=14;
 volatile int a=10;
Constants
 Values can‟t be modified once defined, Also called literals
 Can be of any of other data type
 Integer constants eg: 1234
 Long constant eg: 123456L
 Unsigned constant: eg: 241Ul, 241UL
 Floating point eg: 123.4 or 1e-2
 Character eg: „0‟ (equal to integer val 48)
 Enumerated eg: enum boolean { NO, YES };

 Function can be called with constant as an argument indicating function


will not alter its value
 Syntax:
 const data_type variable_name;
 const data_type *variable_name;  Explained in pointers chapter
 const char mesg[ ]=“ hello world”;  Explained in Strings Chapter
 int strlen( const char[ ] ) (Passing array‟s base address as const, so function should
not change the values of this array)
Escape Sequences
 Combination of characters
comprising of backslash
followed by a character

 backslash causes an
"escape" from the normal
way characters are
interpreted by the
compiler
Quiz 3
1. What is the difference between the declaration and the definition of a
variable?

2. What are maximum and minimum values that can be stored in the char data
type?  -128 to 127

3. Is there any Boolean data type in C? What data types can be used instead of
the Boolean type in C?  char and int

4. What does keyword „void' denote? When is the keyword „void' generally used
in C code?

5. The format identifier „%i‟ is also used for _____ data type?
Quiz 3…
1. What is the output of the below program?

#include <stdio.h>
#define a 10
int main()
{
const int a = 5;
printf("a = %d\n", a);
}

Compilation error
Session 1

1. Introduction to Linux & C


2. Data Types in C & Operators in C
2. (b) Operators
Operators, operands and expressions
• Operators are symbols which take one or more operands or expressions
and perform arithmetic or logical computations.
Examples: +, -, *, /, =, ==
• An "operand" is an entity on which an operator acts.
Example: a+b-5  a, b and 5 are operands
• An "expression" is a sequence of operators and operands that performs
any combination of these actions:
o Computes a value
o Designates an object or function
o Generates side effects
Example: a + (b / 6.0)
Types of Operators
• Operators are classified in two ways

1. Based on Type of Operation 2. Based on number of operands


Precedence and
Order of Evaluation
Bitwise Operations

 What is Memory?

 Collection of Bits

 In real life applications, some times it is necessary to deal with


memory bit by bit

 For example,

 Gaming and Puzzles (Ex: Sudoku)

 Controlling attached devices (Ex: Printers)

 Obtaining status

 Checking buffer overflows…

 Note: The combination of bit level operators and the pointers can
replace the assembly code. For example, only 10% of UNIX is
written using assembly code and the rest is in C.
Bitwise Operations in Integers
There are six operators

 & – AND  ~ – Complement


 Result is 1 if both  Each bit is reversed
operand bits are 1
 | – OR  << – Shift left
 Result is 1 if either  Multiply by 2
operand bit is 1
 ^ – Exclusive OR  >> – Shift right
 Result is 1 if  Divide by 2
operand bits are
different

Restrictions: We can use these operators only on int and char data
typed variables - Signed and unsigned char, short, int, long, long long
Bitwise Operations in Integers…
Examples - &, |, ^ and ~
unsigned short int a,b;
unsigned short int c;

a = 0xb786 1 0 1 1 0 1 1 1 1 0 0 0 0 1 1 0

b = 0xb420 1 0 1 1 0 1 0 0 0 0 1 0 0 0 0 0

c = a&b = 0xb400 1 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0

c = a|b = 0xb765 1 0 1 1 0 1 1 1 1 0 1 0 0 1 1 0

c = a^b = 0x0365 0 0 0 0 0 0 1 1 1 0 1 0 0 1 1 0

c = ~a = 0x4879 0 1 0 0 1 0 0 0 0 1 1 1 1 0 0 1
Example - Left Shift (<<)

unsigned short int a = 0xb786;


A << = 3;

Before shift 1 0 1 1 0 1 1 1 1 0 0 0 0 1 1 0
a= 0xb786

After shift 1 0 1 1 1 1 0 0 0 0 1 1 0 0 0 0
a= 0x9a30

Last three bits are


filled with zeroes
Example - Right Shift (<<)

unsigned short int a = 0xb786;


A << = 3;

Before shift 1 0 1 1 0 1 1 1 1 0 0 0 0 1 1 0
a= 0xb786

After shift 0 0 0 1 0 1 1 0 1 1 1 1 0 0 0 0
a= 0x16f0

First three bits are


filled with zeroes
Quiz 4

1. What do you mean by Binary Operators?


2. What is an unary operator?
3. If x=10 and y=2, what is the value of -x * y++ ?
4. What happens when a floating point value is assigned to an integer variable?
5. If an integer 200 is assigned to a floating point variable, what will be the
result?
Quiz 4
1. What is the output of this code?

#include <stdio.h>
int main()
{
int x = 1, y = 0, z = 5;
int a = x && y || z++;
printf("%d", a); return 0;
}

(a) Syntax Error


(b) 6
(c) 1
(d) 5

Answers: C (z++=5, 0 || 5 = 1)
Quiz 4…
2. What is the output of this code?

#include <stdio.h>
int main()
{
int x = 1, y = 0, z = 3;
x > y ? printf("%d", z) : return z;
}

Syntax Error

Correct Statement:
return(x > y ? printf("%d", z) : z)
Quiz 4…
3. What is the output of this code?

#include <stdio.h>
void main()
{
int x = 0, y = 2, z = 3;
int a = x & y | z;
printf("%d", a);
}

(a) Syntax Error


(b) 6
(c) 3
(d) 0

Answers: c ( 0 & 2 | 3 = 00 & 10 | 11 = 10 | 11 = 11 = 3 (LR)


Quiz 4
4. What is the output of this code?

#include <stdio.h>
void main()
{ (a) Syntax Error
(b) -1 1
int i = -3;
(c) 1 -1
int k = 3 (d) 1 0

int j = i % 2; Answers: b
int m = k % -2;
printf("%d %d", j, m);
}
Quiz 4
5. What is the output of this code?

#include <stdio.h>
void main()
{ (a) 3
(b) 24
int x = 5 * 9 / 3 + 9;
(c) 60
} (d) None

Answers: b
Class Room Work

1. Write a program that asks the user to enter two numbers, obtain the two
numbers from the user and prints the sum, product, difference, quotient and
remainder of the two numbers.
2. Write a program to convert a positive integer (2 digits) to binary.
Day 2

3. Control Statements
4. Functions
Control Statements
• Definition: The control-flow of a language specify the order in which
computations are performed.
• Types:
• Decision Making (Branching)
o if else statement, if..else..if.. Statement (Multi-way decision making)
o Nested if statement
o Switch statement
• Loops
o For Loop
o While Loop
o Do while Loop
if..else
• Definition: The if-else statement is used to express decisions.
• The else part is optional.

Syntax:

If (expression)
set of statements;
else
set of statements;

Example :

If(a>b)
print( “ a is greater\n);
else
print(“ b is greater\n”);
if..else
Example : Write a C program to print the number entered by user
only if the number entered is negative.

#include <stdio.h>
int main()
{
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);

if(num<0)
{ /* checking whether number is less than 0 or not. */
printf("Number = %d\n",num);
}
else
printf("The if statement in C programming is easy.");
return 0;
}
If..else..if..
• Multi Way decision making: If any expression is true, the corresponding
statement is executes and chain terminates
• Last “else” part handles “none of the above”

Syntax: Example :

If (expression) If(a>b)
statement 1; print( “ a is greater\n);
else if (expression) else if (b>a)
statement 2; print(“ b is greater\n”);
else if (expression) else
statement 3; printf(“ a & b are equal”);
else
statement 4;
Nested if
• Nested if: You can use one if or else if statement inside
another if or else if statement(s).

Syntax: Example :

If (expression) if( a == 100 )


statement 1; {
if (expression) if( b == 200 )
statement 2; {
else printf("Value of a is 100\n””;
statement 4; printf(“Value of b is 200\n" );
}
else
printf("Value of a is 100\n”);
}
Class Room Work

1. Write a program to find out the smallest and the largest of three integers
using
(a) Only if
(b) Only if else
(c) Nested if
Switch
• Definition: The switch statement is a multi-way decision that tests
whether an expression matches one of a number of constant integer
values, and branches accordingly.

Syntax:

Switch(expression)
{
case const-expr :
statements;
break;
case const-expr :
statements;
break;
……………
……………
default :
statements;
}
Switch - Rules
Rules:

 The expression used in a switch statement must have an integral or


enumerated type.

 When the variable being switched on is equal to a case, the statements


following that case will execute until a break statement is reached.

 Break statement terminates the switch.

 You can have any number of case statements within a switch.

 A switch statement can have an optional default case. We should have


only one default case.

 Default case can be kept any where in the switch.

 Not every case needs to contain a break.


Switch – rules..
Rules:

 Case label must be unique.

 Empty Switch case is allowed.

 Case label must be a constant or constant expression

 Case label must be an integer or character, cannot be float

 Two or more cases can share a single break.

 Nesting of switch statements is allowed.

 Macro Identifier (Symbolic constant) is allowed as Switch Case Label.


Switch – Example1
Example1: /* Simple Calculator – Add, Sub, Mul, Div */

# include <stdio.h>
int main()
{
char op;
float num1, num2;

printf("Select an operator either + or - or * or / \n");


scanf("%c",&o);

printf("Enter two operands: ");


scanf("%f%f",&num1,&num2);

switch(op)
{
case '+':
printf("%f + %f = %f",num1, num2, num1+num2);
break;
Switch – Example1…
Example1: /* Simple Calculator – Add, Sub, Mul, Div */

case '-':
printf("%f - %f = %f",num1, num2, num1-num2);
break;
case '*':
printf("%f * %f = %f",num1, num2, num1*num2);
break;
case '/':
printf("%f / %f = %f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message */
printf("Error! operator is not correct");
break;
}
return 0;
}
Switch…Example2
Example2: /* count digits, white case ' ':
space, others */ case '\n':
case '\t':
#include <stdio.h> nwhite++;
main() break;
{ default:
int c, i, nwhite, nother,ndigit[10]; nother++;
nwhite = nother = 0; break;
for (i = 0; i < 10; i++) }
ndigit[i] = 0; }
while ((c = getchar()) != EOF) printf("digits =");
{ for (i = 0; i < 10; i++)
switch (c) { printf(" %d", ndigit[i]);
case '0': case '1': case '2': case '3': printf(", white space = %d,
case '4': other = %d\n", nwhite,
case '5': case '6': case '7': case '8': nother);
case '9': return 0;
ndigit[c-'0']++; }
break;
If else .vs. Switch
• The functioning of if-else and switch is more or less same

If..else switch
If else .vs. Switch
• In another form:

If..else…if… switch
If else .vs. Switch
else if Ladder Switch
In else if ladder, the control goes In case of switch case, as per the
through the every else if statement value of the switch, the control jumps
until it finds true value of the statement to the corresponding case.
or it comes to the end of the else if
ladder.
Less compact, Not readable More compact than lot of nested else
if. More readable.

Less efficient (slow), if the size of the More efficient (Fast) – Jump Table or
ladder is big Branch Table

(Because compiler generates a jump


table for a switch during compilation.
Consequently, during execution,
instead of checking which case is
satisfied, it only decides which case
has to be executed.)
Can use float expressions Cannot use float expressions
If else .vs. Switch
Class Room Work

1. Write logical expressions that tests whether a given character is


• lower case letter
• upper case letter
• digit
• white space (includes space, tab,new line)
Use Switch statement.
Loops – for loop
• A for loop is a repetition control structure that allows you to write a loop that
needs to execute a specific number of times.

Syntax:

for (expr1; expr2 ; expr 3)


{
statement(s);
}
For loop - Example
Example: /* Print Floid Triangle */
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
printf("Enter the number of rows of Floyd's triangle to print\n");
scanf("%d", &n);

for (i = 1; i <= n; i++)


{
for (c = 1; c <= i; c++)
{
printf("%d ",a);
a++;
}
printf("\n");
}
return 0;
}
While loop
• A while loop is a repetition control structure that allows you to execute a block
of statements as long as a given condition is true.
• When we do not know the number of iterations in advance.

Syntax:

while (expression)
{
statement(s);
}
while loop - Example
Example: /* Print Floid Triangle */
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
printf("Enter the number of rows of Floyd's triangle to print\n");
scanf("%d", &n);

while (expr)
{

--Class Room Exercise--


< Write the code >

}
return 0;
}
do..While loop
• A do-while loop executes a block of statements at least once.
• The remaining behavior is same as while loop.

Syntax:

do
{
statement(s);
} while(expression)
do..while loop - Example
Example: /* Reverse a number */
#include <stdio.h>

main()
{
int val, r_digit;
printf("Enter the number to be reversed.\n");
scanf("%d", &val);

do {
r_digit = val % 10;
printf("%d", r_digit);
val = val / 10;
} while( val != 0 );

printf("\n");
}
break
• A break statement is used for early exit from a loop.
• It can be used to terminate a case in the switch statement
• If you are using nested loops then the break statement will stop the execution
of the innermost loop and start executing the next line of code after the block.
Syntax: break;

while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
continue
• A continue statement executes the next iteration of the loop, skipping the
remaining code in a block.
Syntax: continue;

int a = 1;
do
{
if( a == 3)
{
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 6 ); Output : 1 2 4 5
goto
• A goto statement causes an unconditional jump from the goto to a labeled
statement in the same function.
• Used to break the loops that are deeply nested, break works for only for a
single level of loop
• Deprecated – Not recommended to use

Syntax:
goto label;
…..
Label : statement;
goto - Example
Example:
#include <stdio.h>
int main ()
{
int a = 10;
LOOP: do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
Quiz 5
1. How can you make the loops to run infinite number of time ?

2. How do you come out of infinite loops?

3. What is the limitation of break? How to overcome it?

4. What is the difference between do loop and do-while loop?


Class Room Work

1. Write a program to print the multiplication table of a given number (upto 10)
using for loop.
2. Write a program to find the number of digits in a given integer number. Use
While loop or Do While loop.
Class Room Work
Solution: /* Multiplication Table */

/* C program to find multiplication table up to 10. */

#include <stdio.h>
int main()
{
int n, i;
printf("Enter an integer to find multiplication table: ");
scanf("%d",&n);

for(i=1;i<=10;++i)
{
printf("%d * %d = %d\n", n, i, n*i);
}
return 0;
}
Class Room Work
Solution: /* Number of digits */

#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
n/=10; /* n=n/10 */
++count;
}
printf("Number of digits: %d",count);
}
Day 2

3. Control Statements
4. Functions
Functions
• Definition: A function is a self-
contained program segment that Input
carries out some specific, well-
defined task.
• Every C program consists of one or
more functions. Function -
Computations
• Function should be declared or
prototyped before it is being used
anywhere
• One of these functions must be
Output
called “main” * (conditions apply)
• Function will carry out its intended
action whenever it is called.
Defining a Function

• Function Definition: A function definition has two principal components:


o the first line - Return type, Function Name, Parameters or Arguments
o the body of the function
• Every C program consists of one or more functions.

Syntax:

return_type function_name( parameter list )


{
body of the function
}
Function Prototypes
• Function Declaration: A function declaration tells the compiler about a
function name and how to call the function.
• Parameter names are not compulsory, but data types must be mentioned.

Syntax:
return_type function_name( parameter list );

• Function Call: To use a function, you will have to call that function to perform
the defined task.
• When a program calls a function, program control is transferred to the called
function.
• A called function performs defined task and when its return statement is
executed
Function prototypes…

Function prototype at the beginning of C code:


• describe what the function returns and what it takes as input
• Prototype should be followed by semicolon
• Parameter list is optional
• Default return type is integer

Example:
double max( double param1, double param2)

{
if (param1 > param2)
{
Examples: return param1; }
else
{
float sqrt( float );
return param2;
}
int maximium( int , int ); }
Return type of a C Function
• Every C function must specify the type of data being generated by the
function.
• If the function does not generate any data, its return type can be “void”.
• The type of expression returned must match the type of the function, or
be capable of being converted, otherwise we can see undefined
behaviour.

Example:
void print_happy_birthday( int age )
{
printf("Congratulations on your %d th Birthday\n", age);
return;
}
Functions - Example
Example:
#include <stdio.h>
long int facrorial( int );  Function prototype
int main()
{ Actual Argument
int n; long int fact;
fact = factorial( n );  Function Call
printf(“Factorial of %d is %ld”, n, fact);
return 0;
} Formal Argument
long int factorial( int n ) /* calculate the factorial of n */
{
int i;
long int prod = 1;
if (n > 1)
for (i = 2; i <= n; ++i)
prod *= i;
return(prod);
}
Function Parameters
 Parameters are the symbolic name for "data" that are passed to a function
 Formal Arguments - Called function
 Actual Arguments - Calling function
 Two ways that arguments can be passed to a function:
 Call by value
o Copy of data is sent to the function being called
o Doesn‟t affect the original data
 Call by Reference
o Reference to the data is sent
o Reference parameter "refers" to the original data in the calling function.
o Changes affect the original data

void swap(int x, int y) void swap( int *x, int *y)

// call by value //call by reference


Swap(x,y); Swap( &x, &y);
Function Parameters…
Function Parameters - Rules
• The number of arguments in a function call must be the same as the number of
parameters in the function definition. This number can be zero.
• The max no. of arguments is 253 for a single function. (Machine dependent)
• If a function is called with arguments of the wrong type, the presence of a
prototype means that the actual argument is converted to the type of the
formal argument „as if by assignment‟. If prototype is not present then it may
give garbage values or undefined behaviour.
• In the old style, parameters that are not explicitly declared are assigned a
default type of int.
• The scope of function parameters is the function itself. Therefore, parameters
of the same name in different functions are unrelated.
Functions - Rules
• Function Declaration: A function declaration tells the compiler about a
function name and how to call the function.
• C program can have one or more functions.
• Any function can be called from any function
• A function can be called any number of times.
• A function can call itself.
• A function cannot be defined in another function.

Size of a function
Functions – Parameter Parsing
• In a function parameters are passed/parsed in Right to Left direction.
Functions - Advantages
Advantages:
• Modularity
• Readability
• Reusability
• Easy to develop, debug and test
• Allows test-driven development
• Allows unit testing
• Allows top-down modular approach
Recursion
• Definition: Recursion is a process by which a function calls itself
repeatedly, until some specified condition has been satisfied.
• To solve a problem recursively
o The problem must be written in a recursive form.
o The problem statement must include a stopping condition.
• A recursive function must have the following type of statements :
o A statement to test and determine whether the function is calling
itself again.
o A statement that calls the function itself and must be argument.
o A conditional statement (if-else).
o A return statement.
Recursion
Syntax:
A()

Void A()
void main() {
{ if (stopping condition)
return;
A(); else
return; A();
} return;
}
Recursion – Example1 - Factorial

Can we compute factorial using recursion?

factorial(5) = 5 * factorial(4)

4 * factorial(3)
n

3 * factorial(2)

2 * factorial(1)
n - 1
Recursion – Example1 - Factorial
Example: Recursive function to find factorial

int main() long int fact(int f)


{ {
long int fact; if (f==1 || f==0)
printf(“Enter n value:”); return 1;
scanf(“%d”, &n); return (f*fact(f-1);
fact = fact(n); }
printf("Factorial=%ld", fact);
return 0;
}
Recursion – Example1 - Factorial
Recursion – Example2 - Fibonacci

Can we compute Fibonacci series using recursion?

Do it Now: Write a program to find „n‟ Fibonacci numbers using recursion


Recursion – Example2 - Fibonacci
#include<stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
printf("%d\t", fibonacci(i));
return 0;
}

int fibonacci(int i)
{
if(i == 0) return 0;
if(i == 1) return 1;
return (fibonacci(i-1) + fibonacci(i-2));
}
Recursion
Advantages:
• Simple to code (Not Always)
• Size of the code will be less
• Readable
• Disadvantages:
• Difficult to understand in some algorithms
• Stack Overflow in case of deep recursion
• Less portable
• Writing parallel recursive functions is error prone
Class room Exercise - 6
1. Write a program to implement multiplication using
addition. Use recursion.
2. Write a program to swap two numbers.
3. Write a recursive function to find the sum of n
integers.
Class room Exercise - 6
Trace of Function multiply(6,3)

The recursive step.

The recursive step.

The simple case.

Ref: 2004 Pearson Addison-Wesley. 10-179


Storage Classes
Defines the scope (visibility) and life-time of variables and/or functions

Auto Register
 Default storage class for local  used to define local variables that should be
variables stored in a register instead of RAM.
 Max size = size of register (=1 word)
 can‟t have unary operator applied to it
int count;
 Should be used for variables that need quick
auto int count; access e.g counters
Ex: register int count;

extern
static  Provides reference of global variable that is
 Exists during the lifetime of the visible to ALL the program files
program  When you use 'extern', the variable cannot
 Enables variables to maintain their be initialized as all it does is point the
values between the function calls variable name at a storage location that has
 Can also be applied to global been previously defined
variable but the scope is restricted  extern modifier is most commonly used
to file in which is declared when there are two or more files sharing the
static int count=2; same global variables or functions
Storage Classes
Defines the scope (visibility) and life-time of variables and/or functions
Example auto

#include <stdio.h>
void increment(int);
int main() void increment(int count)
{ {
auto count = 1; count++;
increment(); printf("count is %d\n", count);
increment(); }
increment();
}

The scope of this auto variable is within the function only. It is


equivalent to local variable. All local variables are auto variables
by default.
Example register

#include <stdio.h>
void increment(int);
int main() void increment(int count)
{ {
register count = 1; count++;
increment(); printf("count is %d\n", count);
increment(); }
increment();
}
Example static

#include <stdio.h>
void increment(); void increment( )
int main() {
{ static int count=0;
increment(); count++;
increment(); printf("count is %d\n", count);
increment(); }
}
Example extern

#include<stdio.h>
int x = 10 ;
int main( )
{
extern int y ; //Declaration
printf ( "The value of x is %d\n", x ) ;
printf ( "The value of y is %d\n",y ) ;
return 0;
}

int y = 50 ; //Definition
Day 3

5. Data Input & Output


6. Arrays
7. Multidimensional Arrays
Introduction
 Input/Output is not part of C language

 C standard library provides us the facility to do I/O

 I/O functions permit the transfer of information between the


computer and the standard input or output devices (e.g., a
keyboard and a TV monitor)

 C Standard library promotes cross platform compatibility

 C has no direct support for random-access data files.

 So, to read from a record in the middle of a file, the programmer


must create a stream, seek to the middle of the file, and then
read bytes in sequence from the stream.
Streams

 Stream: Sequence of characters organized into lines


 ANSI C must support lines of at least 254 characters
 Performs all input and output
 Can often be redirected
 C abstracts all file operations into operations on streams of
bytes
 Types of streams
1. Standard input  keyboard
2. Standard output  screen
3. Standard error  screen
I/O Routines Overview
• I/O operations with standards IO
• I/O with files
• Random I/O operations on files
• Creating temporary files
• Control Buffer Managing scheme
• Handling errors
• Obtaining information
Before learning about I/O, we should learn few other concepts

 What is a variadic function?

o functions which having variable number of parameters

o Examples: printf, scanf

 Escape sequences

 Character and String

 Number representation in C
Escape Sequences
Definition: Character combinations consisting of a backslash (\)
followed by a letter or by a combination of digits.

 Considered as a single character and is therefore valid as a


character constant.

 Uses:

o To represent a newline character, single quotation mark, or certain


other characters in a character constant.

o Used to specify carriage return, tab, literal representations of


nonprinting characters, Characters with special meanings (“) etc.

o Allow you to send non-graphic control characters to a display


device. e.g, the ESC character (\033).
Escape Sequences…
Note:

 You can also use the backslash (\) as a continuation character.

 When a newline character (equivalent to pressing the RETURN


key) immediately follows the backslash, the compiler ignores the
backslash and the newline character and treats the next line as
part of the previous line.

 This is useful primarily for preprocessor definitions longer than a


single line. e.g.

Example: #define assert(xpr) \

((xpr) ? (void)0 : _assert(#xpr, __FILE__, __LINE__))


List of ANSI Escape Sequences

Escape
Description Representation
sequence

\' single quote byte 0x27


\" double quote byte 0x22
\? question mark byte 0x3f
\\ backslash byte 0x5c
\0 null character byte 0x00
\a audible bell byte 0x07
\b backspace byte 0x08
\f form feed - new page byte 0x0c
\n line feed - new line byte 0x0a
\r carriage return byte 0x0d
\t horizontal tab byte 0x09
List of ANSI Escape Sequences…
Escape
Description Representation
sequence

\v Vertical tab byte 0x0b

arbitrary ASCII Character in octal value. At least one


\nnn digit and maximum 3 digits. e.g. \10 or \010 for byte nnn
backspace

arbitrary ASCII character in hexadecimal value.


\xnn Number of hexadecimal digits is unlimited. e.g. \x31, byte nn
\x5A

Unicode character in hexadecimal notation if this


\xnnnn escape sequence is used in a wide-character -
constant or a Unicode string literal. e.g. L'\x4e00'

arbitrary Unicode value. May result in several


\unnnn code point U+nnnn
characters.
Character & String
 A character constant is formed by enclosing a single character from
the representable character set within single quotation marks („ ').
Examples: „5', '\b', „R', L'\x4e00„
 A string is an array of characters. String literals are words surrounded
by double quotation marks ("").
Examples:
"This is a string"
L"This is a wide string"
"123abc"
"a4"
L"1234*abc@"
 In C, to store strings we could use arrays.
Number representation in C
 Computers store information in binary (base-2).
 Every thing in a program eventually gets converted to binary.
 However we read them using base-10 (decimal), base-8 (octal) and
base-16 (hexadecimal).

Number
Base Calculation Example
Representation
1x24+0x23+1x22+1x21 0010111
Binary 0,1 0010111
+1x20
Decimal 0,1,2,3,4,5,6,7,8,9 2x101+3x100 23 -

000 010
Octal 0,1,2,3,4,5,6,7 2x81+7x80 27
111
0,1,2,3,4,5,6,7,8,9,a,b,c,d, 0001 0111
Hexadeci e,f (or)
1x161+7x160 17
mal 0,1,2,3,4,5,6,7,8,9,A,B,C,
D,E,F
Number representation in C…
 Integer constants are constant data elements that have no fractional
parts or exponents.
 Always begin with a digit.
 Can specify integer constants in decimal, octal, or hexadecimal form.
 Can specify signed or unsigned types and long or short types.
 To specify a decimal constant, begin the specification with a nonzero
digit.
 Example:
int num = 120; //decimal constant
Number representation in C…

 To specify an octal constant, begin the specification with 0 (oh),


followed by a sequence of digits in the range 0 through 7. e.g.

int inum = 0774; // octal constant


int jnum = 0495; // error: 9 is not an octal digit

 To specify a hexadecimal constant, begin the specification with 0x or


0X (the case of the "x" does not matter), followed by a sequence of
digits in the range 0 through 9 and a (or A) through f (or F).
 Hexadecimal digits a (or A) through f (or F) represent values in the
range 10 through 15. e.g.

int inum = 0x4f2a; // hexadecimal constant


int inum = 0X4F2A; // equal to inum
Number representation in C…
 To specify an unsigned type, use either the u or U suffix.
 To specify a long type, use either the l or L suffix.
 Example:

unsigned unVal = 238u; // unsigned value


long lgVal = 0x6FFFFFL; // long value specified
// as hex constant
unsigned long unlgVal = 0677342ul; // unsigned long
// value

 To specify a 64-bit integral type, use LL, ll or i64 suffix.


I/O functions
Formatted I/O functions
Byte
Description
character
scanf()
reads formatted byte input from stdin (standard
fscanf()
input), a file stream or a buffer
sscanf()
vscanf()
reads formatted input byte from stdin, a file
vfscanf()
stream or a buffer using variable argument list
vsscanf()
printf()
fprintf() prints formatted byte output to stdout (standard
sprintf() output), a file stream or a buffer
snprintf()
vprintf()
prints formatted byte output to stdout,
vfprintf()
a file stream, or a buffer using variable argument
vsprintf()
list
vsnprintf()
I/O functions…
Unformatted I/O functions:

Byte
Description
character
fgetc()
reads a byte from a file stream
getc()
fgets() reads a byte line from a file stream
fputc()
writes a byte to a file stream
putc()
fputs() writes a byte string to a file stream
getchar() reads a byte from stdin
reads a byte string from stdin (deprecated in
gets()
C99, obsolete in C11)
putchar() writes a byte to stdout
puts() writes a byte string to stdout
ungetc() puts a byte back into a file stream
I/O functions…
File accessing & Direct I/O:

fopen() opens a file


freopen() opens a different file with an existing stream
fflush() synchronizes an output stream with the actual file
File fclose() closes a file
access setbuf() sets the buffer for a file stream
setvbuf() sets the buffer and its size for a file stream
switches a file stream between wide character I/O
fwide()
and narrow character I/O

Direct fread() reads from a file


input/out
put fwrite() writes to a file
I/O functions…
File positioning, Error handling & Other operations on files:
ftell() returns the current file position indicator
fgetpos gets the file position indicator
moves the file position indicator to a specific location in a
File fseek()
file
positioning
moves the file position indicator to a specific location in a
fsetpos()
file
rewind() moves the file position indicator to the beginning in a file
clearerr() clears errors
feof() checks for the end-of-file
Error
ferror() checks for a file error
handling
displays a character string corresponding of the current
perror()
error to stderr
remove() erases a file
Operations rename() renames a file
on files tmpfile() returns a pointer to a temporary file
tmpnam() returns a unique filename
Standard Input & Output
Standard Output – “printf” family
 Functionality of “printf” family: Loads the data from the given
locations, converts them to character string equivalents and writes the
results to stdout or to a file stream or to a char string buffer.

a) printf()  writes to stdout


b) fprintf()  writes to a file stream
c) sprintf()  writes to a character string
d) snprintf()  buffer At most (buf_size – 1)
characters are written
(The resulting character string will be terminated with a null character,
unless buf_size is zero.)
About “printf”
 It performs precise output formatting
o Conversion specifications: flags, field widths, precisions, etc.
 Syntax:

printf( format-control-string, other-arguments );

 format control string: describes output format

 other-arguments: correspond to each conversion specification in


format-control-string. each specification begins with a percent sign,
ends with conversion specifier

 Return Value: Returns the number of characters printed (excluding


the null byte used to end output to strings), (or) a negative value if an
error occurs.

 If format is NULL, the invalid parameter handler is invoked.


About “printf”…
 It can perform:
o Rounding
o aligning columns
o right/left justification
o inserting literal characters
o exponential format
o hexadecimal format
o fixed width
o precision and so on….

Q: What we need to perform the above???

A: Format Specifier
About “printf” – Format Specification
 Syntax:
% [flags] [width] [.precision] [{h | l | ll | I |
I32 | I64}]type

 More readable form:


% [flags] [field_width] [.precision]
[length_modifier] conversion_character

 Where components in brackets [ ] are optional.


 If a percent sign (%) is followed by a character that has no meaning as
a format field, the character is copied to stdout. For example, to print a
percent-sign character, use %%.
“printf” – Format Specification…
Character that control justification of output and
Flags printing of signs, blanks, decimal points, octal and
(Optional) hexadecimal prefixes.
Examples: - + # blank
Width Number that specifies the minimum number of
(Optional) characters output.

Number that specifies the maximum number of


Precision
characters printed for all or part of the output field, or
(Optional)
the minimum number of digits printed for integer
values.
h | l | ll | I32 | I64 Prefixes to type that specify the size of argument.
(Optional)
Required character that determines whether the
Type
associated argument is interpreted as a character, a
(Compulsary)
string, or a number.
Format Specification - Flags
 It is the first optional field of the format specification after % sign.
 More than one flag directive may appear in a format specification.
Flag Meaning
– Left align the result within the given field width.
+ Prefix the O/P with a sign (+ or –) if the output is of a signed type.

If width is prefixed with 0, zeros are added until the minimum width is
0
reached. If 0 and – appear, the 0 is ignored.

A blank. Prefix the output value with a blank if the output value is signed
' '
and positive; the blank is ignored if both the blank and + flags appear.
When used with the o, x, or X format, the # flag prefixes any nonzero
output value with 0, 0x, or 0X, respectively.
# When used with the e, E, f, a or A format, the # flag forces the output
value to contain a decimal point in all cases.
When used with the g or G format, the # flag forces the output value to
contain a decimal point in all cases and prevents the truncation of trailing
zeros. Ignored when used with c, d, i, u, or s.
Format Specification - Width
Width Specification:

 The second optional field.


 The width argument is a non-negative decimal integer controlling the
minimum number of characters printed.
 If the number of characters in the output value is less than the specified
width, blanks are added to the left or the right of the values, depending
on whether the – (minus) flag (for left alignment) is specified, until the
minimum width is reached.
 If width is prefixed with 0, zeros are added until the minimum width is
reached (not useful for left-aligned numbers).
 The width specification never causes a value to be truncated.
Format Specification – Width…
 If the number of characters in the output value is greater than the
specified width, or if width is not given, all characters of the value are
printed (but subject to the precision specification).
 If the width specification is an asterisk (*), an int argument from the
argument list supplies the value.
 The width argument must precede the value being formatted in the
argument list.
 A non-existent or small field width does not cause the truncation of a
field; if the result of a conversion is wider than the field width, the field
expands to contain the conversion result.
Example:
printf("%%7s: %7s, %%7s: %7s,\n", "abc", "123456" );

%7s: abc, %7s: 123456,


Format Specification – Precision
Precision Specification:

 The third optional field.


 It specifies a nonnegative decimal integer, preceded by a period (.),
which specifies the number of characters to be printed, the number of
decimal places, or the number of significant digits as summarized in
the following table (Next slide).
 Unlike the width specification, the precision specification can cause
either truncation of the output value or rounding of a floating-point
value.
 If precision is specified as 0 and the value to be converted is 0, the
result is no characters output, as shown below:
printf("%.0d", 0); /* no characters output */
Format Specification – Precision
Type Meaning Default
Default precision is 6. If precision
The precision specifies the number of digits after the
a, A is 0, no point is printed unless the
point.
# flag is used.
c, C The precision has no effect. Character is printed.
The precision specifies the minimum number of digits
to be printed. If the number of digits in the argument is
d, i, u,
less than precision, the output value is padded on the Default precision is 1.
o, x, X
left with zeros. The value is not truncated when the
number of digits exceeds precision.
Default precision is 6; if precision
The precision specifies the number of digits to be
is 0 or the period (.) appears
e, E printed after the decimal point. The last printed digit is
without a number following it, no
rounded.
decimal point is printed.
The precision value specifies the number of digits after Default precision is 6; if precision
the decimal point. If a decimal point appears, at least is 0, or if the period (.) appears
f
one digit appears before it. The value is rounded to the without a number following it, no
appropriate number of digits. decimal point is printed.
The precision specifies the maximum number of Six significant digits are printed,
g, G
significant digits printed. with any trailing zeros truncated.
The precision specifies the maximum number of
Characters are printed until a null
s, S characters to be printed. Characters in excess of
character is encountered.
Format Specification – Precision…

Examples:

printf("%%4f: %4f\n", 12.4321 );


printf( "%%8.5f: %8.5f\n", 1.234 );
printf("%%.1f: %4.1f\n", 12.4321 );
printf("%%.3f: %.3f\n", 12.4321 );
printf( "%%.3f: %.3f\n%%.3g: %.3g\n%%.3f:
%.3f\n%%.3g: %.3g\n", 100.2, 100.2, 3.1415926,
3.1415926 );
printf( "%%.5s: %.5s\n", "abcdefg" );
Format Specification – Precision…

Output:

%4f: 12.432100
%8.5f: 1.23400
%.1f: 12.4
%.3f: 12.432
%.3f: 100.200
%.3g: 100
%.3f: 3.142
%.3g: 3.14
%.5s: abcde
Format Specification – Size
Size Specification:

 Also known as length modifiers.


 The optional prefixes to type, h, l, I, I32, I64, and ll specify the "size"
of argument (long or short, 32- or 64-bit, single-byte character or
wide character, depending upon the type specifier that they modify).
 These type-specifier prefixes are used with type characters in printf()
functions or wprintf() functions to specify interpretation of arguments,
as shown in the following table.
Format Specification – Size…

Size prefixes for printf() and wprintf() format-type specifiers


To specify Use prefix With type specifier
l (lowercase
long int d, i, o, x, or X
L)
long unsigned int l o, u, x, or X
long long ll d, i, o, x, or X
short int h d, i, o, x, or X
short unsigned int h o, u, x, or X
__int32 I32 d, i, o, x, or X
unsigned __int32 I32 o, u, x, or X
__int64 I64 d, i, o, x, or X
unsigned __int64 I64 o, u, x, or X
ptrdiff_t (that is, __int32
on 32-bit platforms, __int64 on I d, i, o, x, or X
64-bit platforms)
Note: All are not ANSI/C99 compatible – Platform dependent
Format Specification – Size…

Examples:

short int i = 3;
long int j = 3;
wchar_t* wide_str = L"This is a wide string";
long double d = 3.1415926535;

printf( "%%hd: %hd\n", i );


printf( "%%ld: %ld\n", j );
printf( "%%ls: %ls\n", wide_str );
printf( "%%Lg: %Lg\n", d );
Format Specification – Size…

Output:

%hd: 3
%ld: 3
%ls: This is a wide string
%Lg: 3.14159
Format Specification – Type Character
Type character

 The type character of the format specification indicates that the


corresponding argument is to be interpreted as a character, string, or
number.
 The type character is the only required format field, and it appears
after any optional format fields.
Format Specification – Type Characters
Char Type Output format
c int Specifies a single-byte character;
d, i int Signed decimal integer.
o int Unsigned octal integer.
u int Unsigned decimal integer.
x int Unsigned hexadecimal integer, using "abcdef."
X int Unsigned hexadecimal integer, using "ABCDEF."
Signed value having the form [ – ]d.dddd e
[sign]dd[d] where d is a single decimal digit, dddd is one
e double or more decimal digits, dd[d] is two or three decimal digits
depending on the output format and size of the exponent, and
sign is + or –.
Identical to the e format except that E rather than e introduces
E double
the exponent.

Signed value having the form [ – ]dddd.dddd, where dddd


f double
is one or more decimal digits.
Format Specification – Type Characters…
Char Type Output format

Signed values are displayed in f or e format, whichever is more


compact for the given value and precision. The e format is used only
g double
when the exponent of the value is less than –4 or greater than or
equal to the precision argument. Trailing zeros are truncated.
Identical to the g, except that E, rather than e, introduces the
G double
exponent.
Pointer to Displays the argument as an address in hexadecimal digits (as if by
p
void %#x or %#lx)
Pointer to Number of characters successfully written so far to the stream or
n
integer buffer;
Signed hexadecimal double precision floating point value having the
form [−]0xh.hhhh p±dd, where h.hhhh are the hex digits (using
a double
lower case letters) of the mantissa, and dd are one or more digits for
the exponent.
When used with printf() functions, specifies a single-byte-
character string; when used with wprintf() functions, specifies a
s String
wide-character string. Characters are displayed up to the first null
character or until the precision value is reached.
“printf” – Examples
Examples:
printf("%#x\n", 141); 0x8d

printf("%g\n", 5.1234567); 5.12346


printf("%07d\n", 123); 0000123
printf("%+d\n", 456); +456
printf("%-7d,%-5d,\n", 33, 44); 33xxxxx,44xxx,
printf("%7s\n", "123456"); x123456
printf("%4f\n", 41.1234); 41.123400
printf("%8.5f\n", 3.234); x3.23400
printf("%.3f\n", 15.4321); 15.432
printf("%hd\n", 7); 7
printf("%ld\n", 9); 9
printf("%s\n", "my name"); my name
printf("%Lg\n", 45.23456123); 5.13001e-4937
“printf” – Few more Examples

More Examples:

printf("%%#x: %#x\n", 120 );


printf("%%x: %x\n", 12 );
printf("%%#X: %#X\n", 120 );
printf("%%X: %X\n", 12 );
printf("%%#o: %#o\n", 120 );
printf("%%o: %o\n", 12 );
printf("%%#2f: %#2f\n", 120.567 );
printf( "%%g: %g\n", 3.1415926 );
printf( "%%g: %g\n", 93000000.0 );
printf( "%%G: %G\n", 93000000.0 );
printf("%%07d: %07d\n", 102 );
printf("%+d\n", 102 );
printf("%%-7d,%%-5d,: %-7d,%-5d,\n", 11, 22 );
printf("%%#010x: %#010x\n", 121 );
printf("%%#010X: %#010X\n", 121 );
Output :

%#x: 0x78
%x: c
%#X: 0X78
%X: C
%#o: 0170
%o: 14
%#2f: 120.567000
%g: 3.14159
%g: 9.3e+007
%G: 9.3E+007
%07d: 0000102
+102
%-7d,%-5d,: 11 ,22 ,
%#010x: 0x00000079
%#010X: 0X00000079
2 /* Using the integer conversion specifiers */
3 #include <stdio.h>
4
5 int main()  1. Print
6 {
7 printf( "%d\n", 455 );
8 printf( "%i\n", 455 ); /* i same as d in printf */
9 printf( "%d\n", +455 );
10 printf( "%d\n", -455 );
11 printf( "%hd\n", 32000 );
12 printf( "%ld\n", 2000000000 );
13 printf( "%o\n", 455 );
14 printf( "%u\n", 455 );
15 printf( "%u\n", -455 );
16 printf( "%x\n", 455 );
17 printf( "%X\n", 455 );
18
19 return 0;
20 }

455  Program Output


455
455
-455
32000
2000000000
707
455
65081
1c7
1C7
Ref: 2000 Prentice Hall, Inc.
1 /* Fig 9.4: fig09_04.c */
2 /* Printing floating-point numbers with
3 floating-point conversion specifiers */
4
5 #include <stdio.h>  1. Print
6
7 int main()
8 {
9 printf( "%e\n", 1234567.89 );
10 printf( "%e\n", +1234567.89 );
11 printf( "%e\n", -1234567.89 );
12 printf( "%E\n", 1234567.89 );
13 printf( "%f\n", 1234567.89 );
14 printf( "%g\n", 1234567.89 );
15 printf( "%G\n", 1234567.89 );
16
17 return 0;
18 }

1.234568e+006  Program Output


1.234568e+006
-1.234568e+006
1.234568E+006
1234567.890000
1.23457e+006
1.23457E+006

Ref: 2000 Prentice Hall, Inc.


1 /* Fig 9.5: fig09_05c */
2 /* Printing strings and characters */
3 #include <stdio.h>
4
5 int main()
6 {
7 char character = 'A';  1. Initialize variables
8 char string[] = "This is a string";
9 const char *stringPtr = "This is also a string";
 2. Print
10
11 printf( "%c\n", character );
12 printf( "%s\n", "This is a string" );
13 printf( "%s\n", string );
14 printf( "%s\n", stringPtr );
15
16 return 0;
17 }

A
This is a string
This is a string  Program Output
This is also a string

Ref: 2000 Prentice Hall, Inc.


2 /* Using the p, n, and % conversion specifiers */
3 #include <stdio.h>
4
5 int main()
6 {
7 int *ptr;
8 int x = 12345, y;
 1. Initialize variables
9
10 ptr = &x;
11 printf( "The value of ptr is %p\n", ptr );  2. Print
12 printf( "The address of x is %p\n\n", &x );
13
14 printf( "Total characters printed on this line is:%n", &y );
15 printf( " %d\n\n", y );
16
17 y = printf( "This line has 28 characters\n" );
18 printf( "%d characters were printed\n\n", y );
19
20 printf( "Printing a %% in a format control string\n" );
21
22 return 0;
23 }
The value of ptr is 0065FDF0
The address of x is 0065FDF0
 Program Output
Total characters printed on this line is: 41

This line has 28 characters


28 characters were printed

Printing a % in a format control string Ref: 2000 Prentice Hall, Inc.


Standard Input - “scanf” family

 Read formatted data from a variety of standard input streams which


are:
1) data from stdin (standard input)  scanf() and wscanf()
2) data from file stream  fscanf() and fwscanf()
3) data from null-terminated character string buffer  sscanf()
and swscanf()
 and interprets it according to the format then stores the results in its
arguments.
 We focus only on scanf().
Standard Input - “scanf” family

int scanf(const char *format


Syntax
[,argument]...);
format - pointer to a null-terminated character string
Parameters specifying how to read the input or a format control string.
argument - optional arguments.
Usage Read formatted data from the standard input stream
Returns the number of fields successfully converted and
assigned; the return value does not include fields that
Return were read but not assigned. A return value of 0 indicates
value that no fields were assigned. If format is a NULL pointer,
the invalid parameter handler is executed. If execution is
allowed to continue, these functions return EOF.
Example scanf("%d%5f%f%s", &i, &j, &x, name);
Remarks Also called variadic function.
“scanf” – format specifier
 Purpose: Describes the symbols used to tell the scanf() function how to
parse the input stream, such as from stdin, into values that are inserted
into (program) variables.

 Form: Has the following form, components in brackets [ ] are optional.

% [*] [width] [{h | l | ll | I64 | L}]type

 More readable form:

% [*] [field_width] [length_modifier] conversion_character

Where components in brackets [ ] are optional.

 Examples:
scanf("%f", &a);
scanf("%4f", &b);
scanf("%ls", &y);
scanf("%*d %[0123456789]", myname);
“scanf” – format specifier
The format argument specifies the interpretation of the input and can
contain one or more of the following:
1. White-space characters: blank, tab ('\t') or newline ('\n').
 A white-space character causes scanf() to read, but not to store, all
consecutive white-space characters in the input up to the next non-white-
space character.
 One white-space character in the format matches any number (including
0) and combination of white-space characters in the input.
2. Non-white-space characters:
 Except percent sign (%).
 A non-white-space character causes scanf() to read, but not to store,
a matching non-white-space character.
 If the next character in the input stream does not match, scanf()
terminates.
“scanf” – format specifier…
3. Format specifications:
 Introduced by the percent sign (%).
 A format specification causes scanf() to read and convert characters in
the input into values of a specified type.
 The value is assigned to an argument in the argument list.
“scanf” – format specifier…
 The format is read from left to right.
 Characters outside format specifications are expected to match the
sequence of characters in the input stream; the matching characters in
the input stream are scanned but not stored.
 If a character in the input stream conflicts with the format specification,
scanf() terminates, and the character is left in the input stream as if it
had not been read.
 When the first format specification is encountered, the value of the first
input field is converted according to this specification and stored in the
location that is specified by the first argument.
 The second format specification causes the second input field to be
converted and stored in the second argument, and so on through the
end of the format string.
“scanf” – format specifier…

 An input field is defined as all characters (a string of non-white-space


character) up to the first white-space character (space, tab, or
newline), or up to the first character that cannot be converted
according to the format specification, or until the field width (if
specified) is reached.
 If there are too many arguments for the given specifications, the extra
arguments are evaluated but ignored.
 The results are unpredictable if there are not enough arguments for the
format specification.
 The type character, which appears after the last optional format field,
determines whether the input field is interpreted as a character, a
string, or a number.
“scanf” – format specifier…
 The simplest format specification contains only the percent sign and a
type character. e.g. scanf(%s)
 If a percent sign (%) is followed by a character that has no meaning as
a format-control character, that character and the following characters
(up to the next percent sign) are treated as an ordinary sequence of
characters, that is, a sequence of characters that must match the
input.
 For example, to specify that a percent-sign character is to be input, use
%%.
 An asterisk (*) following the percent sign suppresses assignment of
the next input field, which is interpreted as a field of the specified
type. The field is scanned but not stored.
“scanf” – width field
 scanf() normally assumes that the input stream is divided into a
sequence of tokens.
 Tokens are separated by whitespace (space, tab, or newline)
 The width specification is be used to cause the parsing of the input
to stop before the natural end of a token.
 The width specification consists of characters between the % and the
type field specifier, which may include a positive integer called the
width field and one or more characters indicating the size of the field,
which may also be considered as modifiers of the type of the field,
such as an indication of whether the integer type is short or long.
 Example:
scanf("%4f", &x);
“scanf” – size prefix
 The optional prefixes h, l, ll, I64, and L indicate the size of the
argument (long or short, single-byte character or wide character,
depending upon the type character that they modify).
 Used with type characters in scanf() functions to specify interpretation
of arguments as shown in the following table.
 The type prefix I64 is a Microsoft extension example and is not ANSI
compatible.
 The h, l, and L prefixes are Microsoft extensions when used with
data of type char.
“scanf” – size prefix

Examples:
scanf( "%ls", &x ); // read a wide-character string
wscanf( "%hC", &x ); // read a single-byte character
“scanf” – Example1
char *p;
int q;
errno = 0;

q = scanf("%a[a-z]", &p);
if (q == 1)
{
printf("read: %s\n", p);
free(p);
}
else if (errno != 0)
{
perror("scanf");
}
else
{
printf("No matching characters\n"):
}
Note: “a” is interpreted as a specifier for floating-point numbers
“scanf” – When it stops reading a field?
 The scanf() function scans each input field, character by character. It
may stop reading a particular input field before it reaches a space
character for a variety of reasons:
1) The specified width has been reached.
2) The next character cannot be converted as specified.
3) The next character conflicts with a character in the control string
that it is supposed to match.
4) The next character fails to appear in a given character set.
 For whatever reason, when the scanf() function stops reading an input
field, the next input field is considered to begin at the first unread
character.
“scanf” – Type field Characters
The following information applies to any of the scanf() family of functions.
 The type character is the only required format field.
 Appears after any optional format fields.
 The type character determines whether the associated argument is
interpreted as a character, string, or number.
“scanf” – Type field Characters…
Character Type of input expected Type of argument

Character.
White-space characters that are
c ordinarily skipped are read when c is Pointer to char
specified. To read next non-white-space
single-byte character, use %1s;

Character.
White-space characters that are
C ordinarily skipped are read when C is Pointer to wchar_t
specified. To read next non-white-space
single-byte character, use %1s;

d Decimal integer. Pointer to int


“scanf” – Type field Characters…
d Decimal integer. Pointer to int.
An integer. Pointer to int.
Hexadecimal if the input string
i begins with "0x" or "0X", octal if
the string begins with "0",
otherwise decimal.

o Octal integer. Pointer to int.


u Unsigned decimal integer. Pointer to unsigned int.
x Hexadecimal integer. Pointer to int.
Floating-point value consisting of Pointer to float.
optional sign (+ or –), series of
one or more decimal digits
e , E, f, g,
containing decimal point, and
G
optional exponent ("e" or "E")
followed by an optionally signed
integer value.
“scanf” – Type field Characters…
No input read from stream or buffer. Pointer to int, into which is stored
number of characters successfully
n read from stream or buffer up to
that point in current call to scanf()
functions or wscanf() functions.
String, up to first white-space When used with scanf() functions,
character (space, tab or newline). To signifies single-byte character
read strings not delimited by space array. Character array must be
s
characters, use set of square large enough for input field plus
brackets ([ ]). terminating null character, which is
automatically appended.
Opposite-size character string, up to When used with scanf() functions,
first white-space character (space, tab signifies wide-character array.
or newline). To read strings not Character array must be large
S delimited by space characters, use enough for input field plus
set of square brackets ([ ]), as terminating null character, which is
discussed in scanf() Width automatically appended.
“scanf” – Examples

Run the following program and precede the %c‟s with spaces.

#include <stdio.h>

int main(void)
{ White space will terminate a string
char a, b;
int i, j;
printf("Enter two char-int pairs: ");
scanf(" %c %d", &a, &i);
scanf(" %c %d", &b, &j);
printf("%c:%d:\n", a, i);
printf("%c:%d:\n", b, j);
return 0;
}
1 /* Fig 9.20: fig09_20.c */
2 /* Reading characters and strings */
3 #include <stdio.h>
4
5 int main()
6 {
7 char x, y[ 9 ];
 1. Initialize variables
8
9 printf( "Enter a string: " );
10 scanf( "%c%s", &x, y );  2. Input
11
12 printf( "The input was:\n" );
13 printf( "the character \"%c\" ", x );  3. Print
14 printf( "and the string \"%s\"\n", y );
15
16 return 0;
17 }

Enter a string: Sunday


The input was:  Program Output
the character "S" and the string "unday"

Ref: 2000 Prentice Hall, Inc.


1 /* Fig 9.22: fig09_22.c */
2 /* Using an inverted scan set */
3 #include <stdio.h>
4
5 int main()
6 {
7 char z[ 9 ] = { '\0' };  1. Initialize variable
8
9 printf( "Enter a string: " );
10 scanf( "%[^aeiou]", z );  2. Input
11 printf( "The input was \"%s\"\n", z );
12
13 return 0;
 3. Print
14 }

Enter a string: String


The input was "Str"  Program Output

Ref: 2000 Prentice Hall, Inc.


1 /* Fig 9.24: fig09_24.c */
2 /* Reading and discarding characters from the input stream */
3 #include <stdio.h>
4
5 int main()  1. Initialize variables
6 {
7 int month1, day1, year1, month2, day2, year2;  2. Input
8
9 printf( "Enter a date in the form mm-dd-yyyy: " );  3. Print
10 scanf( "%d%*c%d%*c%d", &month1, &day1, &year1 );
11 printf( "month = %d day = %d year = %d\n\n",
12 month1, day1, year1 );
13 printf( "Enter a date in the form mm/dd/yyyy: " );
14 scanf( "%d%*c%d%*c%d", &month2, &day2, &year2 );
15 printf( "month = %d day = %d year = %d\n",
16 month2, day2, year2 );
 Program Output
17
18 return 0;
19 }

Enter a date in the form mm-dd-yyyy: 11-18-2000


month = 11 day = 18 year = 2000

Enter a date in the form mm/dd/yyyy: 11/18/2000


month = 11 day = 18 year = 2000 Ref: 2000 Prentice Hall, Inc.
Quiz - 7
1) Did the values get read into the variables as they should have YES
been?
2) Try the same experiment again without the leading spaces in YES
the format strings for integers e.g. scanf(" %c%d", &a,
&i);. Did you get the results as before?
3) Try the same experiment again without the leading spaces in NO

the format strings for the characters (e.g. scanf("%c %d",


&a, &i);. Did you get the same result as before?
4) When reading in integers, spaces are not needed, true or false? TRUE

5) When reading in characters, we would add the spaces before TRUE

the %c‟s, true or false?

Format strings for floats (%f) behave like integers and


those for strings (%s) behave like characters.
Single character Input - getchar()
Purpose: Single character can be entered into the computer using the C
library function “getchar”.
 Part of C standard library
 Return value: returns a single character from a standard input device
(typically a keyboard)
 Arguments: The function does not require any arguments.

Syntax: character variable = getchar ( ) ;

where character variable refers to some previously declared character


variable.
Single character Input - getchar()
Note:
 If an end-of-file condition is encountered when reading a character with
the getchar function, the value of the symbolic constant EOF will
automatically be returned.
 EOF will be assigned the value -1 (Defined in stdio.h)
 The getchar function can also be used to read multicharacter strings, by
reading one character at a time within a multipass loop.
Single character output - putchar()
Purpose: Single characters can be displayed (Le, written out of the
computer) using the C library function putchar.
 Part of C standard library
 Return value: On success, the character written will be returned. If a
writing error occurs, EOF is returned and the error indicator (ferror) is
set.
 Arguments: Character variable. The value is internally converted to
an unsigned char when written.

Syntax: putchar (character variable) ;

where character variable refers to some previously declared character


variable.
Example – getchar & putchar
Program to convert all the characters in a file from lower case to upper case

#include <stdio.h>
#include <ctype.h>
main( )
{
char letter[80];
int count, tag;
/* enter the text */
for (count = 0; (letter[count] = getchar()) I= '\no; ++count) ;
tag = count;
/* display the line in uppercase */
for (count = 0; count < tag; ++count) putchar(toupper(letter[count]));
}
String Input - gets()
Purpose: Reads characters from the standard input (stdin) and stores them
as a C string into str until a newline character or the end-of-file is reached.
Syntax: char * gets ( char * str );
 Return value:
o On success, the function returns str.
o If the end-of-file is encountered while attempting to read a character,
the eof indicator is set (feof).
o If this happens before any char could be read, the pointer returned is
a null pointer (and the contents of str remain unchanged).
o If a read error occurs, the error indicator (ferror) is set and a null
pointer is also returned
 Arguments: Pointer to a block of memory (array of char) where the
string read is copied as a C string.
String Input - gets()
 A terminating null character is automatically appended after the
characters copied to str.
 The newline character, if found, is not copied into str
 It does not include the ending newline character in the resulting string
 It does not allow to specify a maximum size for str (which can lead to
buffer overflows).
String Input - puts()
Purpose: Writes the C string pointed by str to the standard output (stdout)
and appends a newline character ('\n').

Syntax: int puts ( const char * str );

 Arguments: C string to be printed.


 Return value:
o On success, a non-negative value is returned.
o On error, the function returns EOF and sets the error
indicator (ferror).
 The function begins copying from the address specified (str) until it
reaches the terminating null character ('\0').
 This terminating null-character is not copied to the stream.
 It appends a newline character at the end automatically
Example – gets & puts

#include <stdio.h>
/* read and write a line of text */
int main( )
{
char line[80];
gets(1ine);
puts(1ine);
return 0;
]
Thank You

You might also like