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

C Programming Lecture Notes Final

This document outlines a lecture plan for a Computer Programming course. It covers 9 topics over 13 lectures, including introduction to C, data types, operators, control statements, arrays, functions, pointers, structures, and file management. Students will have 6 tutorials to reinforce concepts. There will be a midterm quiz and final exam weighted at 40% and 60% respectively. Reference books include Programming with C by Gottfried and The C Programming Language by Kernighan and Ritchie.

Uploaded by

Shashank Shekhar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

C Programming Lecture Notes Final

This document outlines a lecture plan for a Computer Programming course. It covers 9 topics over 13 lectures, including introduction to C, data types, operators, control statements, arrays, functions, pointers, structures, and file management. Students will have 6 tutorials to reinforce concepts. There will be a midterm quiz and final exam weighted at 40% and 60% respectively. Reference books include Programming with C by Gottfried and The C Programming Language by Kernighan and Ritchie.

Uploaded by

Shashank Shekhar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 520

Lecture Plan

II Semester, Common (Sec A to D) CSI101 / Computer Programming / 2-1-0 2022−2023


(Winter Semester)

Sl No. Topic Lecture Tutorial

1.
Introduction to Programming in C: Data types, Constants and variable 1 1
declaration, Scope, Data input and output functions, Sample programs.

2.
Operators & Arithmetic, Relational, Logical, Bitwise operators, 1
Expressions:
Conditional, Assignment.

3.
Control & Looping Statements: if, while, do-while, for, switch, break and 2 1
continue statements, Nested loops.

4.
Arrays & String Handling: Declaration, Initialization, Processing. 2 1
5. Functions: Defining functions, Accessing a function, 2 1
Passing arguments, Recursive functions, Storage classes.

6. Pointers: Declaration, Operations on pointers. 2 1

7. Under Defined Data Types: Structures & Unions. 1 1

8. File Management: File operations, Creating and 1


processing a data file.
9. Doubt Clearing Session 1 0

Total 13 06
Text and Reference Books:
1. Programming with C, Byron Gottfried, Schaum’s Outline Series.
2. The C Programming Language, B. W. Kernighan and D. M. Ritchie, Prentice Hall.
3. Programming in ANSI C, E. Balagurusamy, Tata McGraw-Hill.
Weightage of Marks:
Quiz-I(15.04.2023) tentative End Semester( As per the
Academic Calendar)
40% 60%
C: A VERY BRIEF
HISTORY &
STANDARDS
C HISTORY 1
▪ C evolved from two previous languages, BCPL (
Basic Combined Programming Language) and B.
▪ BCPL developed in 1967 by Martin Richards as a language for writing
OSes and compilers.
▪ Ken Thompson modeled many features in his language, B, after their
counterparts in BCPL, and used B to create an early versions of UNIX
operating system at bell Laboratories in 1970 on a DEC PDP-7 computer.
▪ Both BCPL and B were typeless languages: the only data type is machine
word and access to other kinds of objects is by special operators or
function calls.
▪ The C language developed from B by Dennis Ritchie at Bell Laboratories
and was originally implemented on a DEC PDP-11 computer in 1972.
▪ It was named C for new language (after B).
▪ Initially, C used widely as the development language of the UNIX OS.
▪ Today, almost all new major OS are written in C including Windows.
C STANDARDS
▪ The rapid expansion of C over various types of computers led to
many variations - similar but incompatible.
▪ Need to be standardized. In 1983, the
X3J11 technical committee was created under the American
National Standards Institute (ANSI) Committee on Computer and
Information Processing (X3) to provide an unambiguous and
machine-independent definition of the language and approved in
1989, called ANSI C.
▪ Then, the document is referred to as ANSI/ISO 9899:1990.
▪ The second edition of Kernighan and Ritchie, published in 1988,
this version called ANSI C, then used worldwide.
▪ The more general ANSI then adopted by ISO/IEC, known as
ISO/IEC C.
▪ Historically, from ISO/IEC, C programming language evolved from
C89/C90/C95, C99 and the latest is C11.
C Programming

• C is a middle -level language: suitable


language for systems programming
• It is a procedural or sequential language
• C is easy to learn or understand
• It is a case sensitive language
• C is a small language : relies on a “library”
of standard functions
• C is highly portable : means that c
programs written for one computer can be run
on other computer with no modification.
7
Basic structure of C programming

8
A Simple C Program:
Prin7ng a Line of Text
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "Welcome to C!\n" );
8
9 return 0;
10 }

• Documenta7on sec7on
• use in comment line
– Text surrounded by /* and */ is ignored by computer
– Used to describe program
• #include <stdio.h>
– Preprocessor direc7ve
• Tells computer to load contents of a certain file
– <stdio.h> allows standard input/output opera7ons
9
A Simple C Program:
Prin7ng a Line of Text
• int main()
– C programs contain one or more func7ons, exactly
one of which must be main
– Parenthesis used to indicate a func7on
– int means that main "returns" an integer value
– Braces ({ and }) indicate a block
• The bodies of all func7ons must be contained in braces

10
A Simple C Program:
Prin7ng a Line of Text
• printf( "Welcome to C!\n" );
– Instructs computer to perform an ac7on
• Specifically, prints the string of characters within
quotes (“ ”)
– En7re line called a statement
• All statements must end with a semicolon (;)
– Escape character (\)
• Indicates that prinM should do something out of the
ordinary
• \n is the newline character

11
A Simple C Program:
Prin7ng a Line of Text
• return 0;
– A way to exit a func7on
– return 0, in this case, means that the program
terminated normally
• Right brace }
– Indicates end of main has been reached
• Linker
– When a func7on is called, linker locates it in the library
– Inserts it into object program
– If func7on name is misspelled, the linker will produce an
error because it will not be able to find func7on in the
library

12
1 /* Fig. 2.5: fig02_05.c
2 Addition program */
3 #include <stdio.h>
4
5 int main()
6 {
7 int integer1, integer2, sum; /* declaration */ 1. Initialize variables
8
9 printf( "Enter first integer\n" ); /* prompt */ 2. Input
10 scanf( "%d", &integer1 ); /* read an integer */
11 printf( "Enter second integer\n" ); /* prompt */
12 scanf( "%d", &integer2 ); /* read an integer */
13 sum = integer1 + integer2; /* assignment of sum */
2.1 Sum
14 printf( "Sum is %d\n", sum ); /* print sum */
3. Print
15
16 return 0; /* indicate that program ended successfully */
17 }

Enter first integer


45
Program Output
Enter second integer
72
Sum is 117

13
Memory Concepts
• Variables
– Variable names correspond to loca7ons in the
computer's memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable
(through scanf, for example), it replaces (and
destroys) the previous value
– Reading variables from memory does not change
them
• A visual representa7on
integer1 45

14
Arithme7c
• Arithme7c calcula7ons
– Use * for mul7plica7on and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithme7c operators act before others (i.e.,
mul7plica7on before addi7on)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3

15
Character set In C
The character sets help in defining the valid characters that we can
use in the source program or can interpret during the running of the
program:
Lowercase Alphabets a to z: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p,
q, r, s, t, u, v, w, x, y, z
Uppercase Alphabets A to Z: A, B, C, D, E, F, G, H, I, J, K, L, M, N,
O, P, Q, R, S, T, U, V, W, X, Y, Z
Digits 0 to 9: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters – `~@!$#^*%&()[]{}<>+=_–
|/\;:‘“,.?
White Spaces – Blank Spaces, Carriage Return, Tab, New
Line

ASCII Values
All the character sets used in the C language have their equivalent ASCII value. The
ASCII value stands for American Standard Code for Information Interchange value. It
consists of less than 256 characters, and we can represent these in 8 bits or even
less.
16
17
C Tokens, Keywords, identifiers, constants and variables

A token is the smallest unit in a 'C' program.


A token is divided into six as follows, Variables

Keywords (eg: int, while), It is a data name used for storing a data
Identifiers (eg: main, total), value. Its value may be changed during
Constants (eg: 10, 20), the program execution.
Strings (eg: “total”, “hello”),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)

Constants VS Variable
A value that can not be altered
throughout the program A
storage location paired with an
associated symbolic name which has a
value
It is similar to a variable but it cannot be
modified by the program once defined
A storage area holds data
Can not be changed Can be changed
according to the need of the
programmer
Value is fixed
Value is varying

18
Storage classes
It is used to represent the information about a variable.
The variable scope.
The location where the variable will be stored.
The initialized value of a variable.
A lifetime of a variable.

19
1.Identifiers
2.Variables

3.Keywords

4.Statements

5.Comments

6.Whitespaces

7.Syntax

8.Semantic
C IDENTIFIERS
1. Is a unique name that simply references to memory locations, which can
hold values (data).
2. Identifiers give unique names to various objects in a program.
3. Are formed by combining letters (both upper and lowercase), digits (0–9)
and underscore ( _ ).
4. Rules for identifier naming are:
a) The first character of an identifier must be a letter (non-digit) including
underscore ( _ ).
b) The blank or white space character is not permitted in an identifier.
Space, tab, linefeed, carriage-return, formfeed, vertical-tab, and
newline characters are "white-space characters“ - they serve the
same purpose as the spaces between words and lines on a printed
page.
c) Can be any length but implementation dependent.
d) Reserved words/keywords cannot be used.
C IDENTIFIERS

Examples: variable names

Correct Wrong
secondName 2ndName /* starts with a digit */
_addNumber %calculateSum /* contains invalid
character */
charAndNum char /* reserved word */
annual_rate annual rate /* contains a space */
stage4mark my\nName /* contains new line
character, \n */
C VARIABLES
▪ are named blocks of memory & is any
valid identifier.
▪ Have two properties in syntax: name —
a unique identifier & type — what kind of
value is stored.
▪ It is identifier, that value may change
during the program execution.
▪ Every variable stored in the computer’s
memory has a name, a value and a
type.
C VARIABLES
▪ More examples
Correct Wrong Comment
int x, y, z; int 3a, 1, -
p;
short number_one; short number
+one;
long TypeofCar; long #number
unsigned …
int positive_number;
char Title;
float commission, yield =
4.52;
int my_data = 4;
char the_initial = 'M'; A char
Char studentName[20] = A string
"Anita";
C KEYWORDS/RESERVED WORDS
▪ Reserved words in C & are not available for re-definition.
▪ have special meaning in C.
auto extern short _Alignas (C11)
break float signed _Alignof (C11)
case sizeof _Atomic (C11)
char
for static _Bool (C99 beyond)
const goto struct _Complex (C99
continue if switch beyond)
default inline (C99 typedef _Generic (C11)
do beyond) union _Imaginary (C99
double unsigned beyond)
else
int void _Noreturn (C11)
enum long volatile _Static_assert (C11)
register while _Thread_local (C11)
restrict
(C99 beyond)
return
OTHERS

• Statements are terminated with a ';'


• e.g:

char acharacter;
int i, j = 18, k = -20;
printf("Initially, given j = 18 and
k = -20\n");

for(; count != 0; count = count - 1)


OTHERS
▪ Group of statements (compound statement) are
enclosed by curly braces: { and }.
▪ Mark the start and the end of code block.
▪ Also used in initializing a list of aggregate data
values such as in array and enum type.
#include <stdio.h>

int main()
int id[7] = {1, 2, 3, 4, 5, 6, 7};
{
float x[5] = {5.6, 5.7, 5.8, 5.9, 6.1}; int i, j = 18, k = -20;
char vowel[6] = {'a', 'e', 'i', 'o', 'u', prinE("IniHally, given j = 18 and k = -20\n");
'\0'}; prinE("Do some operaHons..."
"i = j / 12, j = k / 18 and k = k / 4\n");
i = j / 12;
enum days {Mon, Tue, Wed, Thu, j = k / 8;
Fri, Sat, Sun}; k = k / 4;
prinE("At the end of the operaHons...\n");
prinE("i = %d, j = %d and k = %d\n", i, j, k);
return 0;
}
COMMENTS
▪ Single line of comment: // comment here
▪ More than single line of comment or expanded: /*
comment(s) here */

// for printf()
#include <stdio.h>
#include <string.h> // for strcpy_s() and their
family

/* main() function, where program


execution starts */
int main()
{
/* declares variable and initializes it*/
int i = 8;

COMMAS
▪ Commas separate function arguments, list of
variables, aggregate values. e.g.

#include <stdio.h> int id[7] = {1, 2, 3, 4, 5,


6, 7};
int main(int argc, int argv)
{ float x[5] = {5.6, 5.7, 5.8,
int i = 77, j, k; 5.9, 6.1};
j = i + 1; k = j + 1; i = k + j; char vowel[6] = {'a', 'e',
prinE("Finally, i = %d\n", i); 'i', 'o', 'u', '\0'};
prinE("... and j = %d\n", j);
prinE("... and k = %d\n", k);
return 0;
} enum days {Mon, Tue,
Wed, Thu, Fri, Sat, Sun};
WHITESPACES
▪ Whitespace is ignored by compiler.
▪ Counted if used as separators or as components of
character constants or string literals.
▪ Space, tab, linefeed, carriage-return, formfeed, vertical-
tab, and newline characters (\n).
#include <stdio.h>

void main(void)
{
int MyAge = 12;
printf("My name is Mr. C.
Cplusplus\n");
… }
SYNTAX & SEMANTIC
▪ Programming language enforces a set of rules,
symbols and special words used to construct a
program.
▪ A set of rules that precisely state the validity of the
instructions used to construct C program is called
syntax or 'grammar' else syntax error will be
generated.
▪ The correctness of the instructions used to write C
program is called semantics or correct meaning.
▪ These set of rules for instructions validity and
correctness are monitored by the compilers.
▪ Semantically one but can have many syntaxes.
SYNTAX & SEMANTIC
▪ e.g.
To add an integer to a variable q and store the
result in q (semantic), syntaxically (correct), we
can write:

q = q + 3; or q += 3;

▪ Pseudocode - an informal high-level description


of the operating principle of a computer program
or other algorithm. www.tenouk.com, ©

▪ Uses the structural conventions of a


programming language, but is intended for
human reading rather than machine reading.
PSEUDOCODE & ALGORITHM
▪ An informal high-level description of a computer program
or algorithm operating principle.
▪ An algorithm is merely the sequence of steps taken to
solve a problem which are normally a sequence,
selection, iteration and a case-type statement.
▪ Algorithm is a procedure for solving a problem - actions
to be executed and the order in which those actions are
to be executed.
▪ e.g. to sort ascendingly, the given unsorted integers, we
can achieve this by using several different algorithms.
▪ Every algorithm may have different number line of code,
different repetition loops, different execution speeds etc.
PSEUDOCODE & ALGORITHM
▪ But all the program have similar purpose:
to sort the given unsorted integers in
ascending order.
▪ Pseudocode uses programming
language’s structural conventions ,
intended for human rather than machine
reading.
▪ helps programmers develop algorithms.
PSEUDOCODE & ALGORITHM

▪ e.g. Set sum to zero


Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the sum
Set the class average to the sum divided by ten
Print the class average.

IF HoursWorked > SET total to zero


NormalMax THEN REPEAT
Display overtime READ Temperature
IF Temperature > Freezing
message THEN
ELSE INCREMENT total
Display regular time END IF
message UNTIL Temperature < zero
ENDIF Print total
C (Basic) Data Types

-different data representations need different types in


programming-
Data Types In C

37
Data type details

38
USER DEFINED (DATA) TYPES
Keyword Size Note

≥ sum of size of An aggregate type which can contain more than one
struct
each member different types.
typedef struct
tag or label is op-onal {
struct theEmployee { int x;
int SomeArray[100];
int age;
} MyFoo;
double salary;
char department; int main()
char name[15]; {
char address[5][25]; MyFoo strctVar;
};
struct theEmployee workerRec; return 0;
}

struct newPoint {
short xPoint;
short yPoint;
} justPoint;

justPoint thePoint;
USER DEFINED (DATA) TYPES
An aggregate type which can contain more than
≥ size of the
one other types. union uses shared memory
union largest
space compared to struct, so only one member
member
can be accessed at one time.
union someData
{
int pNum;
float qNum;
double rNum;
};
union someData simpleData;
union OtherData{
char aNum;
int xNum;
float fNum;
} simpleData;
simpleData saveData;
USER DEFINED (DATA) TYPES
Enumerations are a separate type from ints,
though they are mutually convertible. Used to
enum ≥ size of char
declare identifiers as constants in an ordered
manner.

enum ndays {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

/ * Creates enum days type, which the identifiers are set


automatically to the integers 0 to 6. */
enum ndays ndayCount;

enum trafficDirection{
north,
south, enum cColor = {red = 2,
east, green, blue, black};
west
}; Enum cColor ccolorCode;
enum trafficDirection newDirection;
USER DEFINED (DATA) TYPES
same as the type; being typedef used to give new identifier names or alias (to simplify the
typedef
given a new name long identifier names), normally used for aggregate defined types.

typedef unsigned char BYTE; /* Declares BYTE to be a synonym for unsigned char */
typedef float FLOAT; /* Declares FLOAT (uppercase letter) to be a synonym for unsigned
float (lowercase) */

tag or label is optional

typedef struct simpleData typedef struct TOKEN_SOURCE {


{ int nData; CHAR SourceName[8];
char cData; LUID SourceIdentifier;
} newNameType; } TOKEN_SOURCE, *PTOKEN_SOURCE;
Or
TOKEN_SOURCE newToken;
typedef struct { int nData; char
cData;} newNameType;
newNameType strctType;
typedef enum DayNames { Monday,
typedef union unData{
Tuesday,
double lngSalary;
Wednesday,
int nDay;
Thursday,
}newUntype;
Friday, Saturday, Sunday
} Weekdays;
newUnType lntotalSalary;
Weekdays dayOfWeek;
DERIVED (DATA) TYPES
Type Size Note
▪ Hold the memory address which point to the
actual data/value.
▪ 0 address always represents the null pointer (an
address where no data can be placed),
irrespective of what bit sequence represents the
value of a null pointer.
type* ▪ Pointers to different types will have different
≥ size of char sizes. So they are not convertible to one another.
(a pointer) ▪ Even in an implementation which guarantees all
data pointers to be of the same size, function
pointers and data pointers are in general
incompatible with each other.
▪ For functions taking a variable number of
arguments, the arguments passed must be of
appropriate type.
char *ptoChar;
char csimpleChr = 'T';
int iNumber = 20;
char *chptr;
int *imyPtr = &iNumber;
// assignment
chptr = &csimpleChr;
DERIVED (DATA) TYPES
▪ Use to declare a variable with
collection of identical properties or
types.
▪ Simplify variable declaration.
▪ In a declaration which also
type [integer]
≥ integer × size of initializes the array (including a
type function parameter declaration), the
(an array)
size of the array (the integer) can be
omitted, which is called unsized.
▪ type [ ] is not the same as type*.
Only under some circumstances
one can be converted to the other.

char cName1[ ] =
int fstudentNumber[3] = {4,7,1}; {'a','r','r','a','y'};
int nrowandColumn[1][2] = {34, char cName2[ ] = {"array"};
21}; char cName3[6] = "array";
int nlongHeightWidth[3][4][5] = int nrowCol[2][3] =
0; {4,2,3,7,2,8};
DERIVED (DATA) TYPES
type (comma- — ▪ allow referencing functions
delimited list of with a particular signature.
types/ ▪ Function pointers are invoked
declarations) by name just like normal
function calls. Function
(a function pointers) pointers are separate from
pointers and void pointers.

/* two arguments function pointer */


int (* fptr) (int arg1, int arg2)

/* to store the address of the standard


function stdFunct in the variable myIntFunct */
int (*myIntFunct)(int) = stdFunct;
C STANDARD I/O
-used for reading, wri7ng from/to standard output &
forma[ng-
STANDARD I/O
In this session we will learn:
1. Escape sequence
2. Character and string
3. Standard input/output (examples):
a) Standard input – printf()
b) Standard output – scanf()
STANDARD I/O
▪ Standard library functions for file input and
output.
▪ C abstracts all file operations into operations on
streams of bytes, which may be "input streams"
or "output streams".
▪ 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.
STANDARD I/O
▪ In this topic, indirectly, we also
will learn the C standard built-in
function.
▪ And also the variadic functions
(functions which having variable
number of parameters) such as
printf() and scanf().
▪ Let start with escape sequence…
STANDARD I/O
Escape Sequence

▪ Character combinations consisting of a backslash (\)


followed by a letter or by a combination of digits.
▪ Regarded as a single character and is therefore valid as
a character constant.
▪ Must be used to represent a newline character, single
quotation mark, or certain other characters in a
character constant.
▪ Used to specify actions such as carriage returns and tab
movements on terminals and printers.
▪ Used to provide literal representations of nonprinting
characters and characters that usually have special
meanings, such as the double quotation mark (").
STANDARD I/O- List of the ANSI escape sequences and what they represent

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
\v vertical tab byte 0x0b
arbitrary ASCII character in octal value. At least one digit and
\nnn byte nnn
maximum 3 digits. e.g. \10 or \010 for backspace
arbitrary ASCII character in hexadecimal value. Number of
\xnn byte nn
hexadecimal digits is unlimited. e.g. \x31, \x5A
Unicode character in hexadecimal notation if this escape
\xnnnn sequence is used in a wide-character constant or a Unicode -
string literal. e.g. L'\x4e00'
\unnnn arbitrary Unicode value. May result in several characters. code point U+nnnn

\Unnnnnnnn arbitrary Unicode value. May result in several characters. code point U+nnnnnnnn
Standard I/o
▪ A character constant is formed by enclosing a single character
from the representable character set within single quotation marks
('').

e.g: '3', '\b', 'T', L'p', L'\x4e00'

▪ A string is an array of characters. String literals are words


surrounded by double quotation marks ("").

e.g:
"This is a string, lateral string"
L"This is a wide string"
"123abc"
"a4"
L"1234*abc@"

▪ In C, to store strings we could use array or pointers type


constructs.
STANDARD I/O
C number representation
▪ Computers store information in binary (base-2).
▪ Anything you write in a program and gets executed eventually gets converted
to binary.
▪ However for human reading we have base-10 (decimal), base-8 (octal) and
base-16 (hexadecimal).
▪ Summary:
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
Hexadecim e,f or
1x161+7x160 17
al 0,1,2,3,4,5,6,7,8,9,A,B,C,
D,E,F
STANDARD I/O
C number representation

▪ 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.
▪ e.g.
int iNum = 187; // decimal constant
STANDARD I/O

▪ To specify an octal constant, begin the specification with


0, followed by a sequence of digits in the range 0 through
7. e.g.
int iNum = 0774; // octal constant
int jNum = 0597; // 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 jNum = 0X4F2A; // equal to iNum
STANDARD I/O
▪ To specify an unsigned type, use either the u or U
suffix.
▪ To specify a long type, use either the l or L suffix.
For 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 the LL, ll or


i64 suffix.
STANDARD I/O
Byte Wide
Description
character character
scanf() wscanf()
reads formatted byte/wchar_t input from stdin (standard input), a file
fscanf() fwscanf()
stream or a buffer
sscanf() swscanf()
vscanf() vwscanf()
reads formatted input byte/wchar_t from stdin,
vfscanf() vfwscanf()
a file stream or a buffer using variable argument list
vsscanf() vswscanf()
printf() wprintf()
Formatted fprintf() fwprintf() prints formatted byte/wchar_t output to stdout (standard output), a file
input/output sprintf() swprintf() stream or a buffer
snprintf()
vwprintf()
vprintf() vfwprintf()
vfprintf() vswprintf() prints formatted byte/wchar_t output to stdout,
vsprintf() a file stream, or a buffer using variable argument list
vsnprintf()

fgetc() fgetwc()
reads a byte/wchar_t from a file stream
getc() getwc()
fgets() fgetws() reads a byte/wchar_t line from a file stream
fputc() fputwc()
writes a byte/wchar_t to a file stream
putc() putwc()
Unformatted fputs() fputws() writes a byte/wchar_t string to a file stream
input/output
getchar() getwchar() reads a byte/wchar_t from stdin
gets() N/A reads a byte string from stdin (deprecated in C99, obsolete in C11)
putchar() putwchar() writes a byte/wchar_t to stdout
puts() N/A writes a byte string to stdout
fopen() opens a file
freopen() opens a different file with an existing stream
fflush() synchronizes an output stream with the actual file
STANDA
fclose() closes a file
RD I/O setbuf() sets the buffer for a file stream
File access setvbuf() sets the buffer and its size for a file stream
switches a file stream between wide character I/O and narrow
fwide()
character I/O
Direct fread() reads from a file
input/output fwrite() writes to a file
ftell() returns the current file position indicator
fgetpos gets the file position indicator
File
fseek() moves the file position indicator to a specific location in a file
positioning
fsetpos() moves the file position indicator to a specific location in a 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 error
perror()
to stderr
remove() erases a file
Operations rename() renames a file
on files tmpfile() returns a pointer to a temporary file
STANDARD I/O
The printf() family

▪ Loads the data from the given locations, converts them to


character string equivalents and writes the results:
a) to stdout (standard output) such as printf() and
wprintf().
b) to a file stream stream such as fprintf() and
fwprintf().
c) to a character string buffer such as sprintf() and
swprintf().
d) At most (buf_size – 1) characters are written such
as snprintf(). The resulting character string will be
terminated with a null character, unless buf_size is
zero.

STANDARD I/O
Implementation dependant example (Microsoft Visual C++):

Same as printf() but use the locale parameter


_printf_l()
passed in instead of the current thread locale.

Same as wprintf() but use the locale parameter


_wprintf_l()
passed in instead of the current thread locale.

printf_s(),
_printf_s_l(), Same as printf(), _printf_l(), wprintf()
wprintf_s(), and _wprintf_l() but with security enhancements
_wprintf_s_l()
STANDARD I/O
Sample function

Name printf()
Syntax int printf(const char *format [,argument]...);

format - Format control.


argument - Optional arguments.
... (additional arguments) - Depending on the format string, the function may
expect a sequence of additional arguments, each containing a value to be used
Parameters to replace a format specifier in the format string (or a pointer to a storage
location, for n).
There should be at least as many of these arguments as the number of values
specified in the format specifiers. Additional arguments are ignored by the
function.
Formats and prints a series of characters and values to the standard output
Usage stream, stdout. If arguments follow the format string, the format string must
contain specifications that determine the output format for the arguments
Returns the number of characters printed (excluding the null byte used to end
Return
output to strings), or a negative value if an error occurs. If format is NULL, the
value invalid parameter handler is invoked
printf("%ld, %#X, %-7d, %7s, %8.5f \n", 3, 120, 11, "STRING",
Example 1.234);
Remarks Also called a variadic function.
STANDARD I/O
The syntax for format specifications fields, used in printf(), wprintf() and related functions.
▪ A format specification, which consists of optional and required fields, has the following form:

% [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.


▪ 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); 33 ,44 ,
printf("%7s\n", "123456"); 123456
printf("%4f\n", 41.1234); 41.123400
printf("%8.5f\n", 3.234); 3.23400
printf("%.3f\n", 15.4321); 15.432
printf("%hd\n", 7); 7
printf("%ld\n", 9); 9
STANDARD I/O
▪ Each field of the format specification is a single character or
a number signifying a particular format option.
▪ The simplest format specification contains only the percent
sign and a type character, for example:

printf("A string: %s", "This is a string")

▪ 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 %%.
▪ The optional fields, which appear before the type
character, control other aspects of the formatting, as
follows:
STANDARD I/O
Optional character or characters that control justification of output and
printing of signs, blanks, decimal points, and octal and hexadecimal
flags prefixes (refer to the "Flag Characters" table). More than one flag can
appear in a format specification.

Optional number that specifies the minimum number of characters


Width output (refer to the printf() Width Specification.

Optional number that specifies the maximum number of characters


printed for all or part of the output field, or the minimum number of digits
precision printed for integer values (refer to the Precision Specification table).

Optional prefixes to type that specify the size of argument (refer to Size
h | l | ll | I | I32 |
Specification table).
I64
Required character that determines whether the associated argument is
interpreted as a character, a string, or a number (refer to the printf()
type
Type Field Characters table).
STANDARD I/O Flag Directives

Flag Characters
It is the first optional field of the format specification after % sign.
Is a character that justifies output and prints signs, blanks, decimal points, octal and hexadecimal prefixes. More
than one flag directive may appear in a format specification.
Flag Meaning Default
– Left align the result within the given field width. Right align.
Sign appears only for
+ Prefix the output value with a sign (+ or –) if the output value is of a signed type. negative signed
values (–).
If width is prefixed with 0, zeros are added until the minimum width is reached. If 0
and – appear, the 0 is ignored. If 0 is specified with an integer format (i, u, x, X, o,
0 No padding.
d) and a precision specification is also present (for example, %04.d), the 0 is
ignored.
A blank. Prefix the output value with a blank if the output value is signed and
' ' No blank appears.
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
No blank appears.
with 0, 0x, or 0X, respectively.
Decimal point
When used with the e, E, f, a or A format, the # flag forces the output value to
appears only if digits
# contain a decimal point in all cases.
follow it.

Decimal point
When used with the g or G format, the # flag forces the output value to contain a
appears only if digits
decimal point in all cases and prevents the truncation of trailing zeros.
follow it. Trailing
Ignored when used with c, d, i, u, or s.
zeros are truncated.
STANDARD I/O

Code example: Output example:

%#x: 0x78
printf("%%#x: %#x\n", 120 );
%x: c
printf("%%x: %x\n", 12 ); %#X: 0X78
printf("%%#X: %#X\n", 120 ); %X: C
printf("%%X: %X\n", 12 ); %#o: 0170
printf("%%#o: %#o\n", 120 ); %o: 14
printf("%%o: %o\n", 12 ); %#2f: 120.567000
printf("%%#2f: %#2f\n", 120.567 ); %g: 3.14159
printf( "%%g: %g\n", 3.1415926 ); %g: 9.3e+007
printf( "%%g: %g\n", 93000000.0 ); %G: 9.3E+007
printf( "%%G: %G\n", 93000000.0 ); %07d: 0000102
printf("%%07d: %07d\n", 102 ); +102
printf("%+d\n", 102 ); %-7d,%-5d,: 11 ,22 ,
printf("%%-7d,%%-5d,: %-7d,%-5d,\n", 11, 22 ); %#010x: 0x00000079
printf("%%#010x: %#010x\n", 121 ); %#010X: 0X00000079
STANDARD I/O
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.
STANDARD I/O
Width Specification
● 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. printf("%0*d", 5, 3); /* 00003 is output */
● 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,


STANDARD I/O
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.
● 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 */


STANDARD I/O
Precision Specification

● If the precision specification is an asterisk (*),


an int argument from the argument list supplies
the value.
● The precision argument must precede the value
being formatted in the argument list.
● The type determines the interpretation of
precision and the default when precision is
omitted, as shown in the following table.
STANDARD I/O
How Precision Values Affect Type
Type Meaning Default
Default precision is 6. If precision is 0,
a, A The precision specifies the number of digits after the point. no point is printed unless the # 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 less than
d, i, u,
precision, the output value is padded on the left with zeros. The Default precision is 1.
o, x, X
value is not truncated when the number of digits exceeds
precision.
Default precision is 6; if precision is 0
The precision specifies the number of digits to be printed after or the period (.) appears without a
e, E
the decimal point. The last printed digit is rounded. number following it, no decimal point is
printed.
The precision value specifies the number of digits after the Default precision is 6; if precision is 0,
decimal point. If a decimal point appears, at least one digit or if the period (.) appears without a
f
appears before it. The value is rounded to the appropriate number following it, no decimal point is
number of digits. printed.
The precision specifies the maximum number of significant Six significant digits are printed, with
g, G
digits printed. any trailing zeros truncated.
The precision specifies the maximum number of characters to Characters are printed until a null
s, S
be printed. Characters in excess of precision are not printed. character is encountered.
STANDARD I/O
How Precision Values Affect Type, continue…

If the argument corresponding to a floating-


point specifier is infinite, indefinite, or NAN 9
(Not-A-Number), printf() gives the
following output.
Value Output

+ infinity 1.#INFrandom-digits
– infinity –1.#INFrandom-digits
Indefinite (same as quiet NaN) digit.#INDrandom-digits
NAN digit.#NANrandom-digits
STANDARD I/O
Code Example:

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" );
STANDARD I/O
Output example:

%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
STANDARD I/O
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.
● These prefixes are Microsoft (and some other
implementations) extensions example and are not
ANSI-compatible.
STANDARD I/O
Size Specification
Size prefixes for printf() and wprintf() format-type specifiers
To specify Use prefix With type specifier

long int l (lowercase L) d, i, o, x, or X

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 64-bit I d, i, o, x, or X
platforms)
STANDARD I/O
Size Specification
With type
To specify Use prefix
specifier

size_t (that is, unsigned __int32 on 32-bit o, u, x,


I
platforms, unsigned __int64 on 64-bit platforms) or X
long double l or L f
Single-byte character with printf() functions h c or C
Single-byte character with wprintf() functions h c or C
Wide character with printf() functions l c or C
Wide character with wprintf() functions l c or C
Single-byte – character string with printf() functions h s or S
Single-byte – character string with wprintf()
h s or S
functions
Wide-character string with printf() functions l s or S
Wide-character string with wprintf() functions l s or S
Wide character w c
STANDARD I/O
Size Specification

● Thus to print single-byte or wide-characters with


printf() functions and wprintf() functions, use
format specifiers as follows.
To print character With format
Use function
as specifier
single byte printf() c, hc, or hC
single byte wprintf() C, hc, or hC
wide wprintf() c, lc, lC, or wc
wide printf() C, lc, lC, or wc
● To print strings with printf() functions and
wprintf() functions, use the prefixes h and l
analogously with format type-specifiers s and S.
STANDARD I/O

Code example:

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 );
STANDARD I/O
Output example:

%hd: 3
%ld: 3
%ls: This is a wide
string
%Lg: 3.14159
STANDARD I/O
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.
STANDARD I/O
Type character
printf() Type Field Characters
Character Type Output format
When used with printf() functions, specifies a single-byte character;
c int
when used with wprintf() functions, specifies a wide 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
doubl d is a single decimal digit, dddd is one or more decimal digits, dd[d] is
e
e two or three decimal digits depending on the output format and size of
the exponent, and sign is + or –.
doubl Identical to the e format except that E rather than e introduces the
E
e exponent.
Signed value having the form [ – ]dddd.dddd, where dddd is one or
doubl more decimal digits. The number of digits before the decimal point
f
e depends on the magnitude of the number, and the number of digits
STANDARD I/O
Type character
Char
Type Output format
acter
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 when the exponent of the value is less than
g double
–4 or greater than or equal to the precision argument. Trailing zeros are truncated, and the
decimal point appears only if one or more digits follow it.
Identical to the g format, except that E, rather than e, introduces the exponent (where
G double
appropriate).
p Pointer to void Displays the argument as an address in hexadecimal digits (as if by %#x or %#lx)
Pointer to Number of characters successfully written so far to the stream or buffer; this value is
n
integer stored in the integer whose address is given as the argument.
Signed hexadecimal double precision floating point value having the form
[−]0xh.hhhh p±dd, where h.hhhh are the hex digits (using lower case letters) of the
a double
mantissa, and dd are one or more digits for the exponent. The precision specifies the
number of digits after the point.
Signed hexadecimal double precision floating point value having the form
[−]0Xh.hhhh P±dd, where h.hhhh are the hex digits (using capital letters) of the
A double
mantissa, and dd are one or more digits for the exponent. The precision specifies the
number of digits after the point.
When used with printf() functions, specifies a single-byte-character string; when used
s String with wprintf() functions, specifies a wide-character string. Characters are displayed up
to the first null character or until the precision value is reached.
STANDARD I/O

Source code for C program


examples in txt file format:

1. Example 0
2. Example 1
3. Example 2
STANDARD I/O
scanf() family

● Read formatted data from a variety of


standard input stream which are:
1. data from stdin (standard input) such as
scanf() and wscanf()
2. data from file stream 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.
STANDARD I/O
● Implementation dependant (Microsoft visual C
++) example is listed in the following table.

Function Description
Same as scanf() except they use the locale
_scanf_l() parameter passed in instead of the current thread
locale.

Same as wscanf() except they use the locale


_wscanf_l() parameter passed in instead of the current thread
locale.

_scanf_s_l() Same as _scanf_l() with security enhancements.

_wscanf_s_l() Same as _wscanf_l() with security enhancements


STANDARD I/O
Function example
Name scanf()
int scanf(const char *format
Syntax
[,argument]...);
format - pointer to a null-terminated character string
specifying how to read the input or a format control string.
Parameters
argument - optional arguments.
... - receiving 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
were read but not assigned. A return value of 0 indicates
Return 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.
STANDARD I/O
Format Specification Fields for scanf() and wscanf() family

▪ Describes the symbols used to tell the scanf() functions how to parse the input
stream, such as from stdin, into values that are inserted into (program)
variables.
▪ 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.

▪ Example:

scanf("%f", &x);
scanf("%4f", &x);
scanf("%ls", &x);
scanf("%*d %[0123456789]", name);
STANDARD I/O
1. The format argument specifies the interpretation of the input and
can contain one or more of the following:
a. White-space characters: blank (' '); tab ('\t'); or newline ('\n'). A
white-space character causes scanf() to read, but not 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.
b. Non-white-space characters: except for the percent sign (%). A
non-white-space character causes scanf() to read, but not
store, a matching non-white-space character. If the next
character in the input stream does not match, scanf()
terminates.
c. 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.
STANDARD I/O
● 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.
STANDARD I/O
● 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.
● Each field of the format specification is a single character or
a number signifying a particular format option.
● 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.
● The simplest format specification contains only the percent
sign and a type character. e.g. scanf(%s)
STANDARD I/O
● 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.
STANDARD I/O
scanf() Width Specification

● format strings in the scanf() family of functions.


● These functions normally assume the input stream is divided into a
sequence of tokens.
● Tokens are separated by whitespace (space, tab, or newline), or in the
case of numerical types, by the natural end of a numerical data type as
indicated by the first character that cannot be converted into numerical
text.
● However, the width specification may be used to cause 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.
● Such characters are referred to as the size prefix. e.g.
scanf("%4f", &x);
STANDARD I/O
The Width Field

● The width field is a positive decimal integer


controlling the maximum number of characters
to be read for that field.
● No more than width characters are converted
and stored at the corresponding argument.
● Fewer than width characters may be read if a
whitespace character (space, tab, or newline)
or a character that cannot be converted
according to the given format occurs before
width is reached.
STANDARD I/O
The Size Prefix

1. 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).
2. Used with type characters in scanf() or wscanf()
functions to specify interpretation of arguments as
shown in the following table.
3. The type prefix I64 is a Microsoft extension example
and is not ANSI compatible.
4. The h, l, and L prefixes are Microsoft extensions
when used with data of type char.
5. The type characters and their meanings are
described in the "Type Characters for scanf()
functions" table.
STANDARD I/O
Size Prefixes for scanf() and wscanf() Format-Type Specifiers
To specify Use prefix With type specifier
double l e, E, f, g, or G
long double (same as double) L e, E, f, g, or G
long int l d, i, o, x, or X
long unsigned int l u
long long ll d, i, o, x, or X
short int h d, i, o, x, or X
short unsigned int h u
__int64 I64 d, i, o, u, x, or X
Single-byte character with scanf() h c or C
Single-byte character with wscanf() h c or C
Wide character with scanf() l c or C
Wide character with wscanf() l c, or C
Single-byte character string with h s or S
scanf()
Single-byte character string with h s or S
wscanf()
Wide-character string with scanf() l s or S
STANDARD I/O

▪ The following examples use h and l with


scanf() functions and wscanf()
functions:

scanf( "%ls", &x ); // read a


wide-character string
wscanf( "%hC", &x ); // read a
single-byte character
STANDARD I/O
Reading Undelimited strings

● To read strings not delimited by whitespace characters, a set


of characters in brackets ([]) can be substituted for the s
(string) type character.
● The set of characters in brackets is referred to as a control
string.
● The corresponding input field is read up to the first character
that does not appear in the control string.
● If the first character in the set is a caret (^), the effect is
reversed: The input field is read up to the first character that
does appear in the rest of the character set.
● %[a-z] and %[z-a] are interpreted as equivalent to %
[abcde...z].
● This is a common scanf() function extension, but note that
the ANSI standard does not require it.
STANDARD I/O
▪ Some implementation supports a nonstandard extension that causes the library to
dynamically allocate a string of sufficient size for input strings for the %s and %a[range]
conversion specifiers.
▪ To make use of this feature, specify a as a length modifier (thus %as or %a[range]). The
caller must free the returned string, as in the following example:
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"):
}
▪ (the a is interpreted as a specifier for floating-point numbers).
STANDARD I/O
Reading Unterminated strings

▪ To store a string without storing a


terminating null character ('\0'), use the
specification %nc where n is a decimal
integer.
▪ The c type character indicates that the
argument is a pointer to a character array.
▪ The next n characters are read from the
input stream into the specified location, and
no null character ('\0') is appended.
▪ If n is not specified, its default value is 1.
STANDARD I/O
When scanf() 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.
▪ The conflicting character, if there is one, is considered unread
and is the first character of the next input field or the first
character in subsequent read operations on the input stream.
STANDARD I/O

Type Field Characters for scanf() family

▪ 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.
STANDARD I/O
Size argument in secure
Character Type of input expected Type of argument
version?

Character. When used with scanf()


functions, specifies single-byte character;
when used with wscanf() functions, Pointer to char when
specifies wide character. White-space used with scanf() Required. Size does not
c characters that are ordinarily skipped are functions, pointer to include space for a null
read when c is specified. To read next wchar_t when used with terminator.
non-white-space single-byte character, wscanf() functions.
use %1s; to read next non-white-space
wide character, use %1ws.

Opposite size character. When used with


scanf() functions, specifies wide
character; when used with wscanf() Pointer to wchar_t when
functions, specifies single-byte character. used with scanf() Required. Size argument
C White-space characters that are ordinarily functions, pointer to char does not include space for
skipped are read when C is specified. To when used with wscanf() a null terminator.
read next non-white-space single-byte functions.
character, use %1s; to read next non-
white-space wide character, use %1ws.

d Decimal integer. Pointer to int. No.


STANDARD I/O
Continue…
d Decimal integer. Pointer to int. No.
An integer. Hexadecimal if the input Pointer to int. No.
string begins with "0x" or "0X", octal if
i the string begins with "0", otherwise
decimal.
o Octal integer. Pointer to int. No.

u Unsigned decimal integer. Pointer to unsigned int. No.

x Hexadecimal integer. Pointer to int. No.


Floating-point value consisting of Pointer to float. No.
optional sign (+ or –), series of one or
e , E, more decimal digits containing
f, g, G decimal point, and optional exponent
("e" or "E") followed by an optionally
signed integer value.
No input read from stream or buffer. Pointer to int, into which is stored No.
number of characters successfully
read from stream or buffer up to that
n
point in current call to scanf()
functions or wscanf() functions.
STANDARD I/O
Continue…
String, up to first white-space When used with scanf() Required. Size includes
character (space, tab or functions, signifies single-byte space for a null
newline). To read strings not character array; when used with terminator.
delimited by space characters, wscanf() functions, signifies
use set of square brackets ([ ]), wide-character array. In either
s as discussed in scanf() case, character array must be
Width Specification. large enough for input field plus
terminating null character,
which is automatically
appended.
Opposite-size character string, When used with scanf() Required. Size includes
up to first white-space functions, signifies wide- space for a null
character (space, tab or character array; when used with terminator.
newline). To read strings not wscanf() functions, signifies
delimited by space characters, single-byte-character array. In
S use set of square brackets ([ ]), either case, character array
as discussed in scanf() must be large enough for input
Width Specification. field plus terminating null
character, which is
automatically appended.
STANDARD I/O
● The a and A specifiers are not available with scanf().
● The size arguments, if required, should be passed in
the parameter list immediately following the argument
they apply to. For example, the following code:

char string1[11], string2[9];


scanf("%10s %8s", string1, 11, string2, 9);

● reads a string with a maximum length of 10 into


string1, and a string with a maximum length of 8 into
string2.
● The buffer sizes should be at least one more than the
width specifications since space must be reserved for
the null terminator.
STANDARD I/O
● The format string can handle single-byte or wide character
input regardless of whether the single-byte character or
wide-character version of the function is used.
● Thus, to read single-byte or wide characters with scanf()
and wscanf() functions, use format specifiers as follows:

To read character as Use this function With these format


specifiers
single byte scanf() functions c, hc, or hC
single byte wscanf() functions C, hc, or hC
wide wscanf() functions c, lc, or lC
wide scanf() functions C, lc, or lC
● To scan strings with scanf() functions, and wscanf()
functions, use the above table with format type-specifiers s
and S instead of c and C.
STANDARD I/O
Program examples:

1.Example 1: Try the following inputs: 58 71.3


A t byte characters
2.Example 2:
3.Example 3: See next slide (character and
string issues with scanf())
STANDARD I/O
Run the following program and precede the %c’s with spaces.

#include <stdio.h>

int main(void)
{
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;
}
STANDARD I/O
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 the YES
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 the YES/
format strings for the characters (e.g. scanf("%c %d", &a, NO
&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 the TRUE
%c’s, true or false?

Format strings for floats (%f) behave like integers


and those for strings (%s) behave like characters.
C Operators, Operands,
Expressions & Statements
C OPERATORS, OPERANDS, EXPRESSION & STATEMENTS
▪ Operators are symbols which take one or more operands or
expressions and perform arithmetic or logical computations.
▪ Operands are variables or expressions which are used in
conjunction with operators to evaluate the expression.
▪ Combination of operands and operators form an expression.
▪ Expressions are sequences of operators, operands, and
punctuators that specify a computation.
▪ Evaluation of expressions is based on the operators that the
expressions contain and the context in which they are used.
▪ Expression can result in a value and can produce side
effects.
▪ A side effect is a change in the state of the
execution environment, value that results from the
evaluation of an expression.
C OPERATORS

▪ An expression is any valid set of literals, variables, operators,


operands and expressions that evaluates to a single value.
▪ This value can be a number, a string or a logical value.
▪ For instance a = b + c; denotes an expression in which there are 3
operands a, b, c and two operator + and =.
▪ A statement, the smallest independent computational unit, specifies
an action to be performed.
▪ In most cases, statements are executed in sequence.
▪ The number of operands of an operator is called its arity.
▪ Based on arity, operators are classified as nullary (no operands),
unary (1 operand), binary (2 operands), ternary (3 operands).
C OPERATORS
Operators Description Example Usage
Postfix operators
Function call operator. A function
call is an expression containing
the function name followed by the sumUp(inum1,
function call operator, (). If the inum2)
function has been defined to
displayName()
receive parameters, the values
() that are to be sent into the function student(cname,
iage, caddress)
are listed inside the parentheses
of the function call operator. The Calculate(length,
argument list can contain any wide + 7)
number of expressions separated
by commas. It can also be empty.
C OPERATORS
Array subscripting operator. A postfix
expression followed by an expression in [ ]
(brackets) specifies an element of an #include <stdio.h>

array. The expression within the brackets int main(void)


is referred to as a subscript. The first {
[] element of an array has the subscript int a[3] = { 11, 12, 33 };
printf("a[0] = %d\n",
zero. In array, the index tells the distance a[0]);
from the starting element. So, the first return 0;
element is at 0 distance from the starting }
element. So, that's why array start from 0.

Dot operator used to access class,


. objectVar.memberOfStructUnion
structure, or union members type.

Arrow operator used to access class,


-> structure or union members using a aptrTo->memberOfStructUnion
pointer type.
C OPERATORS

Unary Operators
Unary plus maintains the value of the
+ operand. Any plus sign in front of a +aNumber
constant is not part of the constant.
Unary minus operator negates the
value of the operand. For example, if
num variable has the value 200, -num
- has the value -200. Any minus sign in
-342
front of a constant is not part of the
constant.
C OPERATORS
You can put the ++/-- before or after the operand. If it appears before the
operand, the operand is incremented/decremented. The incremented value is
then used in the expression. If you put the ++/-- after the operand, the value
of the operand is used in the expression before the operand is incremented/
decremented.
Post-increment. After the result is obtained, the
++ aNumber++
value of the operand is incremented by 1.
Post-decrement. After the result is obtained, the
-- aNumber--
value of the operand is decremented by 1.
Pre-increment. The operand is incremented by 1
++ ++yourNumber
and its new value is the result of the expression.
Pre-decrement. The operand is decremented by 1
-- --yourNumber
and its new value is the result of the expression.

int i = 5, int b = ++i In this case, 6 is assigned to b first and then increments to 7 and so on

int i = 5, int b = i++ In this case, 5 is assigned to b first and then increments to 6 and so on
C OPERATORS
The address-of operator (&) gives the address of
its operand. The operand of the address-of
operator can be either a function designator or an
l-value that designates an object that is not a bit
&addressOfDat
& field and is not declared with the register storage-
a
class specifier.
The result of the address operation is a pointer to
the operand. The type addressed by the pointer
is the type of the operand.
The indirection operator (*) accesses a value
indirectly, through a pointer. The operand must
be a pointer value. The result of the operation is
* the value addressed by the operand; that is, the *aPointerTo
value at the address to which its operand points.
The type of the result is the type that the operand
addresses.
C OPERATORS

sizeof operator for sizeof


sizeof
expressions 723
sizeof( sizeof operator for sizeof(ch
) types ar)
Explicit conversion of
(type) the type of an object in
cast-
a specific situation. This (float)i
expressio
n is also call automatic
promotion.
C OPERATORS
Multiplicative Operators

* The multiplication operator causes its two operands to be multiplied. p = q * r;

The division operator causes the first operand to be divided by the second. If two
integer operands are divided and the result is not an integer, it is truncated
according to the following rules:
1.The result of division by 0 is undefined according to the ANSI C standard. The

/ Microsoft C compiler generates an error at compile time or run time.


2.If both operands are positive or unsigned, the result is truncated toward 0.
a = b / c;

3.If either operand is negative, whether the result of the operation is the largest

integer less than or equal to the algebraic quotient or is the smallest integer
greater than or equal to the algebraic quotient is implementation defined.
The result of the remainder operator is the remainder when the first operand is
divided by the second. When the division is inexact, the result is determined by the
following rules:
% 1.If the right operand is zero, the result is undefined.

2.If both operands are positive or unsigned, the result is positive.


x = y % z;

3.If either operand is negative and the result is inexact, the result is implementation

defined.
C OPERATORS
Addition and subtraction Operators
+ addition d = e + f
- subtraction r = s – t;
▪ The operands can be integral or floating values. Some additive
operations can also be performed on pointer values, as outlined
under the discussion of each operator.
▪ The additive operators perform the usual arithmetic conversions on
integral and floating operands. The type of the result is the type of the
operands after conversion.
▪ Since the conversions performed by the additive operators do not
provide for overflow or underflow conditions, information may be lost
if the result of an additive operation cannot be represented in the type
of the operands after conversion.

Program example: assignment, add, subtract, multiply, divide and modulus


C OPERATORS

▪ For relational expression, 0 is FALSE, 1 is


TRUE.
▪ Any numeric value is interpreted as either
TRUE or FALSE when it is used in a C / C+
+ expression or statement that is expecting
a logical (true or false) value. The rules
are:

1. A value of 0 represents FALSE.


2. Any non-zero (including negative numbers)
value represents TRUE.
Program example: true, false and negate
C OPERATORS
Relational Inequality Operators
The relational operators compare two operands and determine the validity of a
relationship.
Specifies whether the value of the left operand is less than
the value of the right operand. The type of the result is int
< and has the value 1 if the specified relationship is true, and 0 i < 7
if false.
Specifies whether the value of the left operand is greater
than the value of the right operand. The type of the result is
> int and has the value 1 if the specified relationship is true, j > 5

and 0 if false.
Specifies whether the value of the left operand is less than or
equal to the value of the right operand. The type of the result
<= is int and has the values 1 if the specified relationship is k <= 4

true, and 0 if false.


Specifies whether the value of the left operand is greater
than or equal to the value of the right operand. The type of
>= the result is int and has the values 1 if the specified p >= 3

relationship is true, and 0 if false.


C OPERATORS
Relational Equality Operators
The equality operators, like the relational operators, compare two operands for
the validity of a relationship.
Indicates whether the value of the left operand is equal to
the value of the right operand. The type of the result is
int and has the value 1 if the specified relationship is
true, and 0 if false. The equality operator (==) should not
be confused with the assignment (=) operator. For
example: nChoice ==
== if (x == 4) evaluates to true (or 1) if x is equal to four. 'Y'
while
if (x = 4) is taken to be true because (x = 4) evaluates to a
nonzero value (4). The expression also assigns the value
4 to x.
Indicates whether the value of the left operand is not
equal to the value of the right operand. The type of the nChoice !=
!= result is int and has the value 1 if the specified 'Y'
relationship is true, and 0 if false.
C OPERATORS
Expressions Evaluates as
(3 == 3) && (4 ! True (1) because both operands
= 3) are true
(4 > 2) || (7 < True (1) because (either) one
11) operand/expression is true
(3 == 2) && (7 False (0) because one operand
== 7) is false
True (1) because the expression
! (4 == 3)
is false
NOT(FALSE) = TRUE
NOT(TRUE) = FALSE

Program example: less-than, greater-than, less-than and equal-to, greater-than


and equal-to, not-equal, equal and assignment operators
C OPERATORS
Logical NOT Operator (unary)
Logical not operator. Produces
value 0 if its operand or
expression is true (nonzero) and
!(4 ==
the value 1 if its operand or
! 2)
expression is false (0). The result
!x
has an int type. The operand
must be an integral, floating, or
pointer value.
Operand (or expression) Output
!0 1 ( T )
!1 0 ( F )
C OPERATORS
Logical AND Operator
Indicates whether both operands are true.
If both operands have nonzero values, the result has the value 1.
Otherwise, the result has the value 0. The type of the result is
int. Both operands must have an arithmetic or pointer type. The
usual arithmetic conversions on each operand are performed.
&& The logical AND (&&) should not be confused with the bitwise AND
x && y

(&) operator. For example:


1 && 4 evaluates to 1 (True && True = True)
while
1 & 4 (0001 & 0100 = 0000) evaluates to 0

Operand1 Operand2 Output


0 0 0 ( F )
0 1 0 ( F )
1 0 0 ( F )
1 1 1 ( T )
C OPERATORS
Logical OR Operator
Indicates whether either operand is true. If either of the
operands has a nonzero value, the result has the value 1.
Otherwise, the result has the value 0. The type of the result is
int. Both operands must have a arithmetic or pointer type.
The usual arithmetic conversions on each operand are
|| performed. x || y
The logical OR (||) should not be confused with the bitwise OR
(|) operator. For example:

1 || 4 evaluates to 1 (or True || True = True)


while 1 | 4 (0001 | 0100 = 0101) evaluates to 5

Operand1 Operand2 Output


0 0 0 ( F )
0 1 1 ( T )
1 0 1 ( T )
1 1 1 ( T )
C OPERATORS
Conditional Operator (ternary)
The first operand/expression is evaluated, and
its value determines whether the second or
third operand/expression is evaluated:
1.If the value is true, the second operand/

expression is evaluated.
2.If the value is false, the third operand/
size != 0 ?
?:
expression is evaluated. size : 0
The result is the value of the second or third
operand/expression. The syntax is:

First operand ? second operand :


third operand
C OPERATORS
▪ The compound assignment operators
consist of a binary operator and the simple
assignment operator.
▪ They perform the operation of the binary
operator on both operands and store the
result of that operation into the left
operand.
▪ The following table lists the simple and
compound assignment operators and
expression examples:
C OPERATORS
Simple Assignment Operator
▪ The simple assignment operator has the
following form:
lvalue = expr
▪ The operator stores the value of the right
= operand expr in the object designated by i = 5 + x;
the left operand lvalue.
▪ The left operand must be a modifiable
lvalue.
▪ The type of an assignment operation is
the type of the left operand.
C OPERATORS
Compound
Assignment Example Equivalent expression
Operator
identifier operator= entity represents
identifier = identifier operator entity
+= nindex += 3 index = nindex + 3
-= *(paPter++) -= 1 * paPter = *( paPter ++) - 1
*= fbonus *= fpercent fbonus = fbonus * fpercent
/= ftimePeriod /= fhours ftimePeriod = ftimePeriod / fhours
%= fallowance %= 80 fallowance = fallowance % 80
<<= iresult <<= inum iresult = iresult << inum
>>= byleftForm >>= 1 byleftForm = byleftForm >> 1
&= bybitMask &= 2 bybitMask = bybitMask & 2
^= itestSet ^= imainTest itestSet = itestSet ^ imainTest
|= bflag |= bonBit bflag = bflag | bonBit
C OPERATORS
Comma Operator
A comma expression contains two operands of any type separated by a comma and
has left-to-right associativity. The left operand is fully evaluated, possibly producing
side effects, and its value, if there is one, is discarded. The right operand is then
evaluated. The type and value of the result of a comma expression are those of its
right operand, after the usual unary conversions. In some contexts where the comma
character is used, parentheses are required to avoid ambiguity. The primary use of
the comma operator is to produce side effects in the following situations:
1.Calling a function.

2.Entering or repeating an iteration loop.

, 3.Testing a condition.

4.Other situations where a side effect is required but the result of the expression is not

immediately needed.
The use of the comma token as an operator is distinct from its use in function calls
and definitions, variable declarations, enum declarations, and similar constructs,
where it acts as a separator.
Because the comma operator discards its first operand, it is generally only useful
where the first operand has desirable side effects, such as in the initializer or the
counting expression of a for loop.
C OPERATORS
▪ The following table gives some examples of the uses of the comma
operator.

Statement Effects
A for statement in which i is incremented and func()
for (i=0; i<4; ++i, func());
is called at each iteration.
An if statement in which function func() is called,
variable i is incremented, and variable i is tested against
a value. The first two expressions within this comma
if (func(), ++i, i>1 )
expression are evaluated before the expression i>1.
{ /* ... */ }
Regardless of the results of the first two expressions, the
third is evaluated and its result determines whether the
if statement is processed.
A function call to func1() in which iaArg is
incremented, the resulting value is passed to a function
func2(), and the return value of func2() is passed to
func1((++iaArg, func2(iaArg)));
func1(). The function func1() is passed only a single
argument, because the comma expression is enclosed in
parentheses within the function argument list.
int inum=3, inum2=7, inum3 = 2; Comma acts as separator, not as an operator.
C OPERATORS
Bitwise (complement) NOT Operators
The ~ (bitwise negation) operator yields the bitwise
(one) complement of the operand. In the binary
representation of the result, every bit has the
opposite value of the same bit in the binary
~
representation of the operand. The operand must
have an integral type. The result has the same type
as the operand but is not an lvalue (left value). The
symbol used called tilde.
Suppose byNum variable represents the decimal value 8. The 16-bit binary
representation of byNum is:
00000000 00001000
The expression ~byNum yields the following result (represented here as a
16-bit binary number):
11111111 11110111
C OPERATORS
Bitwise Shift Operators
Left shift operator, shift their first operand left (<<) by the
<< nbits << nshiftSize
number of positions specified by the second operand.
Right shift operator, shift their first operand right (>>) by
>> nbits >> nshiftSize
the number of positions specified by the second operand.
▪ Both operands must be integral values. These operators perform the usual arithmetic
conversions; the type of the result is the type of the left operand after conversion.
▪ For leftward shifts, the vacated right bits are set to 0. For rightward shifts, the vacated left bits are
filled based on the type of the first operand after conversion. If the type is unsigned, they are set
to 0. Otherwise, they are filled with copies of the sign bit. For left-shift operators without overflow,
the statement:

expression1 << expression2

▪ is equivalent to multiplication by 2expression2. For right-shift operators:

expression1 >> expression2

▪ is equivalent to division by 2expression2 if expression1 is unsigned or has a nonnegative value.


▪ The result of a shift operation is undefined if the second operand is negative, or if the right
operand is greater than or equal to the width in bits of the promoted left operand.
▪ Since the conversions performed by the shift operators do not provide for overflow or underflow
conditions, information may be lost if the result of a shift operation cannot be represented in the
type of the first operand after conversion.
C OPERATORS

Program example: bitwise shift left, bitwise shift right and bitwise-NOT operators
C OPERATORS
Bitwise AND Operator
▪ The & (bitwise AND) operator compares each bit of its first operand to
the corresponding bit of the second operand. If both bits are 1's, the
corresponding bit of the result is set to 1. Otherwise, it sets the
corresponding result bit to 0.
▪ Both operands must have an integral or enumeration type. The usual
arithmetic conversions on each operand are performed. The result has
the same type as the converted operands.
& ▪ Because the bitwise AND operator has both associative and
commutative properties, the compiler can rearrange the operands in an
expression that contains more than one bitwise AND operator.
▪ The bitwise AND (&) should not be confused with the logical AND. (&&)
operator. For example:

1 & 4 evaluates to 0 (0001 & 0100 = 0000) while


1 && 4 evaluates to true [True && True = True]
C OPERATORS
C OPERATORS
C OPERATORS
OPERATOR PRECEDENCE
▪ Considerthe following arithmetic
operation:
- left to right
6 / 2 * 1 + 2 = 5
- right to left Inconsistent
6/2 * 1 + 2 = 1 answers!
- using parentheses
= 6 / (2 * 1) + 2
= (6 / 2) + 2
= 3 + 2
= 5
OPERATOR PRECEDENCE

▪ Operator precedence: a rule used to clarify


unambiguously which operations (operator and
operands) should be performed first in the given
(mathematical) expression.
▪ Use precedence levels that conform to the order
commonly used in mathematics.
▪ However, parentheses take the highest precedence
and operation performed from the innermost to the
outermost parentheses.
OPERATOR PRECEDENCE

▪Precedence and associativity of C


operators affect the grouping and
evaluation of operands in expressions.
▪Is meaningful only if other operators
with higher or lower precedence are
present.
▪Expressions with higher-precedence
operators are evaluated first.
OPERATOR PRECEDENCE
Precedence and Associativity of C Operators

Symbol Type of Operation Associativity


[ ] ( ) . –> postfix ++ and postfix –– Expression Left to right
prefix ++ and prefix –– sizeof
Unary Right to left
& * + – ~ !
typecasts Unary Right to left
* / % Multiplicative Left to right
+ – Additive Left to right
<< >> Bitwise shift Left to right
< > <= >= Relational Left to right
== != Equality Left to right
& Bitwise-AND Left to right
^ Bitwise-exclusive-OR Left to right
| Bitwise-inclusive-OR Left to right
&& Logical-AND Left to right
|| Logical-OR Left to right
? : Conditional-expression Right to left
= *= /= %=
Simple and compound
+= –= <<= >>= &= Right to left
assignment
^= |=
, Sequential evaluation Left to right
OPERATOR PRECEDENCE

▪The precedence and associativity (the order in


which the operands are evaluated) of C
operators.
▪In the order of precedence from highest to
lowest.
▪If several operators appear together, they have
equal precedence and are evaluated according
to their associativity.
▪All simple and compound-assignment operators
have equal precedence.
OPERATOR PRECEDENCE

▪Operators with equal precedence such


as + and -, evaluation proceeds
according to the associativity of the
operator, either from right to left or from
left to right.
▪The direction of evaluation does not
affect the results of expressions that
include more than one multiplication (*),
addition (+), or binary-bitwise (& | ^)
operator at the same level.
OPERATOR PRECEDENCE
▪ e.g:
3 + 5 + (3 + 2) = 13 – right to left
(3 + 5) + 3 + 2 = 13 – left to right
3 + (5 + 3) + 2 = 13 – from middle

▪ Order of operations is not


defined by the language.
▪ The compiler is free to evaluate
such expressions in any order, if
the compiler can guarantee a
consistent result.
OPERATOR PRECEDENCE
▪Only the sequential-evaluation (,), logical-AND
(&&), logical-OR (||), conditional-expression
(? :), and function-call operators constitute
sequence points and therefore guarantee a
particular order of evaluation for their
operands.
▪The sequential-evaluation operator (,) is
guaranteed to evaluate its operands from left
to right.
▪The comma operator in a function call is not
the same as the sequential-evaluation operator
and does not provide any such guarantee.
OPERATOR PRECEDENCE

▪ Logical operators also guarantee


evaluation of their operands from left to
right.
▪ But, they evaluate the smallest number of
operands needed to determine the result
of the expression.
▪ This is called "short-circuit" evaluation.
▪ Thus, some operands of the expression
may not be evaluated.
OPERATOR PRECEDENCE

▪ For example:
x && y++

▪ The second operand, y++, is


evaluated only if x is true (nonzero).
▪ Thus, y is not incremented if x is false
(0).
OPERATOR PRECEDENCE

▪ Label the execution order for the following expressions


OPERATOR PRECEDENCE

▪ Convert the following operations to C


expression

a. (rate*rate) + delta
b. 2*(salary + bonus)
c. 1/(time + (3*mass))
d. (a - 7) / (t + (9 * v))
Arithmetic Operators
• Arithmetic Operators are used to perform numerical operations

Operator Meaning Example


+ Addition x=10,y=5
x+y ->15
- Subtraction X-y -> 5
* Multiplication X*y -> 50
/ Division x/y -> 2
% Modulo X%y -> 0
Division
Relational Operators

• Relational operators are used to test the relationship between two variables or constant

Operator Meaning Example Result value

< Less x=10,y=5 False 0


Than X<y

> Greater X>y True 1


Than
<= Less X<=y False 0
than or
Equal to
>= Greater X>=y True 1
than or
equal to
!= Not X!=y False 0
Equal to
== Equal To X==y False 0
Logical Operators
• Logical operatorsare used to combine two or more relational expressions.
This operator is used to test more than one condition at a time.

Operator Meaning Example Result


&& Logical And When x=9, y=5 True
(y>=5) && (x==‘9’)
|| Logical Or (X>=6) || (y==‘a’) True
! Logical Not !(x>8) False

Operator Meaning Syntax Examp Result


le
++ Unary Variablename++; X=10; X=11
Plus (or) X++;
++ variable
name;
-- Unary Variablename--; X=10; X=9
Minus (or) X--;
-- variable name;
Simple Equivalent Shorthand
Assignment Assignment Operators
Operators
x=x+1 X += 1
y=y-1 Y =- 1
z=z*(x+y) Z *= (x+y)
Y=y/(x+y) Y /= (x+y)
X=x%z X %= z
Simple conditional operations can be carried out with the conditional
operator(?:)

Expression1 ? Expression 2:expression 3

Condition True Part False Part

#include<stdio.h>
void main() OUTPUT
{ The Result is 10
int a=10,b=5,c;
C=(a>b)?a:b;
printf(“The Result is %d",c);
}
/* Bitwise Operator Examples */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,ans,and;
clrscr();
printf("\n Enter A Number");
scanf("%d",&a);
b=1;
ans=a&b;
printf("\n The Result of AND Operation with 1");
if(ans==0)
printf("\n Rightmost bit is OFF");
else
printf("\n Rightmost bit is ON");
and=a/b;
printf("\n The Result of OR Operation with 1");
printf("\n Rightmost bit is ON and the result is %d",and);
getch();
}
Unformatted I/O Statement
• Characters can be read and written in C using the
following functions.
String Based I/O Operations
gets() & Puts() are used to perform Input output
operations on a string
syntax :
gets(variablename);
puts(variablename);
Reading decimal ,octal and hexadecimal numbers

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("\n Enter No in decimal");
scanf("%d",&a);
printf("\n u Entered %d\n",a);

printf("\n Enter No in octal");


scanf("%o",&a);
printf("\n u Entered %o or %d in decimal\n",a,a);

printf("\n Enter No in Hexadecimal");


scanf("%x",&a);
printf("\n u Entered %x or %d\n",a,a);
getch();
}
Type Conversion
• This is used to convert one data type to another data type.
The automatic type conversions for evaluating an expression
are given below -

• For example,
The sizeof operator
• sizeof is a unary compile-time operator

• The use of the sizeof operator shall be clear


from the following example -
Session Summary

@The getchar(),getch(),getche() deals with single character input

@ The functions gets() and puts() deals with string input and output respectively

@ printf() display any number of characters,integers,strings, float can be received

at a time

@ scanf() receives any number of characters, integers,strings,float at a time.

@ getchar() doesnot require any argument

@ gets() require a single argument

@ In a scanf() strings with spaces cannot be accessed until ENTER key is pressed.

@ In a gets() strings with any number of spaces can be accessed.


EXERCISES
1. Describe the different specifiers in scanf() function?

2. State the use of ambersand statement(s) in a scanf() statement?

3. Write a program for swapping two numbers using two varaibles?

4. Write a program to calculate Simple and Compound Interest?

5. Write a program to convert a decimal Number into its equivalent octal

& Hexadecimal number using Format specifiers?

6. Write a program to convert temperature in centigrade to farenheit?

7. Write a program to find the area of the circle (area=3.14*r2)?


C Program Controls + Flow
Charts
-controlling the program execu7on flow: selec7on,
repe77on and branching-
PROGRAM CONTROL
● Program begins execution at the main() function.
● Statements within the main() function are then
executed from top-down style, line-by-line.
● However, this order is rarely encountered in real C
program.
● The order of the execution within the main() body
may be branched.
● Changing the order in which statements are
executed is called program control.
● Accomplished by using program control statements.
● So we can control the program flows.
PROGRAM CONTROL

● There are three types of program controls:


1. Sequence control structure.
2. Selection structures such as if, if-
else, nested if, if-if-else, if-
else-if and switch-case-break.
3. Repetition (loop) such as for, while
and do-while.
1. Certain C functions and keywords also can
be used to control the program flows.
PROGRAM CONTROL
● Take a look at the following example
PROGRAM CONTROL

float paidRate = 5.0, sumPaid, paidHours = S1


25;
sumPaid = paidHours * paidRate; S2
printf("Paid sum = $%.2f \n", sumPaid); S3
return 0; S4

● One entry point and one exit point.


● Conceptually, a control structure like this
means a sequence execution.
PROGRAM CONTROL
Selection Control Structure

● Program need to select from the options given for


execution.
● At least 2 options, can be more than 2.
● Option selected based on the condition evaluation result:
TRUE or FALSE.
PROGRAM CONTROL
Selection: if, if-else, if-else-if
● Starting from the most basic if syntax,

if (condition) if (condition)
statement; { statements;}
next_statement; next_statement;

1. (condition) is evaluated.
2. If TRUE (non-zero) the statement is executed.

3. If FALSE (zero) the next_statement following the if

statement block is executed.


4. So, during the execution, based on some condition, some

codes were skipped.


PROGRAM CONTROL
For example:
if (hours > 70)
hours = hours + 100;
printf("Less hours, no bonus!\n");

▪ If hours is less than or equal to 70, its value will remain unchanged and the printf() will
be executed.
▪ If it exceeds 70, its value will be increased by 100.

if(jobCode == '1')
{
carAllowance = 100.00;
housingAllowance = 500.00;
entertainmentAllowance = 300.00;
}
printf("Not qualified for car, housing and entertainment
allowances!");

The three statements enclosed in the curly braces { } will only be executed if jobCode is equal
to '1', else the printf() will be executed.
PROGRAM CONTROL
if (condition) if (condition)
statement_1; { a block of statements;}
else else
statement_2; { a block of statements;}
next_statement; next_statement;
Explanation:
1.The (condition) is evaluated.

2.If it evaluates to non-zero (TRUE), statement_1 is executed,

otherwise, if it evaluates to zero (FALSE), statement_2 is


executed.
3.They are mutually exclusive, meaning, either statement_1 is

executed or statement_2, but not both.


4.statements_1 and statements_2 can be a block of codes

and must be put in curly braces.


PROGRAM CONTROL

For example:
if(myCode == '1')
rate = 7.20;
else
rate = 12.50;

If myCode is equal to '1', the rate is 7.20 else, if myCode


is not equal to '1' the rate is 12.50.
PROGRAM CONTROL
● The if-else constructs can be nested (placed one within another) to any
depth.
● General forms: if-if-else and if-else-if.
● The if-if-else constructs has the following form (3 level of depth
example),

if(condition_1)
if(condition_2)
if(condition_3)
statement_4;
else
statement_3;
else
statement_2;
else
statement_1;
next_statement;
PROGRAM CONTROL
● In this nested form, condition_1 is evaluated. If it is zero
(FALSE), statement_1 is executed and the entire nested if
statement is terminated.
● If non-zero (TRUE), control goes to the second if (within the first
if) and condition_2 is evaluated.
● If it is zero (FALSE), statement_2 is executed; if not, control
goes to the third if (within the second if) and condition_3 is
evaluated.
● If it is zero (FALSE), statement_3 is executed; if not,
statement_4 is executed. The statement_4 (inner most)
will only be executed if all the if statement are TRUE.
● Again, only one of the statements is executed other will be
skipped.
● If the else is used together with if, always match an else with
the nearest if before the else.
● statements_x can be a block of codes and must be put in
curly braces.
PROGRAM CONTROL
● The if-else-if statement has the following form (3
levels example).

if(condition_1)
statement_1;
else if (condition_2)
statement_2;
else if(condition_3)
statement_3;
else
statement_4;
next_statement;
PROGRAM CONTROL
● condition_1 is first evaluated. If it is non zero (TRUE),
statement_1 is executed and the whole statement
terminated and the execution is continue on the
next_statement.
● If condition_1 is zero (FALSE), control passes to the
next else-if and condition_2 is evaluated.
● If it is non zero (TRUE), statement_2 is executed and
the whole system is terminated. If it is zero (FALSE), the
next else-if is tested.
● If condition_3 is non zero (TRUE), statement_3 is
executed; if not, statement_4 is executed.
● Note that only one of the statements will be executed,
others will be skipped.
● statement_x can be a block of statement and must be
put in curly braces.
PROGRAM CONTROL
The if-else-if program example

● If mark is less than 40 then grade 'F'


will be displayed; if it is greater than or
equal to 40 but less than 50, then
grade 'E' is displayed.
● The test continues for grades 'D', 'C',
and 'B'.
● Finally, if mark is greater than or equal
to 80, then grade 'A' is displayed.
PROGRAM CONTROL
Selection: The switch-case-break

● The most flexible selection program control.


● Enables the program to execute different
statements based on an condition or expression
that can have more than two values.
● Also called multiple choice statements.
● The if statement were limited to evaluating an
expression that could have only two logical values:
TRUE or FALSE.
● If more than two values, have to use nested if.
● The switch statement makes such nesting
unnecessary.
● Used together with case and break.
PROGRAM CONTROL
● The switch constructs has the following form:
switch(condition)
{
case template_1 : statement(s);
break;
case template_2 : statement(s);
break;
case template_3 : statement(s);
break;


case template_n : statement(s);
break;

default : statement(s);
}
next_statement;
PROGRAM CONTROL
● Evaluates the (condition) and compares its value with the
templates following each case label.
● If a match is found between (condition) and one of the
templates, execution is transferred to the statement(s) that
follows the case label.
● If no match is found, execution is transferred to the
statement(s) following the optional default label.
● If no match is found and there is no default label, execution
passes to the first statement following the switch statement
closing brace which is the next_statement.
● To ensure that only the statements associated with the matching
template are executed, include a break keyword where
needed, which terminates the entire switch statement.
● The statement(s) can be a block of code in curly braces.

The C switch-case-break program example


PROGRAM CONTROL
● The statement sequence for case may also be NULL or empty.
● NULL/empty switch-case-break statement example

● The program would display,

If the value entered at the prompt


B stands for Blue colour!
is B;
You have chosen 'G', 'R' or
'Y' If the value entered at the prompt
G stands for Green, R for is G or R or Y;
Red and Y for Yellow!
The initial not a chosen
If there is no matching characters.
colour!

● It is useful for multiple cases that need the same processing


sequence.
PROGRAM CONTROL
● The break statement may be omitted to allow the
execution to continue to the next cases.

The switch-case-break without break program example

● It will display the message "Choice number 1!”


if nChoice == 1.
● It will display the message "Choice number 2!”
if nChoice == 2.
● It will display both the messages "Choice number 3!"
and "Choice number 4!" if nChoice == 3.
● It will display the "Invalid choice!" if it has any other
value.
● The switch-case construct can also be nested.
PROGRAM CONTROL
● The differences between nested if and switch:
1. The switch-case permits the execution of more than one
alternatives (by not placing break) whereas the if statement does
not. In other words, alternatives in an if statement are mutually
exclusive whereas they may or may not be in the case of a
switch-case.
2. A switch can only perform equality tests involving integer (or
character) constants, whereas the if statement allows more
general comparison involving other data types as well.

1. When there are more than 3 or 4 conditions, use the


switch-case-break statement rather than a long nested
if statement.
2. When there are multiple options to choose from.
3. When test condition only use integer (or character)
constants.
PROGRAM CONTROL
A flow-chart story

● A graphical representation of an algorithm.


● Drawn using certain symbols such as
rectangles, diamonds, ovals, and small
circles.
● These symbols are connected by arrows
called flow lines.
● Flow-charts clearly show the program's
execution order and indirectly describe how
control structures operate.
PROGRAM CONTROL
Symbol Name Description
A process or an action such as
Rectangular or action
calculation and assignment
Begin/start or End/stop. Indicates a
Oval completed algorithm or program
flow
Indicates a decision to be made
such as YES/NO, TRUE/FALSE,
Diamond or decision
<, <= etc.

Indicates the order of the actions


Flow lines to be executed, connecting other
symbols
Indicates a portion of a complete
Small circle or algorithm continued from the
connector previous portion or to be continued
to the next portion
The input or output such as
Input or output
standard input or output
PROGRAM CONTROL
● The following flow chart examples represent C if selection constructs.

Start

prinM("");

scanf("”);

intNum == 3? TRUE
prinM("");
prinM("");
FALSE
prinM("");

Stop

The if program source code example describing flow chart


PROGRAM CONTROL
● if, if-else and switch-case-break flow charts
PROGRAM CONTROL
Repetition: The for statement
● Executes a code block for a certain number of times.
● The code block may have no statement, one statement or more.
● The for statement causes the for loop to be executed in a fixed number of
times.
● The following is the for statement form,
for(initial_value;condition(s);increment/decrement)
statement(s);
next_statement;

▪ initial_value, condition(s) and increment/decrement are any valid C expressions.


▪ The statement(s) may be a single or compound C statement (a block of code).
▪ When for statement is encountered during program execution, the following events occurs:
1. The initial_value is evaluated e.g. intNum = 1.

2. Then the condition(s) is evaluated, typically a relational expression.

3. If condition(s) evaluates to FALSE (zero), the for statement terminates and execution

passes to next_statement.
4. If condition(s) evaluates as TRUE (non zero), the statement(s) is executed.

5. Next, increment/decrement is executed, and execution returns to step no. 2 until

condition(s) becomes FALSE.


PROGRAM CONTROL
● The for loop flow chart should be something like the following.

Start

Evaluate
ini7al_value
Do increment/
decrement

Evaluate Execute
condi7on(s) statement(s)
T

Stop
PROGRAM CONTROL
● A Simple for example, printing integer 1 to 10.

#include <stdio.h>
void main(void)
{
int nCount;
// display the numbers 1 to 10
for(nCount = 1; nCount <= 10; nCount++)
printf("%d ", nCount);
printf("\n");
}
PROGRAM CONTROL
● Its flow chart…

Start

nCount = 1

nCount++

nCount prinM("…");
<=10?
T
F
Stop
PROGRAM CONTROL
● for loop is a very flexible construct.
● Can use the decrementing counter instead of
incrementing. For example,
for (nCount = 100; nCount > 0; nCount--)

● Can use counter other than 1, for example 3,


for(nCount = 0; nCount < 1000; nCount += 3)

● initial_value can be omitted if the test variable


has been initialized beforehand.
● However the semicolon must still be there. For
example,
nCount=1;
for( ; nCount < 1000; nCount ++)
PROGRAM CONTROL
● The initial_value can be any valid C
expression, the expression is executed once when
the for statement is first reached. For example,
nCount =1;
for(printf("Now sorting the array…"); nCount
< 1000; nCount ++)

● The increment/decrement expression can be


omitted as long as the counter variable is updated
within the body of the for statement.
● The semicolon still must be included. For example,
for(nCount =0; nCount < 100; )
printf("%d", nCount ++);
PROGRAM CONTROL
● The condition(s) expression that terminates
the loop can be any valid C expression.
● As long as it evaluates as TRUE (non zero), the
for statement continues to execute.
● Logical operators can be used to construct more
complex condition(s) expressions. For
example,
for(nCount =0; nCount < 1000 && name[nCount] != 0;
nCount ++)
printf("%d", name[nCount]);
for(nCount = 0; nCount < 1000 && list[nCount];)
printf("%d", list[nCount ++]);
● Note: The for statement(s) and arrays are closely related, so it is difficult to
define one without explaining the other (will be discussed in another
Chapter).
PROGRAM CONTROL
● The for statement(s) can be followed by a null
(empty) statement, so that task is done in the for
loop itself.
● Null statement consists of a semicolon alone on a
line. For example,

for(count = 0; count < 20000; count++)


;

● This statement provides a pause


(delay) of 20,000 milliseconds.
PROGRAM CONTROL
▪ An expression can be created by separating two sub expressions with
the comma operator, and are evaluated (in left-to-right order), and the
entire expression evaluates to the value of the right sub expression.
▪ Each part of the for statement can be made to perform multiple
duties. For example,

"We have two arrays with 1000 elements each, named a[ ] and b[ ].
Then we want to copy the contents of a[ ] to b[ ] in the reverse order,
so, after the copy operation, the array content should be…"

b[0], b[1], b[2],… and a[999], a[998], a[997],… and


so on.

▪ sample coding is,

for(iRow = 0, jColumn = 999; iRow < 1000; iRow++,


jColumn--)
b[jColumn] = a[iRow];
PROGRAM CONTROL

▪ Another examples of the for statements,


nSum = 0;
for(iRow = 1; iRow <=20; iRow++)
nSum = nSum + iRow;
printf("\n Sum of the first 20 natural numbers:
");
printf("Sum = %d", nSum);
▪ The above program segment will compute and
display the sum of the first 20 natural numbers.
▪ The above example can be re-written as,
Take note that the initialization part has two statements separated by a comma (,).
for(iNum = 1, nSum = 0; iNum <= 20; iNum++)
nSum = nSum + iNum;
printf("Sum of the first 20 natural numbers = %d",
nSum);
PROGRAM CONTROL
● Another example,
for(iNum = 2, nSum=0, nSum2 = 0; iNum <= 20; iNum = iNum + 2)
{
nSum = nSum + iNum;
nSum2 = nSum2 + iNum * iNum;
}
printf("Sum of the first 20 even natural numbers = %d\n",
nSum);
printf("Sum of the square for the first 20 even natural
numbers = %d", nSum2);

● In this example, the for statement is a compound or


block statement.
● Note that, the initial value in the initialization part doesn’t
have to be zero and the increment value unnecessarily
needs to be 1.
PROGRAM CONTROL
▪ We can also create an infinite or never-ending loop by
omitting all the expressions or by using a non-zero constant
for condition(s) as shown in the following two code snippets,

for( ; ; )
printf("This is an infinite loop\n");

▪ or

for( ; 1 ; )
printf("This is an infinite loop\n");

▪ In both cases, the message "This is an infinite


loop" will be printed repeatedly, indefinitely.
▪ All the repetition constructs discussed so far can be nested
to any degree.
PROGRAM CONTROL
The nested for example

● The program has two for loops. The loop index iRow for
the outer (first) loop runs from 1 to 10 and for each value
of iRow, the loop index jColumn for the inner loop runs
from iRow + 1 to 10.
● Note that for the last value of iRow (i.e. 10), the inner loop
is not executed at all because the starting value of
jColumn is 2 and the expression jColumn < 11 yields
the value false (jColumn = 11).
#include <stdio.h>
int main()
int main()
{
{
int n;
int n;
scanf("%d", &n);
scanf("%d", &n); for (int i = 1; i <= n; ++i)
for (int i = n; i >= 1; --i)
{
{
for (int j = 1; j <= n; ++j)
for (int j = 1; j <= i; ++j)
{
{
printf("%c ", '#');
printf("%d ", j);
}
} printf("\n");
printf("\n");
}
}
return 0;
return 0;
}
}

https://www.scaler.com/topics/pattern-program-in-c/
PROGRAM CONTROL
Another nested for example

1. In the first for loop, the initialization is skipped because the initial value of row,
10 has been initialized; this for loop is executed until the row is 1 (row > 0).
2. For every row value, the inner for loop will be executed until col = 1 (col >
0).
3. So the external for loop will print the row and the internal for loop will print the
column so we got a rectangle of #.
PROGRAM CONTROL
Repetition: The while loop
● Executes a block of statements as long as a specified condition is TRUE.
● The general while loop construct,

while (condition)
statement(s);
next_statement;

▪ The (condition) may be any valid C expression.


▪ The statement(s) may be either a single or a compound (a block of code) C
statement.
▪ When while statement encountered, the following events occur:
1. The (condition) is evaluated.

2. If (condition) evaluates to FALSE (zero), the while loop terminates and

execution passes to the next_statement.


3. If (condition) evaluates as TRUE (non zero), the C statement(s) is

executed.
4. Then, the execution returns to step number 1 until condition becomes FALSE.
PROGRAM CONTROL
● The while statement flow chart is shown below.

Start

Evaluate T Execute
condi7on statement(s)

Stop
PROGRAM CONTROL
● A simple example
// simple while loop example
#include <stdio.h>
int main(void)
{
int nCalculate = 1;
// set the while condition
while(nCalculate <= 12)
{
// print
printf("%d ", nCalculate);
// increment by 1, repeats
nCalculate++;
}
// a newline
printf("\n");
return 0;
}
PROGRAM CONTROL
● The same task that can be performed using the
for statement.
● But, while statement does not contain an
initialization section, the program must explicitly
initialize any variables beforehand.
● As conclusion, while statement is essentially
a for statement without the initialization and
increment components.
● The syntax comparison between for and
while,
for( ; condition; ) vs while(condition)
PROGRAM CONTROL
● Just like for and if statements, while statements can also be nested.
● The nested while example
PROGRAM CONTROL
● The nested for and while program example
PROGRAM CONTROL Repetition: The do-while loop

● Executes a block of statements as long as a specified


condition is true at least once.
● Test the condition at the end of the loop rather than at the
beginning, as demonstrated by the for and while loops.
● The do-while loop construct is,
do
statement(s);
while (condition)
next_statement;

▪ (condition) can be any valid C expression.


▪ statement(s) can be either a single or compound (a block of code) C
statement.
▪ When the program encounter the do-while loop, the following events occur:
1. The statement(s) are executed.

2. The (condition) is evaluated. If it is TRUE, execution returns to step number

1. If it is FALSE, the loop terminates and the next_statement is executed.


3. This means the statement(s) in the do-while will be executed at least

once.
PROGRAM CONTROL
● A flow chart for the do- ● The statement(s)
while loop are always executed
at least once.
Start ● for and while
loops evaluate the
Execute
statement(s)
condition at the start
of the loop, so the
associated
Evaluate T statements are not
condi7on
executed if the
F condition is initially
Stop FALSE.
PROGRAM CONTROL
● The do-while program example
PROGRAM CONTROL Other Program Controls

continue keyword
● continue keyword forces the next iteration to
take place immediately, skipping any instructions
that may follow it.
● The continue statement can only be used
inside a loop (for, do-while and while) and
not inside a switch-case selection.
● When executed, it transfers control to the
condition (the expression part) in a while or do-
while loop, and to the increment expression in a
for loop.
● Unlike the break statement, continue does not
force the termination of a loop, it merely transfers
control to the next iteration.
PROGRAM CONTROL
● Consider the following continue keyword example
// using the continue in for structure
#include <stdio.h>

int main(void)
{
int iNum;
for(iNum = 1; iNum <= 10; iNum++)
{
// skip remaining code in loop only if iNum == 5
if(iNum == 5)
continue;
printf("%d ", iNum);
}
printf("\nUsed continue to skip printing the value 5\n");
return 0;
}
PROGRAM CONTROL
● Next consider the following continue keyword example,
#include <stdio.h>

int main(void)
{
int iNum, nSum;
for(iNum=1, nSum=0; iNum<20; iNum++)
{
// test value, 0 or non-zero
if (iNum % 2)
{
printf("iNum %% 2 = %d (skipped)\n", iNum % 2);
// executed if the test value is non-zero
// and repeat the for statement
continue;
}
// executed if the test value is zero and repeat the
for statement
nSum = nSum + iNum;
printf("iNum %% 2 = %d (summed up), nSum = %d \n",
iNum % 2, nSum);
}
return 0;
}
PROGRAM CONTROL

● This loop sums up the even numbers 2, 4, 6, ... and stores the value in
the nSum variable.
● If the expression iNum % 2 (the remainder when iNum is divided by 2)
yields a non-zero value (i.e., if iNum is odd), the continue statement
is executed and the iteration repeated (iNum incremented and tested).
PROGRAM CONTROL
● If it yields a zero value (i.e., if iNum is even), the
statement nSum = nSum + iNum; is executed and
the iteration continued.
● When a continue statement executes, the next
iteration of the enclosing loop begins.
● The enclosing loop means the statements between the
continue statement and the end of the loop are not
executed.
● Try another continue example
PROGRAM CONTROL goto keyword

● The goto statement is one of C unconditional jump or


branching.
● When program execution encounters a goto statement,
execution immediately jumps, or branches, to the location
specified by the goto statement.
● The statement is unconditional because execution always
branches when a goto statement is came across, the
branching does not depend on any condition.
● A goto statement and its target label must be located in
the same function, although they can be in different blocks.
● Use goto to transfer execution both into and out of loop.
● However, using goto statement strongly not
recommended.
● Always use other C branching statements.
● When program execution branches with a goto statement,
no record is kept of where the execution is coming from.
PROGRAM CONTROL
● Try the following C goto keyword program example
PROGRAM CONTROL exit() function

● exit() function normally used when a program want to


terminate at any time.
● The exit() function terminates program execution and
returns control to the Operating System.
● The syntax of the exit() function is,

exit(status);

Status Description
0 (zero) The program terminated normally.
Indicates that the program terminated
1 (or non-
with some sort of error. The return
zero)
value is usually ignored.
PROGRAM CONTROL

▪ We must include the header file stdlib.h


(cstdlib if used in C++ code).
▪ This header file also defines two symbolic
constants for use as arguments to the exit()
function, such as,
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

▪ Then we can call the function like the following,


exit(EXIT_SUCCESS);
Or
exit(EXIT_FAILURE);
PROGRAM CONTROL atexit() function

● Used to specify, or register, one or more functions that


are automatically executed when the program
terminates.
● Exit-processing function that executes prior to program
termination
● These functions are executed on a last-in, first-out
(LIFO) basis, the last function registered is the first
function executed.
● When all functions registered by atexit() executed,
the program terminates and returns control to the OS.
● The prototype of the atexit() function is located in the
stdlib.h and the syntax is,
int atexit(void(*funct)(void));
● where funct is the function to be called.
PROGRAM CONTROL
● atexit() function takes a function pointer as its
argument and functions with atexit() must have a
return type of void.
● The functions passed to atexit() cannot take
parameters.
● atexit() uses the heap (instead of stack) to hold the
registered functions.
● The following program pushes three functions onto the
stack of functions to be executed when atexit() is
called.
● When the program exits, these programs are executed
on a last in, first out basis.
The atexit() function program
example
PROGRAM CONTROL system() function

● The system() function, enables the execution of


OS command from the C running program.
● Can be quite useful, for example, enabling the
program to do a directory listing or formatting a
disk without exiting the program.
● Must include the header file stdlib.h. The syntax is,
system("command");
● The command can be either a string constant or a
pointer to a string.
PROGRAM CONTROL
● For example, using an argument with the
system() function,
char *command = "dir";
system(command);
● After the OS command is executed, the program
continues at the location immediately following
the system() call.
● If the command passed to the system()
function is not a valid OS command, a bad
command or file name error message is
displayed before returning to the program.
● The command can also be any executable or
batch file to be run.
PROGRAM CONTROL
Try the following system() program example
PROGRAM CONTROL return keyword
● The return statement has a form,
return expression;
● The action is to terminate execution of the current
function and pass the value contained in the
expression (if any) to the function that invoked it.
● The value returned must be of the same type or
convertible to the same type as the function's
return type (type casting).
● More than one return statement may be placed in
a function.
● The execution of the first return statement in the
function automatically terminates the function.
PROGRAM CONTROL
● The main() function has a default type int
since it returns the value 0 (an integer) to the
environment.
● A function of type void will not have the
expression part following the keyword return.
● Instead, in this case, we may drop the entire
return statement altogether.
● If a function calls another function before it is
defined, then a prototype for it must be included
in the calling function.
● This gives information to the compiler to look
for the called function (callee).
PROGRAM CONTROL

#include <stdio.h>
Callee

int main(void) printf(“…“) definition


Caller
{
int nNum = 20;

printf("Initial value of the nNum


variable is %d", nNum);
return 0;
}
PROGRAM CONTROL

#include <stdio.h>

// prototype
void DisplayInteger(int); Caller

void main(void)
{
int nNum = 30;
Callee
DisplayInteger(nNum);

void DisplayInteger(int iNum)


{
printf("The integer is %d\n", iNum);
}
PROGRAM CONTROL
● The return keyword example 1

● The return keyword example 2


PROGRAM CONTROL break keyword

Program example on using break in for loop

● Already discussed in switch-case constructs.


● The break statement terminates the execution of the nearest enclosing
loop or conditional statement in which it appears. Control passes to the
statement that follows the terminated statement, if any.
● Used with the conditional switch statement and with the do, for, and
while loop statements.
● In a switch statement, break causes the program to execute the next
statement after the switch. Without a break statement, every statement
from the matched case label to the end of the switch, including the
default, is executed.
● In loops, break terminates execution of the nearest enclosing do, for,
or while statement. Control passes to the statement that follows the
terminated statement, if any.
● Within nested statements, the break statement terminates only the do,
for, switch, or while statement that immediately encloses it. You can
use a return or goto statement to transfer control from within more
deeply nested structures.
PROGRAM CONTROL abort() and terminate() functions

Function Description
Abort current process and returns error code defined in
abort()
stdlib.h
Used when a handler for an exception cannot be found. The
terminate( default action to terminate is to call abort() and causes
) immediate program termination. It is defined in except.h
(Microsoft uses eh.h and only compiled in C++).

1. The syntax is,

void abort( void );

2. abort() does not return control to the calling process. By default, it terminates
the current process and returns an exit code of 3.
3. By default, the abort routine prints the message:

"This application has requested the Runtime to terminate it in an


unusual way. Please contact the application's support team for
more information."
PROGRAM CONTROL
● The abort() program example
PROGRAM CONTROL
● terminate() function calls abort() or a function you
specify using set_terminate().
● terminate() function is used with C++ exception
handling and is called in the following cases:
1. A matching catch handler cannot be found for a thrown
C++ exception.
2. An exception is thrown by a destructor function during
stack unwind.
3. The stack is corrupted after throwing an exception.
● terminate() calls abort() by default. You can change
this default by writing your own termination function and
calling set_terminate() with the name of your function
as its argument.
● terminate() calls the last function given as an argument
to set_terminate().
PROGRAM CONTROL

● The terminate() program example (C++)


PROGRAM CONTROL
● We use EOF (acronym, stands for End Of File),
normally has the value –1, as the sentinel value.
● The user types a system-dependent
EOF keystroke
combination to mean end of file that means ‘I have
no more data to enter’.
● EOF is a symbolic integer constant defined in the
<stdio.h> header file.
● The keystroke combinations for entering EOF are
system dependent.
● On UNIX systems and many others, the EOF is
<Return key> or ctrl-z or ctrl-d.
● On other system such as old DEC VAX VMS or
Microsoft Corp MS-DOS, the EOF is ctrl-z.
PROGRAM CONTROL
● The EOF program example. (Press <Enter> + <Ctrl+z> for
EOF)
● If the value assigned to grade is equal to EOF, the program
terminates.
Strings
n Strings are 1-dimensional arrays of type char.
n By convention, a string in C is terminated by
the end-of-string sentinel \0, or null
character.
n String constant : “abc” is a character array of
size 4, with the last element being the null
chaaracter \0.
n char s[] = “abc” ; a b c \0
C ARRAYS
-a collection of same type data,
1D, 2D-
What is an array?
n A linear arrangement of data of the
same type of elements
n An array has to be declared first with
the maximum number of elements it
can store
n int marks[100];
n char name[20];
ARRAYS
§ An array is a collection of elements of the same type that
are referenced by a common name.
§ Compared to the basic data type (int, float & char) it is
an aggregate or derived data type.
§ All the elements of an array occupy a set of contiguous
memory locations.
§ Why need to use array type?
§ Consider the following issue:
"We have a list of 1000 students' marks of
an integer type. If using the basic data
type (int), we will declare something like
the following…"

int studMark0, studMark1, studMark2, ...,


studMark999;
ARRAYS
§ Can you imagine how long we have to write
the declaration part by using normal variable
declaration?

int main(void)
{
int studMark1, studMark2, studMark3,
studMark4, …, …, studMark998, stuMark999,
studMark1000;


return 0;
}
ARRAYS
§ By using an array, we just declare like this,

int studMark[1000];

§ This will reserve 1000 contiguous memory locations for storing the
students’ marks.
§ Graphically, this can be depicted as in the following figure.
ARRAYS
§ This absolutely has simplified our declaration of the
variables.
§ We can use index or subscript to identify each
element or location in the memory.
§ Hence, if we have an index of jIndex,
studMark[jIndex] would refer to the jIndexth
element in the array of studMark.
§ For example, studMark[0] will refer to the first
element of the array.
§ Thus by changing the value of jIndex, we could
refer to any element in the array.
§ So, array has simplified our declaration and of
course, manipulation of the data.
How is an array stored?
n Starting from a given memory location, the
successive array elements are allocated
space in consecutive memory locations.

Array a
n x: starting address of the array in memory
n k: number of bytes allocated per array element
n a[i] è is allocated memory location at
address x + i*k
Index Rule
n An array index must evaluate to an int
between 0 and n-1 where n is the number of
elements in the array.
n marks[76]
n marks[i*2+k] // provided i*2+k is between 0 1nd 99

C Array bounds are not checked


#define S 100 if (0<=i && i<100)
marks[S] = 10; marks[i] = 10;
else printf (“Array index %d
out of range”, i);
Use
n An array element can be used wherever
a simple variable of the same type can
be used.
n Examples :
scanf (“%d”, &marks[i]);
marks[i] = (int) (sqrt(21.089));
Things you can and can’t do
n You can not
n use = to assign one array variable to
another
n use == to directly compare array variables
n directly scanf or printf arrays
n But you can do these things on array
elements.
n You can write functions to do them.
ARRAYS
One Dimensional Array: Declaration

§ Dimension refers to the array's size, which is how


big the array is.
§ A single or one dimensional array declaration has
the following form,
array_element_data_type array_name[array_siz
e];

§ Here, array_element_data_type define the base


type of the array, which is the type of each
element in the array.
§ array_name is any valid C / C++ identifier name
that obeys the same rule for the identifier naming.
§ array_size defines how many elements the array
will hold.
ARRAYS
§ For example, to declare an array of 30 characters, that
construct a people name, we could declare,
char cName[30];
§ Which can be depicted as follows,

§ In this statement, the array character can


store up to 30 characters with the first
character occupying location cName[0]
and the last character occupying
cName[29].
§ Note that the index runs from 0 to 29. In
C, an index always starts from 0 and ends
with array's (size-1).
§ So, take note the difference between the
array size and subscript/index terms.
ARRAYS
§ Examples of the one-dimensional array declarations,

int xNum[20], yNum[50];


float fPrice[10], fYield;
char chLetter[70];

§ The first example declares two arrays named xNum and yNum
of type int. Array xNum can store up to 20 integer numbers
while yNum can store up to 50 numbers.
§ The second line declares the array fPrice of type float. It
can store up to 10 floating-point values.
§ fYield is basic variable which shows array type can be
declared together with basic type provided the type is similar.
§ The third line declares the array chLetter of type char. It can
store a string up to 69 characters.
§ Why 69 instead of 70? Remember, a string has a null
terminating character (\0) at the end, so we must reserve for
it.
ARRAYS
Array Initialization
§ An array may be initialized at the time of declaration.
§ Giving initial values to an array.
§ Initialization of an array may take the following form,
type array_name[size] = {a_list_of_value};
§ For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i', 'o', 'u',
'\0'};
§ The first line declares an integer array idNum and it immediately
assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1],
idNum[2],..., idNum[6] respectively.
§ The second line assigns the values 5.6 to fFloatNum[0], 5.7 to
fFloatNum[1], and so on.
§ Similarly the third line assigns the characters 'a' to chVowel[0],
'e' to chVowel[1], and so on. Note again, for characters we
must use the single apostrophe/quote (') to enclose them.
§ Also, the last character in chVowel is NULL character ('\0').
ARRAYS
§ Initialization of an array of type char for holding strings may take the
following form,

char array_name[size] = "string_lateral_constant";

§ For example, the array chVowel in the previous example could have been
written more compactly as follows,

char chVowel[6] = "aeiou";

§ When the value assigned to a character array is a string (which must be


enclosed in double quotes), the compiler automatically supplies the NULL
character but we still have to reserve one extra place for the NULL.
§ For unsized array (variable sized), we can declare as follow,

char chName[ ] = "Mr. Dracula";

§ C compiler automatically creates an array which is big enough to hold all


the initializer.
ARRAYS
§ Arrays allow programmers to group related items of the same
data type in one variable.
§ However, when referring to an array, one has to specify not only
the array or variable name but also the index number of interest.
§ Program example 1: Sum of array’s element.
§ Notice the array's element which is not initialized is set to 0
automatically.
ARRAYS
§ Program example 2: Searching the smallest value.
§ Finding the smallest element in the array named fSmallest.
§ First, it assumes that the smallest value is in fSmallest[0] and
assigns it to the variable nSmall.
§ Then it compares nSmall with the rest of the values in fSmallest,
one at a time.
§ When an element is smaller than the current value contained in
nSmall, it is assigned to nSmall. The process finally places the
smallest array element in nSmall.
ARRAYS
§ Program example 3: Searching the biggest
value. By modifying the previous example we
can search the biggest value.
ARRAYS
§ Program example 4: Searching the location for
the given value in an array
ARRAYS
§ Program example 5: Storing and reading
a string
ARRAYS
§ Program example 6: Storing and reading array
content and its index
ARRAYS
Two Dimensional/2D Arrays

§ A two dimensional array has two subscripts/indexes.


§ The first subscript refers to the row, and the second, to the
column.
§ Its declaration has the following form,
data_type array_name[1st dimension size][2nd dimension
size];

§ For examples,
int xInteger[3][4];
float matrixNum[20][25];

§ The first line declares xInteger as an integer array with 3 rows


and 4 columns.
§ Second line declares a matrixNum as a floating-point array with
20 rows and 25 columns.
ARRAYS
§ If we assign initial string values for the 2D array it will look
something like the following,

char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole",


"Kidman", "Arnold", "Jodie"};

§ Here, we can initialize the array with 6 strings, each with


maximum 9 characters long.
§ If depicted in rows and columns it will look something like the
following and can be considered as contiguous arrangement in
the memory.
ARRAYS
§ Take note that for strings the null character (\0) still needed.
§ From the shaded square area of the figure we can determine the size of the
array.
§ For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the
number of the colored square. In general, for

array_name[x][y];

§ The array size is = First index x second index = xy.


§ This also true for other array dimension, for example three dimensional
array,

array_name[x][y][z]; => First index x second index x third index = xyz


§ For example,

ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
§ And if you want to illustrate the 3D array, it could be a cube with wide, long
and height dimensions.

www.tenouk.com, ©
ARRAYS
§ Program example 7: Storing and reading
array content and its index
ARRAYS
§ Program example 8: Swapping iIndex
(iRow) with jIndex (iColumn) in the
previous program example
ARRAYS
1. Program example 9: Strings are read in by the rows.
2. Each row will have one string. Enter the following data:
“you”, “are”, “cat” for the following example.
3. Remember that after each string, a null character is
added.
4. We are reading in strings but printing out only characters.
ARRAYS
§ The contents of the array in memory after the three
strings are read in the array.

§ Re-run the program, enter the following data:


“you”, “my”. Illustrates the content as done
previously.
ARRAYS
1. Does your output agree?
2. How is the null character, '\0' printed?
3. Is there a garbage character in a[1][3]? If so,
why?

a) The output matched, except the garbage.


b) Just an empty space.
c) Yes. This slot has been reserved but not
filled so whatever the previous data that
has been stored here would be displayed
(if possible).
Averaging marks
#define CLASS_SIZE 50
double marks[CLASS_SIZE] ;
double total=0.0;
int i;
printf (“Enter %d grades \n”, CLASS_SIZE);
for (i=0; i<CLASS_SIZE; i++)
scanf(“%f”, &marks[i]);
for (i=0; i<CLASS_SIZE; i++) {
printf (“ %d . %f\n”,i, marks[i]);
total += marks[i] ;
}
printf (“Average = %f\n”, total / (double) CLASS_SIZE) ;
n Are Arrays necessary to solve the above
problem ?
n What about this problem :
n read student marks, print all marks above
average only.
#define MtWeight 0.3
#define FinalWeight 0.7
#define MaxStudents 100

int NumStudents;
int midterm[MaxStudents];
int final[MaxStudents];
double score[MaxStudents];
midterm
final
Parallel Arrays score

/* Suppose we have input the value of NumStudents,


read student i’s grades for midterm and final, and
stored them in midterm[i] and final[i]
Store a weighted average in the array score */
if (NumStudents < MaxStudents)
for (i=0; i<NumStudents; i++) {
score[i] = MtWeight* (double) midterm[i] +
FinalWeight* (double) final[i];
}
Reading Array Elements
/* Read in student midterm and final grades and store
them in two arrays */
#define MaxStudents 100
int midterm[MaxStudents], final[MaxStudents];
int NumStudents ; /* actual no of students */
int i, done, Smidterm, Sfinal;

printf (“Input no of students :”);


scanf(“%d”, &NumStudents) ;
if (NumStudents > MaxStudents)
printf (“Too many students”) ;
else
for (i=0; i<NumStudents; i++)
scanf(“%d%d”, &midterm[i], &final[i]);
Reading Arrays - II
/* Read in student midterm and final grades and store them in 2 arrays */
#define MaxStudents 100
int midterm[MaxStudents], final[MaxStudents];
int NumStudents ; /* actual no of students */
int i, done, Smidterm, Sfinal;
done=FALSE; NumStudents=0;
while (!done) {
scanf(“%d%d”, &Smidterm, &Sfinal);
if (Smidterm !=-1 || NumStudents>=MaxStudents)
done = TRUE;
else {
midterm[NumStudents] = Smidterm;
final[NumStudents] = Sfinal;
NumStudents++;
}
}
Size of an array
n How do you keep track of the number of
elements in the array ?
n 1. Use an integer to store the current size of the array.
#define MAX 100
int size;
float cost[MAX] ;
n 2. Use a special value to mark the last element in an
array. If 10 values are stored, keep the values in
cost[0], ... , cost[9], have cost[10] = -1
n 3. Use the 0th array element to store the size
(cost[0]), and store the values in cost[1], ... ,
cost[cost[0]]
Add an element to an array
1. cost[size] = newval; size++;
2. for (i=0; cost[i] != -1; i++) ;
cost[i] = newval;
cost[i+1] = -1;
3. cost[0]++;
cost[cost[0]] = newval;
Arrays as parameters of functions
n An array passed as a parameter is not
copied
Array operations
#define MAXS 100
int insert (int[], int, int, int) ;
int delete (int[], int, int) ;
int getelement (int[], int, int) ;
int readarray (int[], int) ;
main () {
int a[MAXS];
int size;
size = readarray (a, 10) ;
size = insert (a, size, 4, 7) ;
x = getelement (a, size, 3) ;
size = delete (a, size, 3) ;
}
Array operations
int readarray (int x[], int size) {
#define MAXS 100 int i;
int insert (int[], int, int, int) ; for (i=0; i<size; i++)
int delete (int[], int, int) ; scanf(“%d”, &x[i]) ;
int getelement (int[], int, int) ; return size;
int readarray (int[], int) ; }
main () { int getelement (int x[], int size, int pos){
int a[MAXS]; if (pos <size) return x[pos] ;
int size; return -1;
size = readarray (a, 10) ; }
size = insert (a, size, 4, 7) ;
x = getelement (a, size, 3) ; int insert (int x[], int size, int pos. int val){
for (k=size; k>pos; k--)
size = delete (a, size, 3) ;
x[k] = x[k-1] ;
} x[pos] = val ;
return size+1;
}
void reverse (int x[], int findmax (int x[], int
int size) { size) {

}
}
void reverse (int x[], int size) { int findmax (int x[], int size) {
int i; int i, max;
for (i=0; i< (size/2); i++) max = x[0];
temp = x[size-i-1] ; for (i=1; i< size; i++)
x[size-1-1] = x[i] ; if (x[i] > max)
x[i] = temp; max = x[i] ;
} return max;
}
C FUNCTIONS
-INDEPENDENT ROUTINE WHICH DO A SPECIFIC
TASK(S)-
C FUNCTIONS
Some definition: A function is a named, independent section of C code that
performs a specific task and optionally returns a value to the calling program
or/and receives values(s) from the calling program.

§ Basically there are two categories of function:


1. Predefined functions: available in C / C++
standard library such as stdio.h, math.h,
string.h etc.
2. User-defined functions: functions that
programmers create for specialized tasks
such as graphic and multimedia libraries,
implementation extensions or dependent
etc.
C FUNCTIONS

§ Let try a simple program example that using a simple user defined
function,
C FUNCTIONS
§ The following statement call cube() function, bringing
along the value assigned to the fInput variable.
fAnswer = cube(fInput);
§ When this statement is executed, program jump to the
cube() function definition.
§ After the execution completed, the cube() function returns
to the caller program (main()), assigning the returned
value, fCubeVolume to fAnswer variable for further
processing (if any).
§ In this program the scanf() and print() are examples
of the standard predefined functions.
C FUNCTIONS
§ Basically a function has the following characteristics:
1. Named with unique name .
2. Performs a specific task - Task is a discrete job that the
program must perform as part of its overall operation, such
as sending a line of text to the printer, sorting an array into
numerical order, or calculating a cube root, etc.
3. Independent - A function can perform its task without
interference from or interfering with other parts of the
program.
4. May receive values from the calling program (caller) -
Calling program can pass values to function for processing
whether directly or indirectly (by reference).
5. May return a value to the calling program – the called
function may pass something back to the calling program.
C FUNCTIONS
Function Mechanism

§ C program does not execute the statements in


a function until the function is called.
§ When it is called, the program can send
information to the function in the form of one or
more arguments although it is not a mandatory.
§ Argument is a program data needed by the
function to perform its task.
§ When the function finished processing, program
returns to the same location which called the
function.
C FUNCTIONS
§ The following figure illustrates function calls (also the memory’s
stack record activation – construction & destruction.
C FUNCTIONS

§ Function can be called as many


times as needed as shown for
function_2(…).
§ Can be called in any order
provided that it has been
declared (as a prototype) and
defined.
Stack and Heap
C FUNCTIONS
§ Each process in a multi-tasking OS runs in its own memory area.
§ This area is the virtual address space, which in 32-bit mode, is always a
4GB block of memory addresses.
§ These virtual addresses are mapped to physical memory by page tables,
which are maintained by the OS’s kernel and consulted by the processor.
§ Each process has its own set of page tables.
§ More info at: Anatomy of program in memory.
C FUNCTIONS
§ As an example, the standard program’s/executable’s/binary’s segment
layout in a Linux process is shown in the following figure.
§ The bands in the address space are correspond to memory segments
like the heap, stack, and so on.
C FUNCTIONS
§ Stack and heap are two memory sections in the user mode space.
§ Stack will be allocated automatically for function call.
§ It grows downward to the lower address.
§ It is Last-in First-out (LIFO) mechanism (tally with the assembly
language’s push and pop instructions)
§ Meanwhile, heap will be allocated by demand or request using C
memory management functions such as malloc(), memset(),
realloc() etc.
§ It is dynamic allocation, grows upward to the higher memory
address.
§ By request means we need to release the allocation manually
using C functions such as free() and delete (if using new
keyword).
§ In a multi-threaded environment each thread will have its own
completely independent stack but they will share the heap as
needed.
C FUNCTIONS

§ malloc() & free()


example

§ malloc() without free()


example
C FUNCTIONS
§ By referring the previous function calls example, the stack should be in
the equilibrium condition.
§ By considering the stack area of memory, the following figure illustrates
the condition of stack for function call.
§ In this case, main() function has 3 function calls: function_1(),
function_2() and function_3().
C FUNCTIONS
§ The following is what a typical stack frame might look like.
§ Smaller numbered/lower memory addresses are on top.
C FUNCTIONS
§ This would be the contents of the stack if we have a
function MyFunct() with the prototype,
int MyFunct(int arg1, int arg2, int arg3) ;

§ and in this case, MyFunct() has two local int variables.


(We are assuming here that sizeof(int) is 4 bytes).
§ The stack would look like this if the main() function
called MyFunct() and control of the program is still inside
the function MyFunct().
§ main() is the "caller" and MyFunct() is the "callee".
§ The ESP register is being used by MyFunct() to point to
the top of the stack.
§ The EBP register is acting as a "base pointer".
C FUNCTIONS
§ The arguments passed by main() to MyFunct() and the local
variables in MyFunct() can all be referenced as an offset from the
base pointer.
§ The convention used here (cdecl) is that the callee is allowed to mess
up the values of the EAX, ECX and EDX registers before returning.
§ Depend on the calling convention used:
cdecl, stdcall or fastcall
§ So, if the caller wants to preserve the values of EAX, ECX and EDX, the
caller must explicitly save them on the stack before making the
subroutine call.
§ On the other hand, the callee must restore the values of the EBX, ESI
and EDI registers.
§ If the callee makes changes to these registers, the callee must save the
affected registers on the stack and restore the original values before
returning.
§ Parameters passed to MyFunct() are pushed on the stack.
§ The last argument is pushed first so in the end the first argument is on
top.
§ Local variables declared in MyFunct() as well as temporary variables
are all stored on the stack.
C FUNCTIONS
§ Return values of 4 bytes or less are stored in the EAX
register.
§ If a return value with more than 4 bytes is needed,
then the caller passes an "extra" first argument to the
callee.
§ This extra argument is address of the location where
the return value should be stored. i.e., in C jargon the
function call,
x = MyFunct(a, b, c);
§ is transformed into the call,
MyFunct(&x, a, b, c);
§ Note that this only happens for function calls that
03/01/16

return more than 4 bytes.


C FUNCTIONS
Function Definition

§ Is the actual function body, which contains the code


that will be executed as shown below (previous
example).

int cube(int fCubeSide)


{
// local scope (local to this function)
// only effective in this function 'body'
int fCubeVolume;

// calculate volume
fCubeVolume = fCubeSide * fCubeSide * fCubeSide;
// return the result to caller
return fCubeVolume;
}
C FUNCTIONS
§ First line of a function definition is called the function
header, should be identical to the function prototype, except
the semicolon.
§ Although the argument variable names (fCubeSide in this
case) were optional in the prototype, they must be included
in the function header.
§ Function body, containing the statements, which the
function will perform, should begin with an opening brace
and end with a closing brace.
§ If the function returns data type is anything other than void
(nothing to be returned), a return statement should be
included, returning a value matching the return data type
(int in this case).
C FUNCTIONS
The Function header
§ The first line of every function definition is called function header. It has 3
components, as shown below,

1. Function return type - Specifies the data type that the function should
returns to the caller program. Can be any of C data types: char, float,
int, long, double, pointers etc. If there is no return value, specify a
return type of void. For example,

int calculate_yield(…) // returns an int type


03/01/16
float mark(…) // returns a float type
void calculate_interest(…) // returns nothing
C FUNCTIONS

1. Function name - Can have any name as long as the


rules for C / C++ variable names are followed and
must be unique.
2. Parameter list - Many functions use arguments, the
value passed to the function when it is called. A
function needs to know the data type of
each argument. Argument type is provided in the
function header by the parameter list. Parameter list
acts as a placeholder.
C FUNCTIONS
§ For each argument that is passed to the function, the
parameter list must contain one entry, which specifies the
type and the name.
§ For example,
void myfunction(int x, float y, char z)
void yourfunction(float myfloat, char mychar)
int ourfunction(long size)

§ The first line specifies a function with three arguments:


type int named x, type float named y and type char
named z.
§ Some functions take no arguments, so the parameter list
should be void or empty such as,
long thefunction(void)
void testfunct(void)
int zerofunct()
C FUNCTIONS
§ Parameter is an entry in a function header. It serves as a
placeholder for an argument. It is fixed, that is, do not change
during execution.
§ The argument is an actual value passed to the function by the
caller program. Each time a function is called, it can be
passed with different arguments.
§ A function must be passed with the same number and type of
arguments each time it is called, but the argument values can
be different.

Function
example:
parameter and
argument
C FUNCTIONS
For the first function call:

Then, the second function call:

§ Each time a function is called, the different arguments are passed to


the function’s parameter.
§ z = half_of(y) and z = half_of(x), each send a different
argument to half_of() through the k parameter.
§ The first call send x, which is 3.5, then the second call send y, which
is 65.11.
§ The value of x and y are passed (copied) into the parameter k of
half_of().
§ Same effect as copying the values from x to k, and then y to k.
§ half_of() then returns this value after dividing it by 2.
The Function Body
C FUNCTIONS
§ Enclosed in curly braces, immediately follows the function header.
§ Real work in the program is done here.
§ When a function is called execution begins at the start of the
function body and terminates (returns to the calling program) when
a return statement is encountered or when execution reaches
the closing braces (}).
§ Variable declaration can be made within the body of a function.
§ Which are called local variables. The scope, that is the visibility
and validity of the variables are local.
§ Local variables are the variables apply only to that particular
function, are distinct from other variables of the same name (if
any) declared elsewhere in the program outside the function.
§ It is declared, initialized and use like any other variable.
§ Outside of any functions, those variables are called global
variables.
C FUNCTIONS
§ Function program example: local and global variable

§ The function parameters are considered to be variable


declarations.
§ Function prototype normally placed before main() and your
function definition after main() as shown below.
§ For C++, the standard said that we must include the prototype but
not for C.
#include … C FUNCTIONS
/* function prototype
*/ But it is OK if we directly declare and define the function
int funct1(int); before main() as shown below.
#include …
int main()
{ /* declare and define */
/* function call int funct1(int x)
*/ {
int y = …
funct1(3); }

} int main()
{
/* Function /* function call */
definition */ int y = funct1(3);
int funct1(int x) …
{…} }

Three rules govern the use of variables in functions:

1. To use a variable in a function, we must declare it in the function header or the


function body.
2. For a function to obtain a value from the calling program (caller), the value must be
passed as an argument (the actual value).
3. For a calling program (caller) to obtain a value from function, the value must be
explicitly returned from the called function (callee).
C FUNCTIONS
The Function Statements

§ Any statements can be included within a function, however a function may


not contain the definition of another function.
§ For examples: if statements, loop, assignments etc are valid statements.

Returning a Value

§ A function may or may not return a value.


§ If function does not return a value, then the function return type is said to
be of type void.
§ To return a value from a function, use return keyword, followed by C
expression.
§ The value is passed back to the caller.
§ The return value must match the return data type.
§ A function can contain multiple return statements.

§ Program example: multiple


return statement
C FUNCTIONS
The Function Prototype

§ Must be included for each function that will be defined, (required by


Standards for C++ but optional for C) if not directly defined before
main().
§ In most cases it is recommended to include a function prototype in
your C program to avoid ambiguity.
§ Identical to the function header, with semicolon (;) added at the
end.
§ Function prototype includes information about the function’s return
type, name and parameters’ list and type.
§ The general form of the function prototype is shown below,
function_return_type function_name(type parameter1, type parameter2,…,
type parameterN)

§ An example of function prototype,


long cube(long);
C FUNCTIONS
§ Function prototype provides the C compiler the name and arguments of
the functions and must appear before the function is used or defined.
§ It is a model for a function that will appear later, somewhere in the
program.
§ From the previous prototype example, 'we' know the function is named
cube, it requires a variable of the type long, and it will return a value of
type long.
§ Then, the compiler can check every time the source code calls the
function, verify that the correct number and type of arguments are being
passed to the function and check that the return value is returned
correctly.
§ If mismatch occurs, the compiler generates an error message enabling
programmers to trap errors.
§ A function prototype need not exactly match the function header.
§ The optional parameter names can be different, as long as they are the
same data type, number and in the same order.
§ But, having the name identical for prototype and the function header
makes source code easier to understand.
C FUNCTIONS
§ Normally placed before the start of main() but must
be before the function definition.
§ Provides the compiler with the description of a function
that will be defined at a later point in the program.
§ Includes a return type which indicates the type of
variable that the function will return.
§ And function name, which normally describes what the
function does.
§ Also contains the variable types of the arguments that
will be passed to the function.
§ Optionally, it can contain the names of the variables
that will be returned by the function.
§ A prototype should always end with a semicolon ( ; ).
C FUNCTIONS
Passing Arguments to a Function

§ In order function to interact with another functions or


codes, the function passes arguments.
§ The called function receives the values passed to it and
stores them in its parameters.
§ List them in parentheses following the function name.
§ Program example: passing arguments
C FUNCTIONS
§ The number of arguments and the type of each argument must match
the parameters in the function header and prototype.
§ If the function takes multiple arguments, the arguments listed in the
function call are assigned to the function parameters in order.
§ The first argument to the first parameter, the second argument to the
second parameter and so on as illustrated below.

§ Basically, there are two ways how we can pass something to


function parameters,
1. Passing by value.
2. Passing by reference using array and pointer.
C FUNCTIONS
Macros and Inline Functions
§ If the same sequence of steps or instructions is required in several different
places in a program, you will normally write a function for the steps and call the
function whenever these steps are required. But this involves time overhead.
§ Also can place the actual sequence of steps wherever they are needed in the
program, but this increase the program size and memory required to store the
program. Also need retyping process or copying a block of program.
§ Use function if the sequence of steps is long. If small, use macros or inline
function, to eliminate the need for retyping and time overhead.

Macros

§ Need #define compiler directive. For example, to obtain just the area of a
triangle, we could create a macro,

03/01/16
C FUNCTIONS
§ Then, we can use it anywhere in the program e.g.,
printf("\nArea = %f\n", area(4.0, 6.0));

§ Example for finding an average of 4 numbers (a, b, c and


d),
#define avg(x, y) (x + y)/2.0

§ Then in the program we can define something like this,


avg1 = avg(avg(a, b), avg(c, d))

§ Doing the substitution,


avg4 = ((a + b)/2.0 + (c + d)/2.0) / 2.0

§ The drawback: nesting of macros may result in code that


difficult to read.
C FUNCTIONS Program example: macro

Inline Function
§ Is preferred alternative to the macro since it provides most of the features of
the macro without its disadvantages.
§ Same as macro, the compiler will substitute the code for the inline function
wherever the function is called in the program.
§ Inline function is a true function whereas a macro is not.
§ The best time to use inline functions is when:
1.There is a time critical function
2.That is called often
3.And is respectfully small
§ Use keyword __inline which is placed before the function.

Program example: inline function


C FUNCTIONS
Header Files and Functions

§ Header files contain numerous frequently used functions that programmers


can use without having to write codes for them.
§ Programmers can also write their own declarations and functions and store
them in header files which they can include in any program that may require
them (these are called user-defined header file which contains user defined
functions).

Standard Header File

§ To simplify and reduce program development time and cycle, C provides


numerous predefined functions.
§ These functions are normally defined for most frequently used routines.
§ These functions are stored in what are known as standard library which
consist of header files (with extension .h, .hh etc).
§ In the wider scope, each header file stores functions, macros, enum,
structures (struct) , types etc. that are related to a particular application or
task.
C FUNCTIONS
§ We need to know which functions that are going to use,
how to write the syntax to call the functions and which
header files to be included in your program.
§ Before any function contained in a header file can be
used, you have to include the header file in your
program. You do this by writing,
#include <header_filename.h>
§ This is called preprocessor directive, normally placed at
the top of your program.
§ You should be familiar with these preprocessor
directives, encountered many times in the program
examples previously discussed.
C FUNCTIONS
Using Predefined Functions from Header File

§ Complete information about the functions and the header file


normally provided by the compiler’s documentation.
§ For your quick reference: C standard library reference.

User-defined Header Files

§ We can define program segments (including functions) and store


them in files.
§ Then, we can include these files just like any standard header file in
our programs.

Program example:
user defined
function
C FUNCTIONS
§ Next, let convert the user defined function to header file.
§ Step: Add new header file to the existing project.
C FUNCTIONS
§ Step: Put the header file name.
C FUNCTIONS
§ Step: Cut the function definition from the source file
and paste it into the header file.
// a function definition
float Convert(float TempFer)
{
// return the result to the calling program
return ((TempFer - 32) * 5) / 9;
}
C FUNCTIONS
§ Step: Next, include the header file at the top, just after the #include
<stdio.h>.
§ Use double quotes because the header file is under the project folder/
sub folder instead of the default or VC++ ..\include sub folder.

#include "tempconverter.h"
C FUNCTIONS
Recursive Function
§ We cannot define function within function, but we can call the same
function within that function.
§ A recursive function is a function that calls itself either directly or
indirectly through another function.
§ Classic example for recursive function is factorial, which used in
mathematics.
§ Program example: recursive function
C FUNCTIONS
Passing an array to a function What are the output and
#include <stdio.h> the content of num &
// function prototype
mood variables after
void Wish(int, char[ ]); program execution was
void main(void) completed?
{
Wish(5, "Happy");
}
C FUNCTIONS
1. What are the two values passed to Wish()?
2. In Wish(), what becomes the value of num? What becomes the value of
mood? Write them in the provided boxes.
3. Notice that in both the prototype and the definition of Wish(), there is no
number in the brackets, giving the number of cells of mood[ ]. Can you
think why omitting this number makes the function more flexible for use in
other instances?
4. How can we tell that "Happy" is a character string? How can we tell that
mood[ ] should also be a character string?
5. If Wish() were called from main() with this statement, Wish(3,
"Excited"); , then what would be the output?

1. An integer 5 and a string "Happy".


2. num is an integer of 5 and mood is a string of "Happy".
3. This unsized array make the system decide the actual size needed for storage.
4. "Happy" is a character string because it is enclosed in the double quotes and an
array mood[ ] has been declared as a char type.
5. Only the first 3 alphabets from "Excited" will be displayed that is "I wish I'm Exc".
C FUNCTIONS
#include <stdio.h>

void Rusted(char[ ]);


Build this program, show
the output & what it do?
void main(void)
{
// all work done in function Rusted()...
Rusted("Test Test");
printf("\n");
}

void Rusted(char x[ ])
{
int j;
printf("Enter an integer: ");
scanf_s("%d", &j);
for(; j != 0; --j)
printf("In Rusted(), x = %s\n", x);
}

A funcHon call from main() that passes a character string and


callee will print the number of character string based on the user
input.
C FUNCTIONS
Function, Array and Pointers

§ Functions in C cannot return array types however they can return


pointers to arrays or a reference.
§ When you pass in the array, you're only passing in a pointer. So
when you modify the array's data, you're actually modifying the
data that the pointer is pointing at.
§ Functions shall not have a return type of type array or function,
although they may have a return type of type pointer or reference
to such things.
§ So, there shall be no arrays of functions, although there can be
arrays of pointers to functions.
§ Since arrays are not objects, you can't pass them in and out of
functions.
§ Pointers are objects, so you can pass a pointer to the first
element of an object.
C FUNCTIONS
§ Functions (including main()) are constructed automatically on
the 'stack' memory.
§ When functions return, the stack will be destroyed/rewound.
§ Hence, local variables, including array, will be destroyed,
leaving a garbage.
§ Program example:
passing arrays to a function using array notation.
§ Program example:
passing arrays to a function using pointer notation.
§ Program example:
passing arrays to a function & returning a pointer to the first
element of the array + global variable.
§ Program example:
passing arrays to a function & returning a pointer to the first
element of the array + static keyword.
§ Program example:
passing arrays to a function using pointer & return the array’s
content.
C FUNCTIONS
Output samples
C FUNCTIONS
Function and Pointers (Function Pointers)

§ We can use pointers to point to C functions because C


function have its memory address.
§ When we can point to it, then it is another way to invoke
it.
§ Function pointers are pointer variables which point to
functions.
§ Function pointers can be declared, assigned values and
then used to access the functions they point to.
§ The following is an example of function pointer
declaration,
int (*functptr)();
§ Here, functptr is declared as a pointer to a function
03/01/16

that returns int data type.


C FUNCTIONS
§ It is a de-referenced value of functptr, that is
(*funptr) followed by () which indicates a function,
which returns an integer data type.
§ The parentheses are essential in the declarations because
of the operators’ precedence.
§ The declaration without the parentheses as the following,
int * functptr();
§ Will declare a function functptr that returns an integer
pointer that is not our intention in this case.
§ In C, the name of a function, which used in an expression
by itself, is a pointer to that function.
§ For example, if a function, testfunct() is declared as
follows,
int testfunct(int xIntArg);
C FUNCTIONS
§ The name of this function, testfunct is a
pointer to that function.
§ Then, we can assign the function name to a
pointer variable functptr, something like this:
functptr = testfunct;
§ The function can now be accessed or called, by
dereferencing the function pointer,
/* calls testfunct() with xIntArg as an argument
then assign the returned value to nRetVal */
nRetVal = (*funptr)( xIntArg);

§ Program example: function pointers


C FUNCTIONS
C FUNCTIONS
§ Function pointers can be passed as parameters in function calls and can be
returned as function values.
§ It’s common to use typedef with complex types such as function pointers
to simplify the syntax (typing).
§ For example, after defining,

typedef int (*functptr)();

§ The identifier functptr is now a synonym for the type of 'a pointer to a
function which takes no arguments and returning int type'.
§ Then declaring pointers such as pTestVar as shown below, considerably
simpler,

functptr pTestVar;

§ Another example, you can use this type in a sizeof() expression or as a


function parameter as shown below,

/* get the size of a function pointer */


unsigned pPtrSize = sizeof (int (*functptr)());
/* used as a function parameter */
void signal(int (*functptr)());
C FUNCTIONS

§ The following table summarizes the various


ways of using functions.
§ We can categorize functions by whether or not
arguments are passed to them.
§ Or we can categorize them by whether or not
values are received from them.
§ Intersecting these two methods of categorizing
functions, we come up with four basic methods
of writing and using functions.
C FUNCTIONS
Do not pass argument Do pass arguments
void main(void) void main(void)
{ {
TestFunct(); TestFunct(123);
... ...
} }

void TestFunct(void) void TestFunct(int i)


No return
{ {
// receive nothing // receive something and
// and nothing to be // the received/passed
// returned // value just
} // used here. Nothing
// to be returned.
}
void main(void) void main(void)
{ {
x = TestFunct(); x = TestFunct(123);
... ...
} }

With a return int TestFunct(void) int TestFunct(int x)


{ {
// received/passed // received/passed something
// nothing but need to // and need to return something
// return something return (x + x);
return 123; }
}
Preprocessor

Preprocessor DirecHves DescripHon

#define PI 3.14
During preprocessing, the preprocessor replaces every occurrence of PI in the program with 3.14.
It simply causes the en7re contents of filename (stdio.h) to be inserted into the source code at that point in the
#include<stdio.h>
program.
#ifdef MACRO If MACRO has been #defined, the block of code will be processed as usual; otherwise not.
//code #endif

#ifndef MACRO The #ifndef

(which means ‘if not defined’) works exactly opposite to


//code #ifdef.

#endif

#if NUMBER > 5


//code
#if direc7ve can be used to test whether an expression evaluates to a nonzero value or not. If the
#elif NUMBER < -10

//code #else
result of the expression is nonzero, then

//code subsequent lines up to a #else, #elif or #endif are compiled, otherwise they are skipped.
#endif

#undef PI In order to undefined a macro that has been earlier #defined.

#pragma startup #pragma exit Startup to specify func7ons that are called upon program startup (before main( )) exit to specify func7ons that are called upon
#pragma warn
program exit (arer

main( )). Warn tells the compiler whether or not we want to suppress a specific warning. Pragmas vary from one compiler to

another.
Note: Pragmas vary from one compiler to another. There are certain pragmas available with Microsor C compiler that deal with
forma[ng source lis7ngs and placing comments and the object file generated by the compiler. Turbo C compiler has got a pragma
that allows you to suppress warnings in your C programs.
Preprocessor Example:

#include<stdio.h void fun2(); int f1();


> #define PI 3.14 #pragma startup fun1
#define NUMBER 10 #pragma exit fun2
#pragma warn –rvl /* return value */
#define AREA(x) ( PI * x
* x ) void fun1();
Global Variables
POINTERS
Point to here, point to there, point to that, point to
this, and point to nothing!
well, they are just memory addresses!!??
POINTERS
◆ When declaring a variable, the compiler sets aside
memory storage with a unique address to store that
variable.
◆ The compiler associates that address with the
variable’s name.
◆ When the program uses the variable name, it
automatically accesses a proper memory location.
◆ No need to concern which address.
◆ But we can manipulate the memory address by using
pointers.
◆ Let say we declare a variable named nRate of type
integer and assign an initial value as follows,
int nRate = 10;
POINTERS
#include <stdio.h>
void main(void)
{
int nRate = 10;
printf("variable name is nRate.\n");
// or sizeof(int)
printf("size of nRate (int) is %d bytes.\n",
sizeof(nRate));
printf("size of short int is %d bytes.\n",
sizeof(short int));
printf("initial value stored at nRate is %d.\n", nRate);
printf("memory address of nRate is %p.\n",
nRate);
}
POINTERS
◆ The variable is stored at specific memory
address and can be depicted as follows,
POINTERS
◆ The variable scope is local to the main() function.
◆ The memory allocation is from the main() function's
stack.
◆ The nRate memory address (or any other variable)
is a number, so can be treated like any other number
in C.
◆ Using %p, the address is in hexadecimal format.
◆ Hence, if a variable’s memory address is 'known', we
can create a second variable for storing the memory
address.
◆ From the previous example, let declare another
variable, named pTonRate to hold the address of
nRate variable.
POINTERS
◆ At the beginning, pTonRate is uninitialized.
◆ So, storage has been allocated for pTonRate, but its initial
value is undetermined, as shown below,
POINTERS
◆ Let store the nRate's memory address, in pTonRate variable.
◆ So, pTonRate now holds the nRate's memory address, where the actual data (10) is
stored.
◆ Finally, in C vocabulary, pTonRate is pointing to nRate or is said a pointer to nRate
and can be illustrated as follows,
POINTERS

◆ So, the pointer variable declaration becomes something like this,


int *pTonRate;
◆ In other word, the pTonRate variable holds the memory address of
nRate and is therefore a pointer to nRate.
◆ The asterisk (*) is used to show that is it the pointer variable instead of
normal variable.

Definition: A pointer is a variable that holds memory


address of another variable, where, the actual data is
stored.
POINTERS
◆ By using pointers, it is an efficient way of accessing and
manipulating data.
◆ Very useful for dynamic memory management, as we know
memory, registers and cache are scarce resource in computer
system.
◆ Every computer system, there are fixed and limited amount of
memory for temporary data storage and processing.
◆ There are loading and unloading data into and from, moving data
from and to different locations of the memory, including the cache
and the processors’ registers for temporary data storage and
processing.
◆ The loading and unloading need an efficient memory
management.
◆ Some of the memory portion also used for shared data to further
optimizes the utilization.
◆ This shared data access (read/write) depends heavily on the
www.tenouk.com, ©
pointers manipulation.
◆ Without moving/loading/unloading data to/from different locations
in memory, we can use pointers to point to different locations.
POINTERS
Pointers and Simple Variables

◆ A pointer is a numeric variable and like other variables, must be declared and
initialized before it can be used.
◆ The following is a general form for declaring a pointer variable,

type_of_stored_data * pointer_variable_name;

◆ For example,

char* chName;
int * nTypeOfCar;
float *fValue;

◆ type_of_stored_data is any valid pointer base type such as char, int, float
or other valid C derived types such as array and struct.
www.tenouk.com, ©

◆ It indicates the type of the variable’s data to which the pointer is pointed to.
◆ The pointer_variable_name follows the same rules as other C variable naming
convention and must be unique.
POINTERS
◆ From the pointer declaration examples, in the first line, the declaration
tells us that chName is a pointer to a variable of type char.
◆ The asterisk (*) is called indirection operator, and it indicates that
chName is a pointer to type char and not a normal variable of type
char.
◆ Note the position of the *, it is valid for all the three positions.
◆ Pointers can be declared along with non pointer variables as shown
below,

// chFirstName and chSecondName both are


pointers to
// type char while chInitial is normal char
type variable
char *chFirstName, *chSecondName,
chInitial;
// fValue is a pointer to type float, and
fPercent
// is an ordinary float type variable.
float *fValue, fPercent;
POINTERS
Initializing Pointers

◆ Once a pointer is declared, we must initialize it.


◆ This makes the pointer pointing to something.
◆ Don’t make it point to nothing; it is dangerous.
◆ Uninitialized pointers will not cause a compiler error, but using an
uninitialized pointer could result in unpredictable and potentially
disastrous outcomes.
◆ Until pointer holds an address of a variable, it isn’t useful.
◆ C uses two pointer operators,
1. Indirection operator (*) – asterisk symbol, has been explained
previously.
2. Address-of-operator (&) – ampersand symbol, means return
the address of…

◆ When & operator is placed before the name of a variable, it will


returns the memory address of the variable instead of stored
value.
POINTERS
◆ Program example: initializing a pointer

◆ In this example, pointer variable, pToInt receives the


address of nLocation or
◆ The memory address of the nLocation variable is
assigned to pToInt pointer variable.
POINTERS
◆ Graphically this situation can be illustrated as shown below.

◆ The * operator is a complement of & operator.


◆ * means returns the current value of the variable pointed to.
POINTERS
◆ From the previous example, if we declare another variable of type
int,

int anotherVar;
int * pToInt;
pToInt = &nLocation;
nLocation = 100;

◆ Then, statement,

anotherVar = *pToInt;

◆ will place the actual current data value stored in variable nLocation
into variable anotherVar.
◆ Which means anotherVar was assigned the actual current data
value stored at the memory address held by pToInt.
◆ The * operator appears before a pointer variable in only two places:

When declaring a pointer variable.


When de-referencing a pointer variable (to show the data it‘s
pointed to).
POINTERS
Using Pointers

◆ Only the addition and subtraction operations are permitted in


pointer's expression.
◆ As with any variable, a pointer may be used on the right hand side
of an assignment statement to assign its value to another pointer
as shown in the following example.
◆ Program example: using pointers
POINTERS
◆ The situation can be illustrated as shown below. The memory address
should be different for different run/system.

◆ Take note the difference between memory address and the actual data value,
which stored at the memory address.
◆ Do not worry about the address, which are determined and provided by the
system.
◆ From the previous example, we can:
1. Access the variable's content by using the variable name (iNum) and is
called direct access.
2. Access the variable's content by using a pointer to the variable
(*iPointerOne or *iPointerTwo) and is called indirect access or
indirection.
POINTERS
◆ As a conclusion, if a pointer named pPointerVar of type
int has been initialized to point to a variable named
iNumVar, the following are true,

// declare a pointer variable named


pPointerVar, where the
// data stored pointed to by pPointerVar is
int type
int * pPointerVar;
// assign the iNumVar's address to pPointerVar
pointer variable
pPointerVar = &iNumVar;

◆ * pPointerVar and iNumVar both refer to the contents of


iNumVar (that is, whatever data value stored there).
◆ pPointerVar and &iNumVar refer to the address of
iNumVar (the pPointerVar only hold the address of variable
iNumVar not the actual data value).
◆ So, a pointer name without the indirection operator (*)
accesses the pointer value itself, which is of course, the
address of the variable pointed to.
POINTERS
◆ Program example: using pointers operator

◆ The address displayed for variable iNormVar may be


different on your system because different computer will
have different specification.
POINTERS
◆ For pointer arithmetic operation, only two arithmetic
operations, that is addition and subtraction available. For
example,

int iAge = 35;

◆ Hence, C reserved storage for the variable iAge and store


the value 35 in it.
◆ Let say, C has stored this value at the memory address
1000, then we declare a pointer variable named
pPointerToAge that point to the iAge variable.
◆ Then, after the following expressions have been executed,

int * pPointerToAge;
pPointerToAge = &iAge;
pPointerToAge++;

◆ The content of the pointer then becomes 1004 instead of


1001 (integer value takes 4 bytes so C add 4 to the
pointer).
POINTERS
◆ Different variable types occupy different amount of
memory, implementation dependent, following C
standard or implementation extension and whether 16,
32 or 64 bits system.
◆ Each time the pointer is incremented, it points to the
next integer and similarly, when a pointer is
decremented, it points to the previous integer.
◆ Each individual byte of memory has its own address; so
multi-byte variable actually occupies several addresses.
◆ When pointers used to handle the addresses of multi-
byte variables, the address of a variable is actually the
address of the lowest byte it occupies.
◆ For example,

int iNum = 12252; // 4 bytes


char chVar = 90; // 1 byte
float fVar = 1200.156004; // 4 bytes
POINTERS
◆ The pointer variables are pointing to the lowest byte of
variable memory slots e.g: iNum occupies 4 bytes and
chVar occupies 1 byte.
◆ Other pointer arithmetic operation is called differencing,
which refers to subtracting two pointers.
◆ For example, two pointers that point to different elements
of the same array can be subtracted to find out how far
apart they are.
◆ Pointer arithmetic automatically scales the answer, so that
it refers to the array elements.
◆ Thus, if pPointer1 and pPointer2 point to elements of
an array (of any type), the following expression tells you
how far apart the elements are,

pPointer1 – pPointer2;
POINTERS
◆ However ptrdiff_t type can be used to return
the subtraction operation between two pointers.
◆ It is a base signed integer type of C/C++
language.
◆ The type's size is chosen so that it could store the
maximum size of a theoretically possible array of
any type.
◆ On a 32-bit system ptrdiff_t will take 32 bits,
on a 64-bit one 64 bits.
◆ The ptrdiff_t type enable you to write well-
portable code.
◆ ptrdiff_t (together with wchar_t and size_t)
defined in stddef.h (cstddef for C++).
POINTERS
Pointers Comparison

◆ The comparison is valid only between pointers that point to the


same array.
◆ The following relational operators work for pointers operation:
==, !=, >, <, >= and <=.
◆ A lower array element that is those having a smaller subscript,
always have a lower address than the higher array elements.
◆ Thus if pPointer1 and pPointer2 pointing to the elements of
the same array, the following comparison is TRUE,

pPointer1 < pPointer2

◆ If pPointer1 points to an earlier member of the array than


pPointer2 does.
◆ Many arithmetic operations that can be performed with regular
variables, such as multiplication and division, do not work with
pointers and will generate errors in C.
POINTERS
◆ The following table summarizes pointer operations.

Operation Description
You can assign a value to a pointer. The
1. Assignment value should be an address with the address-
(=) of-operator (&) or from a pointer constant
(array name)
2. Indirection The indirection operator (*) gives the value
(*) stored in the pointed to location.
You can use the address-of operator to find
3. Address of
the address of a pointer, so you can use
(&)
pointers to pointers.
You can add an integer to a pointer to point to
4. Incrementing
a different memory location.
You can subtract an integer from a pointer to
5. Differencing
point to a different memory location.
Valid only with two pointers that point to the
6. Comparison
same array.
POINTERS
Uninitialized Pointers Issue

◆ Let say we have declared a pointer something like this,

int *iPtrVar;

◆ This statement declares a pointer to type int but not yet initialized, so it
doesn’t point to anything known value (address).
◆ Then, consider the following pointer assignment statement,

// this is not an address that system allocate!


*iPtrVar = 121;
POINTERS
◆ This statement means the value of 121 is assigned to whatever
address (00??????) iPtrVar is pointing to.
◆ That address can be anywhere in memory which may contain critical
data.
◆ The 121 stored in that location may overwrite some important
information, and the result can be anything from program error to a
full system crash.
◆ We must initialize a pointer so that it point to something. Do not
create a stray pointer.
◆ A better solution, we can assign NULL (\0) value during the
initialization before using it, such as,

int *iPtrVar = NULL; /* null pointer, pointing to


something but nothing */

◆ For pointer that point to a string you may just point to an empty string
for a dummy such as,

char *chMyString = " ";

◆ The .NET C/C++ programming uses nullptr instead of NULL. The


◆ NULL/nullptr is a pointer that point to the 0x00000000 (32 bits
system) memory address.
POINTERS
◆ Program example: NULL pointer and empty string
POINTERS
Arrays and Pointers

◆ A special relationship exists between pointers and arrays.


◆ An array name without brackets is a pointer to the array’s first
element.
◆ So, if a program declared an array,

char chName[10];

◆ chName (array’s name) is the address of the first array


element and is equivalent to the expression,

&chName[0]

◆ Which is a reference to the address of the array’s first element.


◆ chName equivalent to &chName[0].
◆ The array’s name is, therefore a pointer to the array’s first
element and therefore to the string if any.
POINTERS
◆ A pointer is a constant, which cannot be changed and
remains fixed for the duration of program execution.
◆ Many string operations in C are typically performed by
using pointers because strings tend to be accessed in
a strictly sequential manner.
◆ Program example: pointers and array
POINTERS
◆ Which can be illustrated as follows,
POINTERS
◆ Let take a look at the following example: pointers and
array

◆ Notice the difference between the element addresses.

12FF40 – 12FF3C = 4 bytes for int


12FF04 – 12FF00 = 4 bytes float
12FEB0 – 12FEA8 = 8 bytes double
POINTERS
◆ Try another program example: pointers and array access
POINTERS
▪ Let re-cap, if an array named iListArray[ ] is a declared array,
the expression * iListArray is the array’s first element,
*( iListArray + 1) is the array’s second element, and so on.
▪ Generally, the relationship is,

*(iListArray) == iListArray[0] // first


element
*(iListArray + 1) == iListArray[1] // second
element
*(iListArray + 2) == iListArray[2] // third
element
...
...
*(iListArray + n) == iListArray[n] // the nth
element

▪ So, you can see the equivalence of array subscript notation and
array pointer notation.
POINTERS
Arrays of Pointers and Function

◆ Pointers may be arrayed like any other data type.


◆ For example, a pointer array iArrayPtr of sized 20 is
declared as,

int *iArrayPtr[20];

◆ To assign the address of an integer variable called


iIntVar to the first element of the array, we could write
something like this,

// assign the address of variable


// iIntVar to the first iArrayPtr element
iArrayPtr [0] = &iIntVar;
POINTERS
◆ Graphically can be depicted as follows,
POINTERS

◆ To find the value stored in iIntVar, we could write


something like this,

iArrayPtr[0]

◆ To pass an array of pointers to a function, we simply


call the function with the array’s name without any
index/subscript, because this is an automatically a
pointer to the first element of the array, as explained
before.
◆ For example, to pass the array named iArrayPtr to
viewArrayFunc() function, we use the following
statement,

viewArrayFunc(iArrayPtr);
POINTERS
Pointers to Pointers

◆ Graphically, the construct of a pointer to pointer


can be illustrated as shown below.
◆ iPointerOne is the first pointer, pointing to the
second pointer, iPointerTwo and finally
iPointerTwo is pointing to a normal variable
iNum that hold integer 100.
POINTERS
▪ In order to indirectly access the target value pointed to
by a pointer to a pointer, the asterisk operator must be
applied twice. For example,

int **iPointerOne;

▪ Tells compiler that iPointerOne is a pointer to a


pointer of type integer.
▪ Pointer to pointer is rarely used but you will find it
regularly in programs that accept argument(s) from
command line.
▪ Consider the following declarations,

char chVar; /* a normal character


variable */
char *pToChar; /* a pointer to a
character */
char **pToCharPointer; /* a pointer to a
pointer to a character */
POINTERS
◆ If the variables are related as shown below,

◆ We can do some assignment like this,


chVar = 'A';
pToChar = &chVar;
pToCharPointer = pToChar;

◆ Recall that char * (which is *pToChar in this case) refers


to a NULL terminated string.
◆ Then, we can declare a pointer to a pointer to a string
something like this,
POINTERS
◆ Taking this one stage further we can have several
strings being pointed to by the integer pointers
(instead of char) as shown below,

POINTERS
Then, we can refer to the individual string by using
pToCharPointer[0], pToCharPointer[1],…. and generally, this
is identical to declaring,

char * pToCharPointer[ ]; /* an array of


pointer */

◆ Or from last figure,

char ** pToCharPointer;

◆ Thus, programs that accept argument(s) through command line, the


main() parameter list is declared as follows,

int main(int argc, char **argv)

◆ Or something like this,

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

◆ Where the argc (argument counter) and argv (argument vector) are
equivalent to pToChar and pToCharPointer respectively.
POINTERS
◆ For example, program that accepts command line
argument(s) such as echo,

◆ This can be illustrated as,


POINTERS
▪ So our main() function now has its own arguments.
▪ As a convention, these are the only arguments main()
accepts.
▪ Notice that the argv[0] is an application name.
▪ argc (argument counter) is the number of arguments
(unsigned integer), which we input including the program
name.
▪ argv (argument vector) is an array of strings (argv[0],
argv[1], argv[2],...) holding each command line
argument including the program name that is the first array
element, argv[0].
▪ But some implementation will have another third parameter,
envp/env, which is a pointer to an environment variable as
shown below.

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


*envp[ ])

▪ Environment variable in Operating System is an array of


strings.
POINTERS
◆ Let try a program example (this program must be run at
command prompt)
POINTERS
▪ Another pointer-to-pointer example
NULL Pointer Constant
POINTERS
◆ The null pointer constant is guaranteed not to point to any
real object.
◆ You can assign it to any pointer variable since it has type void
*.
◆ The preferred way to write a null pointer constant is with NULL.

char * pNulPointer = NULL; or


char * pNulPointer = nullptr;

◆ NULL pointer when set, actually pointing to memory address


0x00000000 (32 bits).
◆ The computer systems have reserved this zero address for
NULL pointer and that is why it cannot be used for other
purposes.
◆ (in C++ .NET programming, nullptr is used as the keyword
instead of NULL)
◆ Since C functions can only return one variable, it is common
practice for those which return a pointer is set to NULL, can
avoid the stray pointer.
◆ Set a pointer to NULL to indicate that it’s no longer in use.
POINTERS
void Pointers

◆ There are times when you write a function but do not know
the data type of the returned value.
◆ When this is the case, you can use a void pointer, a pointer
of type void.

◆ Program example: void pointer


POINTERS
◆ Other pointer declarations that you may find and can make
you confused are listed below.

Pointer declaration Description


int *x x is a pointer to int data type.
int *x[10] x is an array[10] of pointer to int data type.
int *(x[10]) x is an array[10] of pointer to int data type.
x is a pointer to a pointer to an int data type – double
int **x
pointers.
int (*x)[10] x is a pointer to an array[10] of int data type.
int *funct() funct() is a function returning an integer pointer.
int (*funct) funct() is a pointer to a function returning int data
() type – quite familiar constructs.
int
funct() is a function returning pointer to an
(*(*funct())
array[10] of pointers to functions returning int.
[10])()
int (*(*x[4]) x is an array[4] of pointers to functions returning
())[5] pointers to array[5] of int.
POINTERS
And something to remember!

* - is a pointer to…
[] - is an array of…
() - is a function returning…
& - is an address of…
STRUCT, TYPEDEF,
ENUM & UNION
In this session we will learn struct and union types,
typedef and enum
STRUCT, TYPEDEF, ENUM & UNION
Structure (struct)

§ With array, we can only declare one data type per array.
§ For different data type, we need another array
declaration.
§ It is single type aggregate data type.
§ Struct overcomes this problem by declaring composite
data types which can consist different types.
§ A structure is a collection of related data items stored in
one place and can be referenced by more than one
names.
§ These data items are different basic data types. So, the
number of bytes required to store them may also vary.
§ A structure type is a user-defined composite type.
§ It is composed of fields or members which can be
different types.
STRUCT, TYPEDEF, ENUM & UNION
§ In C++, a struct is same as a class except that its
members are public by default.
§ In order to use a structure, we must first declare a structure
template.
§ The variables in a structure are called elements or members.
§ In C, you must explicitly use the struct keyword to declare a
structure however in C++, this is unnecessary, once the type
has been defined.
§ In C99, the allowable data types for a bit field include qualified
and unqualified _Bool, signed int, and unsigned int.
§ The default integer type for a bit field is signed.
§ You have the option of declaring variables when the structure
type is defined by placing one or more comma-separated
variable names between the closing brace and the semicolon.
STRUCT, TYPEDEF, ENUM & UNION
§ Structure variables can be initialized. The initialization for each
variable must be enclosed in braces.
§ Both structure types and variables follow the same scope as
normal variables, as do all identifiers.
§ If you define a structure within a function, then you can only use
it within that function.
§ Likewise if you define a structure outside of any function then it
can be used in any place throughout your program.
§ Example, to store and process a student’s record with the
elements chIdNum (identification number), chName, chGender
and nAge, we can declare the following structure,

struct student {
char chIdNum[5];
tag char chName[10];
char chGender;
int nAge;
};
STRUCT, TYPEDEF, ENUM & UNION

§ Here, struct is a keyword that tells the compiler


that a structure template is being declared and
student is a tag that identifies its data structure.
§ Tag is not a variable; it is a label for the structure’s
template.
§ Note that there is a semicolon after the closing
curly brace.
§ A structure tag simply a label for the structure’s
template but you name the structure tag using the
same rules for naming variables.
STRUCT, TYPEDEF, ENUM & UNION
§ The previous sample template for the structure
can be illustrated as follow (note the different
data sizes),
STRUCT, TYPEDEF, ENUM & UNION
Define, declare and initialize

§ Compiler will not reserve memory for a structure until it is


declared.
§ A structure declaration names a type and specifies a sequence
of variable values called 'members' or 'fields' of the structure
that can have different types.
§ An optional identifier, called a 'tag', gives the name of the
structure type and can be used in subsequent references to
the structure type.
§ A variable of that structure type holds the entire sequence
defined by that type.
§ Declaring structure variables can be done in the following way,
struct MyEmployee // defines a structure variable named EmpData
{ char chName[20];
int nIdNum;
long nDepatment;
} EmpData;
STRUCT, TYPEDEF, ENUM & UNION
§ The struct MyEmployee structure has three
members: chName, nIdNum, and nDepatment.
§ The chName member is a 20-element array, and
nIdNum and nDepatment are simple members
with int and long types, respectively.
§ The identifier MyEmployee is the structure
identifier.
§ Then we can declare variables of type struct
MyEmployee like the following,
struct MyEmployee student, staff, academician;

Struct basic example


STRUCT, TYPEDEF, ENUM & UNION
§ Another example, anonymous struct (struct without
tag),
Struct /* defines an anonymous struct and a */
{ /* structure variable named area */
float fwidth, flength;
} area;

§ The area structure has two members with float type,


fwidth and flength.
§ The structure type has no tag and is therefore is unnamed
or anonymous.
§ The nested structures, called anonymous structures allows
you to declare a structure variable within another structure
without giving it a name.
§ However, C++ does not allow anonymous structures.
§ You can access the members of an anonymous structure
as if they were members in the containing structure.
STRUCT, TYPEDEF, ENUM & UNION
§ Anonymous structure example
STRUCT, TYPEDEF, ENUM & UNION
§ Anonymous structures can be useful when the tag named
is not needed.
§ This is the case when one declaration defines all structure
instances.
§ Embedded or nested structures are often anonymous. For
example,
struct MyCube{
struct /* anonymous structure */
{
int width, length;
} area;
int height;
} CubeData;

§ Nested structures can also be accessed as though they


were declared at the file-scope level.
STRUCT, TYPEDEF, ENUM & UNION
§ Nested structure example
STRUCT, TYPEDEF, ENUM & UNION
§ Optionally, we can declare variables when the
structure type is defined by placing one or more
comma-separated variable names between the
closing brace and the semicolon.
§ Structure variables can be initialized.
§ The initialization for each variable must be
enclosed in braces.
§ Define & declare structure example
STRUCT, TYPEDEF, ENUM & UNION
§ Define, declare & initialize a structure example

§ Define, declare & initialize a structure example 2


STRUCT, TYPEDEF, ENUM & UNION
Declaring and Using Bit Fields in Structures

§ A structure declarator can also be a specified


number of bits, called a 'bit field'.
§ Its length is set off from the declarator for the field
name by a colon.
§ A bit field is interpreted as an integral type.
§ Both C and C++ allow integer members to be stored
into memory spaces smaller than the compiler would
ordinarily allow.
§ These space-saving structure members bit fields,
and their width in bits can be explicitly declared.
§ Used in programs that must force a data structure to
correspond to a fixed hardware representation and it
is not portable.
STRUCT, TYPEDEF, ENUM & UNION
§ A bit field declaration contains a type specifier followed by an
optional declarator, a colon, a constant integer expression that
indicates the field width in bits, and a semicolon.
type-specifier declarator opt : constant-expression;

§ A bit field declaration may not use either of the type qualifiers,
const or volatile.
§ The following structure example has four bit-field members
left, right, front and rear, occupying 4, 3, 4 and 5 bits
respectively,
struct direction { // declare direction bit field
int left : 4; // 00000000 0000XXXX
int right : 3; // 00000000 0XXX0000
int front : 4; // 00000XXX X0000000
int rear : 5; // XXXXX000 00000000
};

§ In this case, total bits is 16, equal to 2 bytes.


STRUCT, TYPEDEF, ENUM & UNION

§ The following restrictions apply to bit


fields. You cannot,

1. Define an array of bit fields.


2. Take the address of a bit field.
3. Have a pointer to a bit field.
4. Have a reference to a bit field.
STRUCT, TYPEDEF, ENUM & UNION
Alignment of Bit Fields
§ If a series of bit fields does not add up to the size of an int, padding
can take place.
§ The amount of padding is determined by the alignment
characteristics of the members of the structure.
§ The following example demonstrates padding.
§ Suppose that an int occupies 4 bytes (4 x 8 = 32 bits). The example
declares the identifier onoffpower to be of type struct
switching,
struct switching {
unsigned light : 1;
unsigned fridge : 1;
int count; /* 4 bytes */
unsigned stove : 4;
unsigned : 4;
unsigned radio : 1;
unsigned : 0;
unsigned flag : 1;
} onoffpower ;
STRUCT, TYPEDEF, ENUM & UNION
§ The structure switching contains eight members totaling 16 bytes.
§ The following table describes the storage that each member
occupies,
Member Name Storage Occupied Total Total
light 1 bit 1 bit
fridge 1 bit 1 bit 32 bits
(padding up to 30 bits) To the next int boundary 30 bits
count The size of an int (4 bytes) 4 x 8 = 32 bits 32 bits
stove 4 bits 4 bits
(unnamed field) 4 bits 4 bits
radio 1 bit 1 bit 32 bits
To the next int boundary 23 bits
(padding up to 23 bits)
(unnamed field)
flag 1 bit 1 bit
32 bits
(padding up to 31 bits) To the next int boundary 31 bits
16 bytes = 64 bits 4 x 32 bits = 128 bits 128 bits
STRUCT, TYPEDEF, ENUM & UNION
§ All references to structure fields must be fully qualified. For instance,
you cannot reference the second field by fridge.
§ You must reference this field by onoffpower.fridge.
§ The following expression sets the light field to 1,

onoffpower.light = 1;

§ When you assign to a bit field a value that is out of its range, the bit
pattern is preserved and the appropriate bits are assigned.
§ The following expression sets the fridge field of the onoffpower
structure to 0 because only the least significant bit is assigned to the
fridge field,

onoffpower.fridge = 2;

§ But the following expression sets the fridge field of the onoffpower
structure to 1.

onoffpower.fridge = 5;
STRUCT, TYPEDEF, ENUM & UNION
§ Bit fields structure example

§ Real implementation examples can be found in the Linux


socket programming in
fabricating the udp, tcp, ip and other protocol headers.
STRUCT, TYPEDEF, ENUM & UNION
Accessing the Structure Member

§ A "member-selection expression" refers to


members of structures (and unions, classes).
§ Such an expression has the value and type of the
selected member.
§ The member access operators . (dot) and ->
(arrow: minus + greater than symbols) are used
to refer to members of structures (also unions
and classes).
§ Member access expressions have the value and
type of the selected member.
§ There are two methods that can be used to
access the members using dot or an arrow
operator.
STRUCT, TYPEDEF, ENUM & UNION
§ The two syntaxes are,
1. postfix-expression. Identifier
2. postfix-expression –> identifier
§ In the first form, postfix-expression represents a value of
struct (or union, class object) type and identifier names a
member of the specified structure (or union, class object).
§ The value of the operation is that of identifier and is an left-
value if postfix-expression is an left-value.
§ In the second form, postfix-expression represents a pointer to
a structure or union, and identifier names a member of the
specified structure or union.
§ The value is that of identifier and is an left-value.
§ The two forms of member-selection expressions have similar
effects.
STRUCT, TYPEDEF, ENUM & UNION
§ An expression involving arrow member-selection
operator (->) is a shorthand version of an
expression using the dot (.) if the expression
before the dot consists of the indirection operator
(*) applied to a pointer value.
§ Therefore,
expression->identifier
§ is equivalent to,
(*expression).identifier
§ provided that expression is a pointer value
which is normally the case.
STRUCT, TYPEDEF, ENUM & UNION
§ How to access structure member example

§ A member-selection expression for the justitem


structure is,
justitem.pSctPtr = &justitem;
§ In this case, the address of the justitem structure is
assigned to the pSctPtr member of the structure.
§ This means that justitem contains a pointer to itself.
STRUCT, TYPEDEF, ENUM & UNION
(justitem.pSctPtr)->nNumA = 33;
§ In this case, the pointer expression
justitem.pSctPtr is used with the member-
selection operator (–>) to assign a value of 33 to
the member nNumA.
justalist[8].nNumB = 44;
§ This statement shows how to access and select
an individual structure member from an array of
structures.
§ An integer 44 was assigned to nNumB
justalist's ninth structure member.
STRUCT, TYPEDEF, ENUM & UNION
Arrays of Structures

§ Suppose you would like to store and manipulate the record of 100
students.
§ It would be tedious and unproductive to create 100 different student
array variables and work with them individually.
§ It would be much easier to create an array of student structures.
§ Structures of the same type can be grouped together into an array.
§ We can declare an array of structures just like we declare a normal
array variable.
§ e.g., for 100 student records, we can declare a structure like the
following,

struct student{
int nIdNum, nAge;
char chName[80];
char chGender;
}studRecord[100];
STRUCT, TYPEDEF, ENUM & UNION
§ Or something like the following statements,
struct student{
int nIdNum, nAge;
char chName[80];
char chGender;
};
§ And later in our program we can declare
something like this,
struct student studRecord[100];
§ This statement declares 100 variables of type
struct student.
STRUCT, TYPEDEF, ENUM & UNION
§ As in arrays, we can use a subscript to reference a
particular student record.
§ For example, to print the name of the seventh student, we
could write the following statement,
printf("%\n", studRecord[6].chName;
§ Example of initializing all the student names to blanks and
their ages to 0, we could do this simply by using for loop
as shown below,
for(i=0; i<100; i++)
{
studRecord[i].chName = " ";
studRecord[i].nAge = 0;
}
STRUCT, TYPEDEF, ENUM & UNION
§ Array of structure program example
STRUCT, TYPEDEF, ENUM & UNION
§ Example demonstrates structure containing arrays
STRUCT, TYPEDEF, ENUM & UNION
§ Example demonstrates array of structure that containing
arrays
§ So, take
note on
the
difference
between
an array
of
structure
and
structure
containing
array.
STRUCT, TYPEDEF, ENUM & UNION
Structure and Function

§ Structure variables may be passed as arguments


and returned from functions just like scalar
variables.
§ Let take a look at the following program example.
STRUCT, TYPEDEF, ENUM & UNION
§ We have declared the structure, inventory, at the top of the source
file.
§ This is called an external declaration and the scope is the entire file
after the declaration.
§ Since all the functions in the file use this structure tag, the structure
must be visible to each of them.
§ The main() calls readpart() to read data into a structure and return
it to be assigned to the variable, items.
§ Next, it calls printpart() passing items which merely prints the
values of the structure fields, one at a time.
§ External declarations of structure templates and prototypes facilitate
consistent usage of tags and functions.
§ Sometimes, external structure tag declarations will be placed in a
separate header file, which is then made part of the source file by an
include directive (#include).
§ From this example, we can see that using structures with functions is
no different than using any scalar data type like int.
STRUCT, TYPEDEF, ENUM & UNION
§ When the function readpart() is called, memory is allocated for all of its local
variables, including the struct inventory variable, part.
§ As each data item is read, it is placed in the corresponding field of part,
accessed with the dot operator.
§ The value of part is then returned to main() where it is assigned to the variable
items.
§ As would be the case for a scalar data type, the value of the return expression is
copied back to the calling function.
§ Since this is a structure, the entire structure (each of the fields) is copied.
§ For our inventory structure, this isn't too bad because only two floats and an
integer.
§ If structure having many members or nested, many values would need to be
copied.
§ For call to printpart(), an inventory structure is passed to the function.
§ Recall that in C, all parameters are passed by value, hence the value of each
argument expression is copied from the calling function into the cell allocated for
the parameter of the called function.
§ Again, for large structures, this may not be a very efficient way to pass data to
functions.
STRUCT, TYPEDEF, ENUM & UNION
Structure, Function and Pointers

§ Passing and returning structures to functions


may not be efficient, particularly if the structure
is large.
§ We can eliminate this excessive data
movement and computer resources usage by
passing pointers to the structures to the
function, and access them indirectly through the
pointers.
§ The following example is a modified version of
our previous program which uses pointers
instead of passing entire structures.
STRUCT, TYPEDEF, ENUM & UNION
§ Structure, function and pointers example (using * operator)

§ The code is very similar previous example, but we have changed the
prototypes and functions to work with pointers.
§ The argument of readpart() function is a pointer to the inventory
structure.
§ While items variable declared in main() is inventory structure
type.
§ The function accesses the object pointed to by pPartPtr, and uses
the dot operator to access a member of that object.
STRUCT, TYPEDEF, ENUM & UNION
§ Since pPartPtr points to an object of type struct
inventory, we dereference the pointer to access the members
of the object using the following statements,
(*pPartPtr).nPartNo
(*pPartPtr).fBuyCost
(*pPartPtr).fSellingPrice

§ Similar changes have been made to printpart() function.


§ Note, the parentheses are necessary here because the .
operator has higher precedence than the indirection operator, *.
§ We must first dereference the pointer, and then select its
appropriate member.
§ Since, for efficiency, pointers to structures are often passed to
functions, and, within those functions, the members of the
structures are accessed, the operation of dereferencing a
structure pointer and a selecting a member is very common in
programs.
STRUCT, TYPEDEF, ENUM & UNION
§ As we have discussed previously, we can use
arrow (->) operator instead of indirection
operator (*) because,
pPartPrt->nPartNo is equivalent to (*pPartPtr).nPartNo

§ The left hand expressions are equivalent ways of


writing expressions on the right hand side.
§ Our code for readpart() could use the
following more readable alternative expressions,
pPartPtr->nPartNo
pPartPtr->fBuyCost
pPartPtr->fSellingPrice
STRUCT, TYPEDEF, ENUM & UNION
§ Structure, function and pointer example 2 (using ->
operator)
STRUCT, TYPEDEF, ENUM & UNION
STRUCT, TYPEDEF, ENUM & UNION
§ Step: Re-build and re-run the project.

§ The output should be the same.


STRUCT, TYPEDEF, ENUM & UNION
#import and #pragma once

§ There are two more ways of indicating that a header file


should be read only once.
§ Neither one is as portable as a wrapper #ifndef.
§ In Objective-C language, there is a variant of #include
called #import which includes a file, but does so at most
once.
§ If you use #import instead of #include, then you don't
need the conditionals inside the header file to prevent
multiple inclusion of the contents.
§ However, it is not in standard C or C++ and should
therefore not be used for program portability.
§ #import is not a well designed feature.
§ It requires the users of a header file to know that it should
only be included once.
STRUCT, TYPEDEF, ENUM & UNION
§ It is much better for the header file's implementor to write
the file so that users don't need to know this.
§ Using a wrapper #ifndef accomplishes this goal.
§ Another way to prevent a header file from being included
more than once is with the #pragma once directive.
§ If #pragma once is seen when scanning a header file,
that file will never be read again, no matter what.
§ #pragma once does not have the problems that #import
does, but it is not recognized by all preprocessors, so you
cannot rely on it in program portability.
§ More real implementation of the source code packaging
and organization can found at,
1. Reactos C and C++ source code (browse the left
menu).
2. Linux online source code.
STRUCT, TYPEDEF, ENUM & UNION
typedef
§ typedef declaration do not introduce new type but
introduces new name or creating synonym (or alias) for
existing type.
§ To construct shorter or more meaningful names for types
already defined by the language or for types that you have
declared.
§ A typedef declaration does not reserve storage.
§ The name space for a typedef name is the same as other
ordinary identifiers.
§ Therefore, a program can have a typedef name and a
local-scope identifier by the same name.
§ The exception to this rule is if the typedef name specifies a
variably modified type. In this case, it has block scope.
§ The syntax is,

typedef type-declaration the_synonym;


STRUCT, TYPEDEF, ENUM & UNION
§ You cannot use the typedef specifier inside a function definition.
§ When declaring a local-scope identifier by the same name as a
typedef, or when declaring a member of a structure or union in the
same scope or in an inner scope, the type specifier must be
specified.
§ For example,

typedef float TestType;

int main(void)
{ ... }

// function scope (local)


int MyFunct(int)
{
// same name with typedef, it is OK
int TestType;
}
STRUCT, TYPEDEF, ENUM & UNION
§ When declaring a local-scope identifier by the same name
as a typedef, or when declaring a member of a structure
or union in the same scope or in an inner scope, the type
specifier must be specified.
§ For example,
// both declarations are different
typedef float TestType;
const TestType r;
§ To reuse the TestType name for an identifier, a structure
member, or a union member, the type must be provided,
for example,
const int TestType;
STRUCT, TYPEDEF, ENUM & UNION
§ Typedef names share the name space with ordinary
identifiers.
§ Therefore, a program can have a typedef name and a
local-scope identifier by the same name.
// a typedef specifier
typedef char FlagType;

void main(void)
{ ... }

void myproc(int)
{
int FlagType;
}
STRUCT, TYPEDEF, ENUM & UNION
§ The following paragraphs illustrate other typedef
declaration examples,
// a char type using capital letter
typedef char CHAR;

// a pointer to a string (char *)


typedef CHAR * THESTR;
// then use it as function parameter
THESTR strchr(THESTR source, CHAR destination);

typedef unsigned int uint;


// equivalent to 'unsigned int ui';
uint ui;
STRUCT, TYPEDEF, ENUM & UNION
§ To use typedef to specify fundamental and derived types
in the same declaration, you can separate declarators with
comma. For example,
typedef char CHAR, *THESTR;

§ The following example provides the type Funct() for a


function returning no value and taking two int arguments,
typedef void Funct(int, int);

§ After the above typedef statement, the following is a


valid declaration,
Funct test;

§ And equivalent to the following declaration,


void test(int, int);
STRUCT, TYPEDEF, ENUM & UNION
§ Names for structure types are often defined with typedef to
create shorter and simpler type name.
§ For example, the following statements,
typedef struct Card MyCard;
typedef unsigned short USHORT;

§ Defines the new type name MyCard as a synonym for type


struct Card and USHORT as a synonym for type unsigned
short.
§ Programmers usually use typedef to define a structure (also
union, enum and class) type so a structure tag is not required.
§ For example, the following definition.
typedef struct{ No tag
char *face;
char *suit;
} MyCard;
STRUCT, TYPEDEF, ENUM & UNION
§ Creates the structure type MyCard without the
need for a separate typedef statement.
§ Then MyCard can be used to declare variables
of type struct Card and look more natural
as normal variable.
§ For example, the following declaration,
MyCard deck[50];
§ Declares an array of 50 MyCard
structures. typedef simply creates a new type
name which may be used as an alias for an
existing type name.
STRUCT, TYPEDEF, ENUM & UNION
§ Often, typedef is used to create synonyms for
the basic data types.
§ For example, a program requiring 4-byte integers
may use type int on one system and type long
on another system.
§ Programs designed for portability often uses
typedef to create an alias for 4-byte integers
such as, let say Integer.
§ The alias Integer can be changed once in the
program to make the program work on both
systems.
§ Microsoft uses this extensively in defining new
type name for Win32 and Windows programming.
STRUCT, TYPEDEF, ENUM & UNION
§ A basic use of typedef program example

§ Another typedef program example


STRUCT, TYPEDEF, ENUM & UNION
§ All the structure program examples in the previous structure section
can be simplified using typedef. For example,
// declare a structure with 3 members
struct inventory{
int nPartNo;
float fBuyCost;
float fSellingPrice;
};

§ Can be typedef-ed,

// declare a structure with 3 members


typedef struct inventory{
int nPartNo;
float fBuyCost;
float fSellingPrice;
}abcinventory;
STRUCT, TYPEDEF, ENUM & UNION

Then, the following declaration,

// variable of type struct inventory


struct inventory items;

Should become

// variable of type struct abcinventory


abcinventory items;
STRUCT, TYPEDEF, ENUM & UNION
enum - Enumeration Constants
§ enum is another user-defined type consisting of a set of named
constants called enumerators.
§ Using a keyword enum, it is a set of integer constants represented
by identifiers.
§ The syntax is shown below, ([is optional])
// for definition of enumerated type
enum [tag]
{
enum-list
}
[declarator];

§ And
// for declaration of variable of type tag
enum tag declarator;

§ These enumeration constants are, in effect, symbolic constants


whose values can be set automatically.
STRUCT, TYPEDEF, ENUM & UNION
§ The values in an enum start with 0, unless specified
otherwise, and are incremented by 1. For example, the
following enumeration,
enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

§ Creates a new data type, enum days, in which the


identifiers are set automatically to the integers 0 to 6.
§ To number the days 1 to 7, use the following
enumeration,
enum days {Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};

§ Or we can re-arrange the order,


enum days {Mon, Tue, Wed, Thu = 7, Fri, Sat, Sun};
STRUCT, TYPEDEF, ENUM & UNION
§ A simple enum program example

§ As said before, by default, the first enumerator has a value of 0,


and each successive enumerator is one larger than the value of
the previous one, unless you explicitly specify a value for a
particular enumerator.
§ Enumerators needn't have unique values within an enumeration.
§ The name of each enumerator is treated as a constant and must
be unique within the scope where the enum is defined.
STRUCT, TYPEDEF, ENUM & UNION
§ An enumerator can be promoted to an integer
value.
§ Converting an integer to an enumerator requires
an explicit cast, and the results are not defined if
the integer value is outside the range of the
defined enumeration.
§ Enumerated types are valuable when an object
can assume a known and reasonably limited set of
values.
§ Another enum program example.
STRUCT, TYPEDEF, ENUM & UNION
§ After the enum data type has been declared and
defined, in C++ it is legal to use the enum data type
without the keyword enum.
§ From the previous example, however, the following
statement is legal in C++,
// is legal in C++
Days WhatDay = tuesday;

§ Enumerators are considered defined immediately


after their initializers; therefore, they can be used to
initialize succeeding enumerators.
§ The following example defines an enumerated type
that ensures any two enumerators can be combined
with the OR operator.
STRUCT, TYPEDEF, ENUM & UNION

§ In this example, the preceding enumerator


initializes each succeeding enumerator.
STRUCT, TYPEDEF, ENUM & UNION
§ Enumerated types are integral types; any enumerator can
be converted to another integral type by integral promotion.
§ Consider the following enum example,

§ However, there is no implicit conversion from any integral


type to an enumerated type.
§ Therefore from the previous example, the following
statement is an error,
// erroneous attempt to set enDays to
// Saturday
enDays = 5;
STRUCT, TYPEDEF, ENUM & UNION
§ The assignment enDays = 5, where no implicit conversion
exists, must use casting to perform the conversion,
// explicit cast-style conversion to type Days
enDays = (Days)5;
// explicit function-style conversion to type Days
enDays = Days(4);

§ The preceding example shows conversions of values that


coincide with the enumerators.
§ There is no mechanism that protects you from converting a
value that does not coincide with one of the enumerators. For
example,
enDays = Days(30);

§ Some such conversions may work but there is no guarantee


the resultant value will be one of the enumerators.
STRUCT, TYPEDEF, ENUM & UNION
§ The following program example uses
enum and typedef.
STRUCT, TYPEDEF, ENUM & UNION
Union
§ A union is a user-defined data or class type
that, at any given time, contains only one object
from its list of members (although that object can
be an array or a class type).
union [tag] { member-list } [declarators];

§ Then, in program we can declare union type


variable as,
[union] tag declarators;

§ In C++ the union keyword is optional.


STRUCT, TYPEDEF, ENUM & UNION
§ The storage associated with a union variable is
the storage required for the largest member of
the union.
§ When a smaller member is stored, the union
variable can contain unused memory space.
§ All members are stored in the same memory
space and start at the same address.
§ Hence, the stored value is overwritten each time
a value is assigned to a different member.
§ Begin the declaration of a union with the union
keyword, and enclose the member list in curly
braces.
STRUCT, TYPEDEF, ENUM & UNION
§ Union with array and pointer example.

§ Another variation of the previous union


example.
STRUCT, TYPEDEF, ENUM & UNION
§ The members of the myuniontype union are, in
order of their declaration, a pointer to a char, a
char, and an array of float values.
§ The storage allocated for myuniontype is the
storage required for the 20-element array fNum,
since fNum is the longest member of the union.
§ If the tag (mycharfloat) associated with the
union is omitted, the union is said to be unnamed
or anonymous.
§ A union may only be initialized with a value of the
type of its first member; thus union myuniontype
described above can only be initialized with a
pointer to a string value.
STRUCT, TYPEDEF, ENUM & UNION
union vs struct Storage Allocation
§ Let check the union’s size and its biggest member.
§ In the following program examples, we are using stack memory instead of
heap.
§ Hence, no need 'manual' memory allocation using function such as
malloc() etc.
§ Union, array and pointers example: storage size

§ The size is the size of the biggest element which is an array of float (20 x 4
bytes = 80 bytes).
STRUCT, TYPEDEF, ENUM & UNION
§ Let change the union to structure.
§ Structure, array and pointers example: storage size

§ Well the size is 88 bytes but the biggest element is 80 bytes.


§ Why 88 bytes? The char pointer is 4 bytes on 32 bits system, char is 1 byte
and an array of 20 floats is 80 bytes which makes the total 85 bytes.
§ We lack another 3 bytes which used for 32-bits system memory alignment of
the char (4 - 1 = 3 bytes).
STRUCT, TYPEDEF, ENUM & UNION
Accessing union Member

§ If we put the some of the printf() at the end of source code, structure will
generate the expected output but not for union, because the last printf()
access will overwrite the previous stored data or at least the result is
unreliable.
§ Union, array and pointers program example: structure member access

§ The string pointed to by chaA pointer was displayed properly.


STRUCT, TYPEDEF, ENUM & UNION
§ Let change the same program to union.

§ The string pointed by chaA pointer is nowhere can be seen.


§ If a union of two types is declared and one value is stored, but the union
is accessed with the other type, the results are unreliable.
§ For example, a union of float and int is declared. A float value is
stored, but the program later accesses the value as an int.
§ In such a situation, the value would depend on the internal storage of
float values.
§ The integer value would not be reliable.
STRUCT, TYPEDEF, ENUM & UNION
§ Let try another example

§ Default access of members in a union is public.


§ A C union type can contain only data members.
§ In C, you must use the union keyword to declare a union
variable. In C++, the union keyword is unnecessary.
§ A variable of a union type can hold one value of any type
declared in the union. Use the member-selection operator
(.) to access a member of a union.
STRUCT, TYPEDEF, ENUM & UNION
Initializing union member
§ You can declare and initialize a union in the same statement by
assigning an expression enclosed in braces.
§ The expression is evaluated and assigned to the first field of the
union.
§ For example: union initialization program example.

§ The NumericType union is arranged in memory (conceptually) as


shown in the following figure.
§ The memory spaces of union members are overlaps.
STRUCT, TYPEDEF, ENUM & UNION
§ Another example to initialize a union.

§ Unions can contain most types in their member


lists, except for the following,
1. Class types that have constructors or
destructors.
2. Class types that have user-defined
assignment operators.
3. Static data members.
STRUCT, TYPEDEF, ENUM & UNION
Anonymous union

§ Anonymous unions are unions that are declared without a


class-name or declarator-list.
union { member-list }
§ Such union declarations do not declare types but they
declare objects.
§ The names declared in an anonymous union cannot
conflict with other names declared in the same scope.
§ In C, an anonymous union can have a tag; it cannot have
declarators.
§ Names declared in an anonymous union are used
directly, like non-member variables.
STRUCT, TYPEDEF, ENUM & UNION
1. In addition to the restrictions mentioned in 'Union can
contain most types…', anonymous unions are subject to
additional restrictions,
a) They must also be declared as static if declared in
file scope. If declared in local scope, they must be static
or automatic.
b) They can have only public members; private and
protected members in anonymous unions generate
errors (compared to C++ class).
c) They cannot have function members.
2. Simply omitting the class-name portion of the syntax does
not make a union an anonymous union.
3. For a union to qualify as an anonymous union, the
declaration must not declare an object.
STRUCT, TYPEDEF, ENUM & UNION
§ Let try a program example: anonymous union
STRUCT, TYPEDEF, ENUM & UNION
§ Anonymous union (and struct) is not in the C99 standard, but
they are in the C11 standard.
§ GCC and clang already support this.
§ The C11 standard seems have been removed from Microsoft, and
GCC has provided support for some MSFT extensions for some
time.
§ As in structure, typedef can be used to simplify the union
declaration.
// defines a union named myuniontype with
// members consist
// of char pointer, char and array of 20 floats
typedef union mycharfloat
{
char *chaA, chaB;
float fNum[20];
} myuniontype;

§ Later, in program we just write like the following,

myuniontype myUnionVar;
STRUCT, TYPEDEF, ENUM & UNION
§ Union are particularly useful in embedded programming or in situations
where direct access to the hardware/memory is needed depending on
the endianism and processor architecture.
§ For example, union can be used to breakdown hardware registers into
the component bits. So, you can access an 8-bit register bit-by-bit.
§ Unions are used when you want to model struct defined by hardware,
devices or network protocols, or when you are creating a large number
of objects and want to save space.
§ In most occasion of the program running, you really don't need them
90% of the time. (just an assumption!)
§ Most of the cases the union is wrapped in a struct and one member
of the struct tells which element in the union to access.
§ In effect, a union is a structure in which all members have offset zero
from the base.
§ The same operations are permitted on union as on struct:
assignment to or copying as a unit, taking the address, and accessing a
member.
File Handling
File
• Discrete storage unit for data in the form of a
stream of bytes.
• Durable: stored in non-vola7le memory.
• Star7ng end, sequence of bytes, and end of
stream (or end of file).
• Sequen7al access of data by a pointer
performing read / write / dele7on / inser7on.
• Meta-data (informa7on about the file) before
the stream of actual data.
Head Tail
Meta Data 40 65 87 90 24 67 89 90 0 0

File Pointer
File handling in C
• In C we use FILE * to represent a pointer to a file.
• fopen is used to open a file. It returns the special value
NULL to indicate that it couldn't open the file.

FILE *fptr;
char filename[]= "file2.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* DO SOMETHING */
}
Modes for opening files
• The second argument of fopen is the mode
in which we open the file. There are three
• "r" opens a file for reading
• "w" creates a file for wri7ng - and writes over
all previous contents (deletes the file so be
careful!)
• "a" opens a file for appending - wri7ng on the
end of the file
• “rb” read binary file (raw bytes)
• “wb” write binary file
The exit() func7on
• Some7mes error checking means we want
an "emergency exit" from a program. We
want it to stop dead.
• In main we can use "return" to stop.
• In func7ons we can use exit to do this.
• Exit is part of the stdlib.h library
exit(-1);
in a function is exactly the same as
return -1;
in the main routine
Usage of exit( )
FILE *fptr;
char filename[]= "file2.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
prinM (“ERROR IN FILE CREATION”);
/* Do something */
exit(-1);
}
Wri7ng to a file using fprinM( )
• fprinM( ) works just like prinM and sprinM
except that its first argument is a file pointer.
FILE *fptr;
fptr= fopen ("file.dat","w");
/* Check it's open */
fprintf (fptr,"Hello World!\n");
Reading Data Using fscanf( )
•We also read data from a file using fscanf( ).

FILE *fptr;
input.dat
fptr= fopen (“input.dat”,“r”);
/* Check it's open */ 20 30
if (fptr==NULL)
{
prinM(“Error in opening file \n”);
} x=20
y=30
fscanf(fptr,“%d%d”,&x,&y);
Reading lines from a file using
fgets( )
We can read a string using fgets ( ).
FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL) {
printf ("Read line %s\n",line);
}

fgets( ) takes 3 arguments, a string, a maximum


number of characters to read and a file pointer.
It returns NULL if there is an error (such as EOF).
Closing a file
• We can close a file simply using fclose( ) and
the file pointer.
FILE *fptr;
char filename[]= "myfile.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) { Opening
printf ("Cannot open file to write!\n");
exit(-1);
}
fprintf (fptr,"Hello World of filing!\n");
Access
fclose (fptr);
closing
Three special streams
• Three special file streams are defined in the
<stdio.h> header
• stdin reads input from the keyboard
• stdout send output to the screen
• stderr prints errors to an error device
(usually also the screen)
• What might this do?

fprintf (stdout,"Hello World!\n");


An example program
Give value of i
#include15<stdio.h>
main() Value of i=15
{ No error: But an example to show error message.
int i;

fprintf(stdout,"Give value of i \n");


fscanf(stdin,"%d",&i);
Display on
fprintf(stdout,"Value of i=%d \n",i);
The screen
fprintf(stderr,"No error: But an example to
show error message.\n");
}
Input File & Output File redirec7on
• One may redirect the input and output files to
other files (other than stdin and stdout).
• Usage: Suppose the executable file is a.out
$ ./a.out <in.dat >out.dat
No error: But an example to show error message.

Give value of i Display


15 Value of i=15 screen

in.dat out.dat
Reading and Wri7ng a character
• A character reading/wri7ng is equivalent to
reading/wri7ng a byte.
int getchar( );
int fgetc(FILE *fp);
int putchar(int c);
int fputc(int c, FILE *fp);
• Example:
char c;
c=getchar( );
putchar(c);
Example: use of getchar() and
putchar()
#include <stdio.h>
main()
{
int c;

printf("Type text and press return to see it again \n");


printf("For exiting press <CTRL D> \n");
while((c=getchar( ))!=EOF) putchar(c);
}

End of file
Command Line Arguments
• Command line arguments may be passed by
specifying them under main( ).
int main(int argc, char *argv[ ]);

Argument
Count Array of Strings
as command line
arguments including
the command itself.
Example: Reading command line arguments
#include <stdio.h>
#include <string.h>

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


{
FILE *ifp,*ofp;
int i,c;
char src_file[100],dst_file[100];

if(argc!=3){
printf("Usage: ./a.out <src_file> <dst_file> \n");
exit(0);
}
else{
strcpy(src_file,argv[1]);
strcpy(dst_file,argv[2]);
}
Example: Contd.
if((ifp=fopen(src_file,"r"))==NULL)
{
printf("File does not exist.\n"); ./a.out s.dat d.dat
exit(0);
}
if((ofp=fopen(dst_file,"w"))==NULL) argc=3
{
printf("File not created.\n");
exit(0); ./a.out
} argv s.dat
while((c=getc(ifp))!=EOF){
putc(c,ofp);
d.dat
}
fclose(ifp);
fclose(ofp);
}
Ge[ng numbers from strings
• Once we've got a string with a number in it
(either from a file or from the user typing)
we can use atoi or atof to convert it to
a number
• The func7ons are part of stdlib.h
char numberstring[]= "3.14";
int i;
double pi;
pi= atof (numberstring);
i= atoi ("12");
Both of these functions return 0 if they have a problem
Example: Averaging from Command
Line
#include <stdio.h>
#include <stdlib.h> $ ./a.out 45 239 123

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


{ Average=135.666667
float sum=0;
int i,num;

num=argc-1;
for(i=1;i<=num;i++)
sum+=atof(argv[i]);
printf("Average=%f \n",sum/(float) num);
}
List of C PracHce Problems Topic – Wise
1. Operators and Expressions
· Length and breadth of a rectangle are 5 and 7 respec7vely. Write a program to calculate the area and

perimeter of the rectangle.


1. Write a program to enter a 4-digit number from keyboard. Add 8 to the number and then divide it by 3.
Now, the modulus of that number is taken with 5, and then mul7ply the resultant value by 5.
Display the final result, and solve the ques7on using assignment operators (eg. +=, -=, *=).
· Swap 2 numbers and Print the swapped Numbers.

· The total number of students in a class are 45 out of which 25 are boys. If 80% of the total students secured

grade 'A' out of which 15 are boys, then write a program to calculate the total number of girls ge[ng a grade 'A'.
· Write a program to reverse a 3-digit number that is entered from keyboard. E.g.-

INPUT: 132 OUTPUT : 231

•Control Statements
· Write a program to enter the values of two variables 'a' and 'b' from keyboard and then check if both the

condi7ons 'a < 50' and 'a < b' are true.
· Write a C program to find whether a given year is a leap year or not

· Write a C program to find the eligibility of admission for a professional course based on the
following criteria: Eligibility Criteria : Marks in Maths >=65 and Marks in Phy >=55 and Marks in Chem>=50 and
Total in all three subject >=190 or Total in Maths and Physics >=140 ------------------------------------- Input the
marks obtained in Physics :65 Input the marks obtained in Chemistry :51 Input the marks obtained in
Mathema7cs :72 Total marks of Maths, Physics and Chemistry : 188 Total marks of Maths and Physics : 137
The candidate is not eligible. Expected-Output :
The candidate is not eligible for admission.
· Write a program in C to accept a grade and declare the equivalent descrip7on

Grade Description
E Excellent
V Very Good
G Good
A Average
F Fail

· Write a program in C to read any Month Number in an integer and display the number of
days for this month.

• Flow statements (Loops)


· Print pyramid pa‚ern with given value of n.

For n=6, Expected Output:

*
**
***
****
*****
******

· Create a simple Calculator for all basic operators using Switch.


· Print Fibonacci series up to an input value N.
· Given a number (num) we need to check whether it is a Neon Number ( i.e. a number where
the sum of digits of the square of the number is equal to the number ) and
return “true” or “false” accordingly.
· C program to count the frequency of digits in an integer
Input

Input rows: 5

Output
· Write a C program to convert Binary
1 to Octal number system.
11
· C program to print pascal triangle
121
1331
14641

• Arrays
· Write a C program to find maximum and
minimum element in an array.
· Write a C program to delete an element from an array
at specified posi7on.
· Write a C program to delete all duplicate elements
from an array.
· Write a C program to right rotate an array.
· Create 2 2-D arrays as matrix and write a C program to
perform Scalar matrix mul7plica7on.
· You are given an integer array score of size n,
where score[i] is the score of the ith athlete in a
compe77on. All the scores are guaranteed to be
unique.
Input: score = [5,4,3,2,1]

Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]

ExplanaHon: The placements are [1st, 2nd, 3rd, 4th, 5th].

5. Strings

· Write a C program to concatenate two strings.


· Write a C program to compare two strings.
5. Write a C program to convert lowercase string to uppercase.
· Write a C program to count total number of vowels and consonants in a string.
· Write a C program to find highest frequency character in a string.
5. Write a C program to remove all occurrence of a word in given string.

• FuncHons and Recursions


· Write a C programming to find out maximum and minimum of some values using func7on which will return an array.

Test Data Input 5 values


25,11,35, 65,20
Expected Output :

Number of values you want to input: Input 5 values Minimum value is: 11
Maximum value is: 65
· Calculate the factorial of a number using recursion

· Create different func7ons to calculate Square, square root, print prime numbers up 7ll number N.

· Write a func7on “perfect()” that determines if parameter number is a perfectnumber. Use this func7on in a program that

determines and prints all the perfect numbers between 1 and 1000. [An integer number is said to
be “perfect number” if its factors, including 1(but not the number itself), sum to the number. E.g., 6 is a perfect number
because 6=1+2+3].
· Write a func7on to calculate power of a number raised to other ( a ) using recursion.
b
7. Pointers
· Write a program to find out the greatest and the smallest among three numbers using pointers.

· Write a C program for dynamic memory alloca7on using malloc().


· Program to print size of different types of pointer variables.

· Program to demonstrate example of double pointer (pointer to pointer).

• Structure and Unions

· Write a program to store and print the roll no., name , age and marks of a student using structures.
· Enter the marks of 5 students in Chemistry, Mathema7cs and Physics (each out of 100) using a structure
named Marks having elements roll no., name, chem_marks, maths_marks and phy_marks and then
display the percentage of each student.
· Write a structure to store the name, account number and balance of customers (more than 10) and
store their informa7on. 1 - Write a func7on to print the names of all the customers having balance
less than $200. 2 - Write a func7on to add $100 in the balance of all the customers
having more than $1000 in their balance and then print the incremented value of their balance.
· Let us work on the menu of a library. Create a structure containing book informa7on like accession number,
name of author, book 7tle and flag to know whether book is issued or not.

Create a menu in which the following can be done. 1 - Display book informa7on
• - Add a new book

• - Display all the books in the library of a par7cular author 4 - Display the number of books of a par7cular

7tle
5 - Display the total number of books in the library 6 - Issue a book
(If we issue a book, then its number gets decreased by 1 and if we
add a book, its number gets increased by 1)
· Calculate party expenses using C program

· C program to find the size of the union


· 9. File Handling
· Write a C program to compare two files.
· Write a C program to copy contents from one file to another file.
· Write a C program to merge two files to third file.
· Write a C program to count characters, words and lines in a text file.
· Write a C program to print source code of same program.
· Write a C program to convert uppercase to lowercase character and vice versa in a text file.

• Miscellaneous
· Create a Rock-Paper scissor game in C

· C Program to check if two given strings are isomorphic to each other

Input: str1 = “egg”, str2 = “add”


Output: Yes
Explana-on:
‘e’ in str1 with ASCII value 101 is mapped to ‘a’ in str2 with ASCII value 97.
‘g’ in str1 with ASCII value 103 is mapped to ‘d’ in str2 with ASCII value 100.
· Draw a moving car using computer graphics programming in C

· Given the number of rows and columns, print the corresponding swastika pattern

using loops.
Input: row = 7, column = 7

11. Projects
EASY
· Cricket Score Display
Here, you will display a summary of a cricket match that has already been played. You can
include the names of the teams, venue, umpires, list of players with their role runs made by
ba‚ers of each team, wickets taken by bowlers of each team, final result, and man of the match
(You can use graphics)

MEDIUM
· TIC-TAC-TOE Game
Tic-tac-toe, also known as noughts and crosses or Xs and Os, is a two-person paper and pencil game
in which each player alternates marking squares in a three-by-three grid with an X or an O. The
winner is the player who successfully places three of their markers in a horizontal, ver7cal, or
diagonal row. You can implement this fun game using 2D arrays in the C programming
language. It is important to use arrays while crea7ng a Tic Tac Toe game in the C programming
language. The Xs and Os are stored in separate arrays and passed across various func7ons in
the code to maintain track of the game’s progress. You can play the game against the computer by
entering the code here and selec7ng either X or O. The source code for the project is given below.

HARD
· Bus Reserva7on System
This system is built on the concept of booking bus 7ckets in advance. The user can check
the bus schedule, book 7ckets, cancel reserva7ons, and check the bus status board using this
system. When purchasing 7ckets, the user must first enter the bus number, arer which the system
will display the en7re number of bus seats along with the passengers’ names, and the user must
then enter the number of 7ckets, seat number, and person’s name.
We will be using arrays, if-else logic, loop statements, and various func7ons like login(), cancel(), etc.
to implement the project.

You might also like