Basics of C
Computing Lab
https://www.isical.ac.in/~dfslab
Indian Statistical Institute
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 1 / 30
Books
The C Programming Language — Kernighan and Ritchie
Programming with C — Byron Gottfried (Schaums’ Outline series)
The Practice of Programming — Kernighan and Pike
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 2 / 30
What does a program look like?
#include <stdio.h>
#include <string.h> Preamble
int main(int ac, char **av) { main function
char s[256];
int i, j;
...
Variable declarations
}
Statements
Terminology
Memory = space for calculations, rough work, etc.
Variables = names given to memory locations for convenience
Instructions / statements = each step in the procedure
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 3 / 30
Example program: blood groups
Algorithm
1. Let a, b, ab, o represent the number of students with blood group A, B,
AB and O.
2. Initially, set a, b, ab, o to zero.
3. Consider each student in turn.
4. Let the current student be t. Find out t’s blood group.
5. Add 1 to the corresponding count (a, b, ab or o).
6. Report the numbers (a, b, ab and o) when done.
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 4 / 30
Example 1: blood groups (contd.)
1. Let a, b, ab, o represent the number of students with blood group A, B,
AB and O.
2. Initially, set a, b, ab, o to zero.
3. Consider each student in turn.
4. Let the current student be t. Find out t’s blood group.
5. Add 1 to the corresponding count (a, b, ab or o).
6. Report the numbers (a, b, ab and o) when done.
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 5 / 30
Example 1: blood groups (contd.)
#include <stdio.h>
int main(void)
{
/* declarations */
int c;
unsigned int a, b, ab, o;
unsigned int n, i;
a = 0; b = 0; ab = 0; o = 0;
printf("Enter the number of students: ");
scanf("%d", &n); getchar();
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 6 / 30
Example 1: blood groups (contd.)
for (i = 1; i <= n; i++) {
printf("Enter the blood group of mtc15%02d: ", i);
c = getchar(); getchar();
if (c == 'A')
a = a + 1;
else if (c == 'B')
b = b + 1;
else if (c == 'a')
ab = ab + 1;
else if (c == 'O')
o = o + 1;
else
printf("Invalid blood group %c, skipping\n", c);
}
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 7 / 30
Example 1: blood groups (contd.)
printf("Number of students with blood group A: %d\n", a);
printf("Number of students with blood group B: %d\n", b);
printf("Number of students with blood group AB: %d\n", ab);
printf("Number of students with blood group O: %d\n", o);
return 0;
}
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 8 / 30
More examples (from the Screening Test) I
1. Consider a reservoir, fitted with a set of taps and drains. Write a
program that takes as input details about the taps and drains attached
to the reservoir, and prints the correct output from among the
following options.
2. Consider a point that starts from the origin, and moves East, West,
North or South for M steps. Write a program that takes the directions
of the M steps, and computes the final distance of the point from the
origin. (Assume that in each step, the point travels unit distance.)
Input format: A sequence of letters from the set {E, W, N, S}
denoting the direction of movement of the point at each step. The
length of the sequence will NOT be given to you in advance. The first
character not belonging to the set will mark the end of the input.
Output format: Your program should print the distance from the final
position of the point to the origin, as a floating point number.
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 9 / 30
More examples (from the Screening Test) II
3. A sequence {s1 , s2 , . . . , sm } of m > 1 strings is said to satisfy
property P if
all the strings s1 , s2 , . . . , sm are of the same length; and
for any i (1 ≤ i ≤ m − 1), the strings si and si+1 differ in at most two
positions.
Write a program that takes a sequence of strings as input, and
determines whether the strings satisfy property P or not.
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 10 / 30
Agenda
Variables, built-in types and operators
Conditional statements (if): executing statements based on whether
some condition holds or does not hold
Loops (for, while, do): executing statements repeatedly
Input and output
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 11 / 30
Memory, variables
Unit of storage = 1 byte (8 bits)
Storage units are consecutively numbered
Number assigned to storage = location / address
Variable ≡ name assigned to a storage location
Variables must be defined and initialised before use
Examples:
LATER : difference
char c;
between definition
int count_a, count_b;
vs. declaration
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 12 / 30
Variable names
REQUIRED
must start with a letter or underscore (_)
can contain only letters, underscores, digits
cannot match reserved words (main, for, while, . . . )
case-sensitive
RECOMMENDED
use “meaningful” names (i.e., not just a, a1, a2, b, c, aaaa, . . . )
use under_scores or CamelCase for long names
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 13 / 30
Types
ALL data stored in memory as a sequence of 0s and 1s
Variable’s type determines how a sequence of 0s and 1s is interpreted
Example:
byte
0 1 0 0 0 0 0 1
Integer value: 65
Character representation: ’A’
For arithmetic operations: interpreted as integer
x = x + 65 and x = x + 'A' mean the same thing
x = x - 48 and x = x - '0' mean the same thing
For printing:
as integer (printf("%d\n", x)): 65 is printed
as character (printf("%c\n", x) or putchar(x)): A is printed
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 14 / 30
Built-in types
Integer data types
Type Size∗∗ Minimum value Maximum value
char 8 -2 7
27 − 1
short int 16 -2 15
215 − 1
int 32 -231 231 − 1
long int 32 -231 231 − 1
long long int 64 -2 63
263 − 1
unsigned char 8 0 28 − 1
unsigned short int 16 0 216 − 1
unsigned int 32 0 232 − 1
unsigned long int 32 0 232 − 1
unsigned long long int 64 0 264 − 1
∗∗
in bits (typical)
Use sizeof if you need to know the actual size, e.g., sizeof(a)
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 15 / 30
Signed and unsigned
Unsigned types: if a variable of unsigned type occupies k bits, its
value can be between 0 and 2k − 1.
Signed types:
Bit sequences stored are the same as for unsigned types
(i.e., B = bk−1 bk−2 . . . b1 b0 ).
BUT they are interpreted differently.
if bk−1 = 0, B is interpreted as for unsigned types;
if bk−1 = 1, B is interpreted as a negative number in two’s complement
representation.
Range of values: −2k−1 to +(2k−1 − 1)
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 16 / 30
Two’s complement representation
x is a variable of integer type, stored in k bits.
If 0 ≤ x ≤ 2k−1 − 1, x is represented as usual in binary.
If x < 0, it is represented in (k -bit) two’s complement form by the
number 2k − |x| (in binary).
Examples:
char x = -1; x is represented by 28 − 1 = 255 = 1 1 1 1 1 1 1 1 .
char x = -128; x is represented by 28 − 27 = 27 = 1 0 0 0 0 0 0 0 .
Thumbrule to compute the k -bit two’s complement representation of
x < 0:
1. Let B denote the k bit representation of |x|.
2. Flip each bit of B to get B ′ .
3. Add 1 to B ′ . This is called the one’s complement of B .
(Why does this work?)
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 17 / 30
In-built types
“Real” (floating point) numbers
Type Size∗∗
float 32 At times behaviour may be
counter-intuitive
double 64
(more about this later).
long double 128
Examples:
Decimal notation Exponential / scientific notation
1.23456 3.45e67
1. +3.45e67
e means ‘10 to the
.1 -3.45e-67 power’
-0.12345 .00345e-32
+.4560 1e-15
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 18 / 30
Operators
Arithmetic operators: + - * / %
Increment decrement operator: ++ –
Relational operators: < <= == != >= >
Boolean operators: && || !
See
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
for a complete list, along with precedence and associativity.
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 19 / 30
Boolean values and expressions
Any non-zero value is TRUE; zero is FALSE.
Examples:
0 False 0e10 False
1 True ’A’ True
6 - 2 * 3 False ’\0’ False
(6 - 2) * 3 True x = 0 False
0.0075 True x = 1 True
Lazy evaluation: Boolean expressions are evaluated from left to
right; evaluation stops as soon as the truth value of the expression is
determined.
Examples:
When i == N, A[i] (i.e., A[N]) is not checked.
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 20 / 30
Strings
Recall: char ≡ 1 byte ≡ single character OR small integer
String ≡ sequence of single characters in successive locations
Must be terminated by null character ≡ 0 OR ’\0’
Exercise:
difference between 2, ’2’ and "2"
difference between a, ’a’ and "a"
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 21 / 30
Conditionals: if, if-else
if (condition) { if (condition) { if (condition) {
statements statements statements
} } }
else { else if (condition) {
statements statements
} }
...
else {
No braces { } required for single statement, statements
but remember the semi-colon; }
Each else is paired with the closest preceding else-less if
if (condition1)
if (condition2) {
...
}
else { ... }
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 22 / 30
Conditionals: switch
switch (E) {
case value1 :
statement;
break;
case val2 :
statement;
break;
...
case valn :
statement;
break;
default:
statement;
}
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 23 / 30
Loops
while (condition) {
statement;
}
do {
statement;
} while (condition);
for ( initialisation ; condition ; update operation ) {
statement;
}
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 24 / 30
Loops
break: immediately jump to the next statement after the loop.
continue: for for loops, do the update operation; continue with the
next iteration of the loop.
i = 0;
while (i < 100) {
for (i=1; i<=100; ++i) { printf("%4d",i);
printf("%4d",i); if (i%10 != 0)
if (i%10 != 0) continue;
continue; printf("\n");
printf("\n"); i++;
} }
i is incremented after continue. i is NOT incremented after
continue.
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 25 / 30
Casting / type conversion
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 26 / 30
Some useful library functions
Mathematical functions: #include <math.h>
Character types: #include <ctype.h>
String functions: #include <string.h>
Miscellaneous functions: #include <stdlib.h>
Look up the man pages!
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 27 / 30
Practice problems – I
1. Write a program to determine the roots of a quadratic equation
ax2 + bx + c = 0. Your program should ask for the values of a, b and
c, and print the roots (real or complex).
2. Read a sequence of positive integers a0 , a1 , a2 , . . . (the length of the
∑
4
sequence will not be known a priori) and determine max ai+j .
i
j=0
Note that you do not need to store the complete sequence in order to
compute the required quantity.
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 28 / 30
Supplementary reading
1. Review lectures 1–4 from
https://cse.iitkgp.ac.in/~pallab/course/2022/spring%
202022/pds%20theory%202022/index.html
2. Review the list of reserved words in C (Kernighan & Ritchie, Appendix
A.2.4).
3. Review the list of escape sequences in C (’\n’, ’\\’, . . . )
(Kernighan & Ritchie, Section 2.3).
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 29 / 30
Acknowledgements
http://cse.iitkgp.ac.in/~pds/notes/
(please see the above page for many more practice problems)
Computing Labhttps://www.isical.ac.in/~dfslab (ISI) Basics of C 30 / 30