Basic Components in a
Computer
Central Processing
Unit
Control Unit
Arithmetic Logic
Unit
Input Unit Memory Output Unit
(Temporary)
Mouse, Monitor,
Keyboard, Printer,
Microphon Storage Speaker
e, etc. (Permanent)
s, etc.
Memory
Unit
1
Programming and
Software
• A computer needs to be programmed to do
tasks
• Programming is the process of writing
instructions in a language that can be
understood by the computer so that a desired
task can be performed by it
• Program: sequence of instructions to do a task,
computer processes the instructions
sequentially one after the other
• Software: programs for doing tasks on
computers
2
Three steps in writing
programs
Step 1: Write the program in a high-level language (in
your case, C) Step 2: Compile the program using a C
compiler
Step 3: Run the program (as the computer to execute
it)
3
Binary
Representation
The decimal number system we use is base-10
•10 digits, from 0 to 9, Positional weights 100, 101, 102,…from right to left
for integers
•Example: 723 = 3x100 + 2x101 + 7x102
Numbers are represented inside computers in the base-2 system (Binary
Numbers)
•Only two symbols/digits 0 and 1
•Positional weights of digits: 20, 21, 22,…from right to left for integers
•Example: 1101 in binary = (1 x 20) + (0 x 21) + (1 x 22) + (1 x 23) = 13 in
decimal
8
Binary
Dec Numbers
Binary
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9
Binary
Numbers
Dec Binary Binary to Decimal Conversion
0 0
1 1 101011 1x25 + 0x24 + 1x23 + 0x22 + 1x21 +
2 10 1x20 = 43
3 11 (101011)2 = (43)10
4 100 111001 1x25 + 1x24 + 1x23 + 0x22 + 0x21 +
5 101 1x20 = 57
6 110 (111001)2 = (57)10
7 111
10100 1x24 + 0x23 + 1x22 + 0x21 + 0x20 = 20
8 1000
(10100)2 = (20)10
Bits and
Bytes
• Bit – a single 1 or 0
• Byte – 8 consecutive bits
• 2 bytes = 16 bits
• 4 bytes = 32 bits
• Maximum integer that can represented
• in 1 byte = 255 (=11111111)
• In 4 bytes = 4294967295 (= 32 1’s)
• Number of integers that can be represented in 1 byte = 256 (the integers
0, 1, 2, 3,….255)
11
Fundamentals
of C
12
First C program – print on
screen
#include <stdio.h> int
Outp
main() ut
Hello, World!
{
printf ("Hello, World!
\n") ; return 0;
}
13
A Simple C
program
#include <stdio.h> int main()
When you run the
{ program
int x, y, sum, max;
scanf(“%d%d”, &x, &y);
sum = x + y;
if (x > y) max = x; Output after you type 15
and 20
else max = y; 15 20
printf (“Sum = %d\n”, sum); Sum = 35
printf (“Larger = %d\n”, max); Larger = 20
return 0;
}
14
Structure of a C
program
• A collection of functions (we will see what they are later)
• Exactly one special function named main( ) must be present. Program always
starts from there.
• Until we study functions in detail, this is the only function your programs will
have for now
• Each function has statements for variable declarations, assignment, condition
check, looping etc.
• Statements are executed one by one in order
15
#include
main
<stdio.h> int
function
{ main()
Declaration
int x, y, sum, max; statement
scanf(“%d%d”, &x, &y); Input
sum = x + y; statement
Assignment
if (x > y)
statements
max = x;
else Control
statement
max = y;
printf (“Sum = %d\n”, sum);
printf (“Larger = %d\n”, Output
max); return 0; statements
} Return
statement
16
Writing a C
program
• You will have to understand what different statements do to decide which you should
use in what order to solve your problem
• There is a fixed format (“syntax") for writing each statement and other things. Need to
remember the syntax.
• Do not question why you have to type exactly like this, you just have to or it is not a C
program!!
• Compiler will give error if your typed program does not match required C syntax
• There are other rules to follow
13
Things you will see in a C program (we will look at all
these one by one)
• Variables
• Constants
• Expressions (Arithmetic, Logical, Assignment)
• Statements (Declaration, Assignment, Control
(Conditional/Branching, Looping))
• Arrays
• Functions
• Structures
• Pointers
14
The C
Character Set
The C language alphabet
•Uppercase letters ‘A’ to
‘Z’
•Lowercase letters ‘a’ to ‘z’
•Digits ‘0’ to ‘9’
! # % ^ & * ( )
•Certain special
characters: - _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ?
whitespace characters (space,
tab, …)
A C program should not
contain anything else
19
Variabl
es
• Very important concept for programming
• An entity that has a value and is known to the program by a name
• Can store any temporary result while executing a program
• Can have only one value assigned to it at any given time during the
execution of the program
• The value of a variable can be changed during the execution of the program
Variables are stored in memory
Memory is a list of consecutive storage locations, each having a unique address A
variable is like a bin
•The contents of the bin is the value of the variable
•The variable name is used to refer to the value of the variable
•A variable is mapped to a location of the memory, called its address
20
Examp
le
#include <stdio.h> int main(
)
{
int x; int y;
x=1; y=3;
printf("x = %d, y= %d\n", x,
y); return 0;
}
21
Variables in
Memory
Instruction Memory
sequence
X=
10
(may contain
X ? whatever value at
X=
20 the beginning)
X=X
+1
X=
X*5
18
Variables in
Memory
Instruction Memory
sequence
X=
10
X 10
X=
20
X=X
+1
X=
X*5
19
Variables in
Memory
Instruction Memory
sequence
X=
10
X 20
X=
20
X=X
+1
X=
X*5
20
Variables in
Memory
Instruction Memory
sequence
X=
10
X 21
X=
20
X=X+
1
X=X*
5
21
Variables in
Memory
Instruction Memory
sequence
X=
10
X 105
X=
20
X=X+
1
X=X*
5
22
Variables in
Memory
Instruction Memory
sequence
X=
20
(may contain
X ? whatever value at
Y=
15 the beginning)
(may contain
X=Y+ Y ? whatever value at
3 the beginning)
Y=X/
6
23
Variables in
Memory
Instruction Memory
sequence
X=
20
X 20
Y=
15
X=Y+ Y ?
3
Y=X/
6
24
Variables in
Memory
Instruction Memory
sequence
X=
20
X 20
Y=
15
X=Y+ Y 15
3
Y=X/
6
25
Variables in
Memory
Instruction Memory
sequence
X=
20
X 18
Y=
15
X=Y+ Y 1
3 5
Y=X/
6
26
Variables in
Memory
Instruction Memory
sequence
X=
20
X 18
Y=
15
X=Y+ Y 3
3
Y=X/
6
27
Data
Types
• Each variable has a type, indicates what type of values the
variable can hold
• Four common data types in C (there are others)
• int - can store integers (usually 4 bytes)
• float - can store single-precision floating point numbers
(usually 4 bytes)
• double - can store double-precision floating point numbers
(usually 8 bytes)
• char - can store a character (1 byte)
32
Rules and good
practices
• First rule of variable use: Must declare a variable (specify its type and
name) before using it
anywhere in your program
• All variable declarations should ideally be at the beginning of the main( )
or other functions
• There are exceptions, we will see later
• A value can also be assigned to a variable at the time the variable is
declared. int speed = 30;
char flag = ‘y’;
33
Variable
Names
• Sequence of letters and digits
• First character must be a letter or ‘_’
• No special characters other than ‘_’
• No blank in between
• Names are case-sensitive (max and Max are two
different names)
• Examples of valid names:
i rank1 MAX max Minclass_rank
• Examples of invalid
names:
class,ra
a’s fact rec2sqroot nk
34
More Valid and Invalid
Identifiers
Valid identifiers Invalid
X identifiers
abc 10abc
simple_interest
my-name
a123 LIST
“hello”
stud_name
simple
Empl_1 Empl_2
interest
_avg_empl_salar
y (area)
%rate
C
Keyword
s
• Used by the C language, cannot be used as variable names
• Examples:
int, float, char, double, main, if else, for, while, do, struct, union, typedef, enum, void,
return, signed,
unsigned, case, break, sizeof,….
• There are others, see textbook…
Exampl
e1
#include
<stdio.h> int
main()
{ Three integer type variables
int x, y, sum; declared
scanf(“%d%d”,&x, Values
&y); sum = x + y; assigned
printf( “%d plus %d is %d\n”, x,
y, sum );
} return 0;
37
Example
2
#include
<stdio.h> int
main()
{ /* Two floating point variables declared */
float x, y; /* Here integer variable d2 is initialized to 10, can be
int d1, d2 = 10; changed later */
scanf(“%f%f%d”,&x, &y, &d1);
printf( “%f plus %f is %f\n”, x, y, x + y);
printf( “%d minus %d is %d\n”, d1, d2,
d1 – d2);
return 0;
}
38
Read-only
Variables
• Variables whose values can be initialized during declaration, but cannot be changed
after that
• Declared by putting the const keyword in front of the declaration
• Storage allocated just like any variable
• Used for variables whose values need not be changed
• Prevents accidental change of the value
Correct Incorrect: Limit changed int main() {
int main( ) {
const int LIMIT = 10; int n; const int Limit = 10; int n;
scanf(“%d”, &n); scanf(“%d”, &n);
if (n > LIMIT) printf(“Out of Limit = Limit + n;
limit”); printf(“New limit is %d”, Limit);
return 0; return 0;
} }
39
Consta
nts
• Integer constants
• Consists of a sequence of digits, with possibly a plus or a minus sign
before it
• Embedded spaces, commas and non-digit characters are not
permitted between digits
• Floating point constants
• Two different notations:
• Decimal notation:0.123e-12,
• 3.45e23, 25.0, 0.0034, .84,e -2.234
means “10 to the
• Exponential (scientific) notation
123e2 power of”
40
Cont
d.
• Character constants
• Contains a single character enclosed within a pair of single
quote marks.
• Examples :: ‘2’, ‘+’, ‘Z’
• Some special backslash characters
• ‘\n’ new line
• ‘\t’ horizontal tab
• ‘\’’ single quote
• ‘\”’ double quote
• ‘\\’ backslash
• ‘\0’ null
41
Typical Size of Data
Types
char – 1 byte int – 4 bytes float – 4 bytes
double – 8 bytes
•“Typical”, because some of them vary depending on machine/OS type
•Therefore never use the values (1, 4, 8) directly, use the sizeof( )
operator given
• sizeof(char) will give 1, sizeof(int) will give 4 and so on … as per
your PC/Laptop
42
Input: scanf
function
• Performs input from keyboard
• It requires a format string and a list of variables into which the value received from the
keyboard will be stored
• format string = individual groups of characters (usually ‘%’ sign, followed by a conversion
character), with one
character group for each variable in the list
int a, b; float c;
Variable list (note the & Commonly used conversion
before each variable
characters
name)
c for char type variable d for
scanf(“%d%d%f”, &a,
&b, &c); int type variable
Format string
f for float type variable
lf for double type variable
43
Exampl
es
scanf ("%d", &size) ;
•Reads one integer from keyboard into an int type variable named size
scanf ("%c", &nextchar) ;
• Reads one character from keyboard into a char type variable named nextchar
scanf ("%f", &length) ;
•Reads one floating point (real) number from keyboard into a float type variable named
length
scanf (“%d%d”, &a, &b);
• Reads two integers from keyboard, the first one in an int type variable named a and
the second one in an int type variable named b
44
Importa
nt
• scanf( ) will wait for you to type the input from the keyboard
• You must type the same number of inputs as the number of %’s in the format string
• Example: if you have scanf(“%d%d”,…), then you must type two integers (in same
line or different lines),
otherwise scanf( ) will just wait and the next statement will not be executed
45
Reading a single
character
• A single character can be read using • What happens here?
scanf with %c char a, b;
printf(“Enter the first character:\n”);
• It can also be read using the getchar() a = getchar( );
function printf(“Enter the second character:\n”);
b = getchar( );
char c;
c = getchar();
• You may encounter a situation where
the computer does not wait for reading
• Program waits at the getchar() line until a the second character. Why?
character is typed, and then reads it and
stores it in c
46
Output: printf
function
• Performs output to the standard output device (typically defined to be the screen)
• It requires a format string in which we can specify:
• The text to be printed out
• Specifications on how to print the values printf ("The number is %d\n", num);
• The format specification %d causes the value listed after the format string to be
embedded in the output as a decimal number in place of %d
• Output will appear as: The number is 125
47
General syntax of
printf( )
printf (format string, arg1, arg2, …, argn);
•format string refers to a string containing formatting information and data types of the
arguments to be output
•the arguments arg1, arg2, … represent list of variables/expressions whose values are to be
printed
•The conversion characters are the same as in scanf
•Examples:
printf (“Average of %d and %d is %f”, a, b, avg); printf (“Hello \nGood \nMorning \n”);
printf(“%3d %3d %5d”, a, b, a*b+2); printf(“%7.2f %5.1f”, x, y);
•Many more options are available for both printf and scanf – read from the book
48
More Examples
(Explain the outputs to test if you understood
format strings etc.)
49
More
#include <stdio.h> int
print Output
Hello, World! Hello World!
main()
{
printf ("Hello, World! ") ;
printf ("Hello \n World!
\n") ; return 0;
}
46
Some more Output
#include <stdio.h> int
print Hello, World! Hello
World!
main()
Hell
o World!
{
printf ("Hello, World! \n") ;
printf ("Hello \n World!
\n") ; printf ("Hell\no \t
World! \n") ; return 0;
}
47
Output
Some more Enter values for f1 and f2:
#include <stdio.h> int main()
{
print 23.5 14.326
Enter values for x1 and x2:
float f1, f2; int x1, x2;
54 7
printf(“Enter values for f1 and f2: \n”); f1 = 23.500000, f2 = 14.33
scanf(“%f%f”, &f1, &f2); printf(“Enter x1 = 54, x2 = 7
values for x1 and x2: \n”);
Can you explain why
scanf(“%d%d”, &x1, &x2); printf(“f1 =
14.326 got printed as
%f, f2 = %5.2f\n”, f1, f2); 14.33?
printf(“x1 = %d, x2 = %10d\n”, x1, x2);
return 0;
}
48
Some more Output
#include <stdio.h> int
print ab ab
main()
{
char c1, c2;
scanf(“%c%c”, &c1, &c2);
printf(“%c%c”, c1, c2);
return 0;
}
49
What about Output
#include <stdio.h> int
this? ab a
main()
Can you explain why only
{ ‘a’ was printed this time,
even though it is the same
char c1, c2; program as in the last
slide? Note the difference
scanf(“%c%c”, &c1, &c2); from the last slide carefully.
Also note that two
printf(“%c%c”, c1, c2); characters were read this
return 0; time also, or scanf would
have waited
}
50
Practice
Problems
Write C programs to
1.Read two integers and two floating point numbers, each in a separate scanf() statement (so 4
scanf’s) and print them with separate printf statements (4 printf’s) with some nice message
2.Repeat 1, but now read all of them in a single scanf statement and print them in a single printf
statement
3.Repeat 1 and 2 with other data types like double and char
4.Repeat 1 and 2, but now print all real numbers with only 3 digits after the decimal point
5.Read 4 integers in a single scanf statement, and print them (using a single printf statement) in
separate lines such that the last digit of each integer is exactly 10 spaces away from the beginning
of the line it is printed in (the 9 spaces before will be occupied by blanks or other digits of the
integer). Remember that different integers can have different number of digits
6.Repeat 5, but now the first integer of each integer should be exactly 8 spaces away from the
beginning of the line it is printed in.
55