C Programming Lecture Notes Final
C Programming Lecture Notes Final
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.
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
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 }
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
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
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
char acharacter;
int i, j = 18, k = -20;
printf("Initially, given j = 18 and
k = -20\n");
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
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;
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 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) */
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.
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:
"This is a string, lateral string"
L"This is a wide string"
"123abc"
"a4"
L"1234*abc@"
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
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
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]...);
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
%#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
+ 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:
%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
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;
%hd: 3
%ld: 3
%ls: This is a wide
string
%Lg: 3.14159
STANDARD I/O
Type character
1. Example 0
2. Example 1
3. Example 2
STANDARD I/O
scanf() family
Function Description
Same as scanf() except they use the locale
_scanf_l() parameter passed in instead of the current thread
locale.
▪ 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.
▪ 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
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
#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?
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
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
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.
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.
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
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:
, 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:
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:
▪ For example:
x && y++
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
• Relational operators are used to test the relationship between two variables or constant
#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);
• For example,
The sizeof operator
• sizeof is a unary compile-time operator
@ The functions gets() and puts() deals with string input and output respectively
at a time
@ In a scanf() strings with spaces cannot be accessed until ENTER key is pressed.
if (condition) if (condition)
statement; { statements;}
next_statement; next_statement;
1. (condition) is evaluated.
2. If TRUE (non-zero) the statement is executed.
▪ 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.
For example:
if(myCode == '1')
rate = 7.20;
else
rate = 12.50;
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
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.
Start
prinM("");
scanf("”);
intNum == 3? TRUE
prinM("");
prinM("");
FALSE
prinM("");
Stop
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.
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--)
"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…"
for( ; ; )
printf("This is an infinite loop\n");
▪ or
for( ; 1 ; )
printf("This is an infinite loop\n");
● 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;
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
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
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
#include <stdio.h>
Callee
#include <stdio.h>
// prototype
void DisplayInteger(int); Caller
void main(void)
{
int nNum = 30;
Callee
DisplayInteger(nNum);
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++).
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:
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
§ 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,
§ For example, the array chVowel in the previous example could have been
written more compactly as follows,
§ For examples,
int xInteger[3][4];
float matrixNum[20][25];
array_name[x][y];
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.
int NumStudents;
int midterm[MaxStudents];
int final[MaxStudents];
double score[MaxStudents];
midterm
final
Parallel Arrays score
}
}
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.
§ 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
// 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,
Function
example:
parameter and
argument
C FUNCTIONS
For the first function call:
Returning a Value
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));
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:
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?
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);
}
§ 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;
#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
#endif
//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
#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:
◆ 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,
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:
◆ 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,
int * pPointerToAge;
pPointerToAge = &iAge;
pPointerToAge++;
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
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
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,
◆ For pointer that point to a string you may just point to an empty string
for a dummy such as,
char chName[10];
&chName[0]
▪ So, you can see the equivalence of array subscript notation and
array pointer notation.
POINTERS
Arrays of Pointers and Function
int *iArrayPtr[20];
iArrayPtr[0]
viewArrayFunc(iArrayPtr);
POINTERS
Pointers to Pointers
int **iPointerOne;
char ** pToCharPointer;
◆ 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,
◆ 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.
* - 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
§ 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
};
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
§ 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
§ 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
int main(void)
{ ... }
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;
§ Can be typedef-ed,
Should become
§ And
// for declaration of variable of type tag
enum tag declarator;
§ 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
§ 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
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);
}
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;
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>
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
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
· 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.-
•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.
*
**
***
****
*****
******
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]
5. Strings
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 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
• Miscellaneous
· Create a Rock-Paper scissor game 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.