Sei sulla pagina 1di 48

Introduction: Computers

and Programming

Akanksha Bharadwaj
Lecturer
BITS Pilani
Computer Hardware
Despite significant variations in cost, size, and capabilities, modern
computers resemble one another in many basic ways. Essentially, most
consist of the following components:
o Main memory
o Secondary memory, which includes storage devices such as hard disks,
CDs,DVDs, and flash drives
o Central processing unit
o Input devices, such as keyboards, mouse, touch pads, scanners, joysticks
o Output devices, such as monitors, printers, and speakers
Computer Software
The collection of computer programs that control the interaction of the
user and the computer hardware is called the operating system (OS).
Here is a list of some of the operating systems many responsibilities:
o Communicating with the computer user: receiving commands and
carrying them out or rejecting them with an error message.
o Managing allocation of memory, of processor time, and of other
resources for various tasks.
o Collecting input from the keyboard, mouse, and other input devices, and
providing this data to the currently running program.
o Conveying program output to the screen, printer, or other output
device.
o Accessing data from secondary storage.
o Writing data to secondary storage.
Computer Languages
Machine Language: is a collection of binary numbers.
Assembly Language: a language in which computer operations
are represented by mnemonic codes rather than binary numbers
and variables can be given names rather than binary memory
addresses.
High-level Languages: combine algebraic expressions and
symbols taken from English.
Software Development Method
Six basic steps:
o Specify problem requirements
o Analyze the problem
o Design an algorithm to solve the problem
o Implement the algorithm
o Test and verify the completed program
o Maintain and update the program
Example problem: Compute
the volume of a cone
Data Requirements
o Problem input:
radius (of the base), height (of the cone)
o Problem output:
volume (of the cone)
o Relevant formula:
volume = 1 / 3 * pi * radius2 * height
Design
o Algorithm
o Get the radius and height for the cone
o Compute the volume of the cone
o volume = 1 / 3 * pi * radius2 * height
o Display the resultant volume of the cone
Example problem: Compute
the volume of a cone Contd.
Implementation (in C)
#include <stdio.h> /* Needed for printf (), scanf () */
#define PI 3.14159 /* Constant macro */
int main (void)
{ int height = 0, radius = 0;
double volume = 0.0;
printf ("Enter height of cone as integer: "); /* Displays prompt message */
scanf ("%d", &height); /* Gets the value from the user/keyboard */
printf ("Enter radius of base of cone as integer: ");
scanf ("%d", &radius);
/* Compute the volume of the given cone */
volume = ((double) 1 / 3) * PI * radius * radius * height;
/* Display the resultant volume of the given cone */
printf ("Volume of cone with radius %d and height %d is %lf.\n", radius, height,
volume);
return 0;
}
Example problem: Compute
the volume of a cone Contd.
Testing
o We would execute the program, trying several different input
data values and observing the results
o Debugging is NOT testing! Its a result of testing!
o Each test is defined by a test case
o A test case provides actual inputs, system state or
configuration information, and expected results
o Should always test boundaries of inputs and conditions
Maintenance
o Most software requires continual improvements, adaptations,
and corrections; software patches are a result of maintenance
Review Questions
1. List at least three kinds of information stored in a computer.
2. List two functions of the CPU.
3. List two input devices, two output devices, and two secondary storage
devices.
4. Describe three categories of programming languages.
5. What is a syntax error?
6. What processes are needed to transform a C program to a machine
language program that is ready for execution?
7. Explain the relationship between memory cells, bytes, and bits.
8. Name three high-level languages and describe their original usage.
9. What are the differences between RAM and ROM?
10. What is the World Wide Web?
11. How do you install new software on a computer?
12. What are two high-speed Internet connection options available to home
computer users?
Number systems and
Representations
Decimal Systems: In the decimal number system, there are ten
possible values that can appear in each digit position, and so there
are ten numerals required to represent the quantity in each digit
position.The decimal numerals are the familiar zero through nine
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). When we write decimal (base 10) numbers,
we use a positional notation system. Each digit is multiplied by an
appropriate power of 10 depending on its position in the number:
Example: 843
Binary Systems: In the binary number system, there are only two
possible values that can appear in each digit position rather than
the ten that can appear in a decimal number. Only the numerals 0
and 1 are used in binary numbers.
Example: 101101, 11, 10110
Binary to Decimal Conversion
To convert a binary number to decimal, sum together the weights.
Each weight is calculated by multiplying the bit by 2^ i , where i is
the index relative to the LSB.

What is 10011 in decimal?


1 0 0 1 1
2^4 2^3 2^2 2^1 2^0
Weight = 1*2^0 + 1*2^1 + 0*2^2 + 0*2^3 + 1*2^4
= 1*1 + 1*2 + 0*4 + 0*8 + 1*16
= 1+2+16 = 19 (base 10, decimal)
Decimal to Binary Conversion
To convert a decimal number to its equivalent binary number
representation, the easiest method is to use repeated division by 2.
Each time, save the remainder. The first remainder is the least
significant bit. The last remainder is the most significant bit.

What is 19 in binary?
19 / 2 = 9 remainder 1 LSB
9 / 2 = 4 remainder 1
4 / 2 = 2 remainder 0
2 / 2 = 1 remainder 0
1 / 2 = 0 remainder 1 MSB
Our final number is 10011.
Number systems and
Representations Contd.
Octal System: Octal numbers uses digits from 0..7
Example: 278 = 281+780 = 16+7 = 23
308 = 381+080 = 24
43078 = 483+382+081+780= 2247
Hexadecimal System: The hexadecimal system is base 16, there are
sixteen numerals required. The following are the hexadecimal numerals: 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Example: 3FA, A03F
Convert the binary number 0110101110001100 to hexadecimal
Divide into groups of 4 digits 0110 1011 1000 1100
Convert each group to hex digit 6 B 8 C
Convert the hex number 374F into binary
3 7 4 F
Convert the hex digits to binary 0011 0111 0100 1111
0011011101001111
Binary Number Representation
Unsigned Binary Number: When a fixed precision binary
number is used to hold only positive values, it is said to be
unsigned. In this case, the range of positive values that can be
represented is 0 -- 2n -1, where n is the number of bits used.
Signed Binary Number: In this case, part of the total range of
values is used to represent positive values, and the rest of the
range is used to represent negative values. There are a few ways to
represent negative binary numbers.
Ones complement
Two's complement
Eg: 3510 = 0010 00112
invert -> 1101 11002
add 1 -> 1101 11012
Elements of C Language
C Language
Developed in 1972 by Dennis Ritchie (b. 1941 2011) at AT&T Bell
Labs
Considered an imperative procedural programming language versus
an object-oriented language (like Java, C++, C#)
A very popular language from which many other languages are
derived
Has evolved into a general-purpose programming language
Has a reputation for being on the low end of the "high-level"
programming language spectrum
C Language Elements
Implementation (in C)
#include <stdio.h> /* Needed for printf (), scanf () */
#define PI 3.14159 /* Constant */
Comment
int main (void)
{ int height = 0, radius = 0; Preprocessor Directive
double volume = 0.0;
Variable Declaration
Reserved
Word printf ("Enter height of cone as integer: "); /* Displays prompt message */
scanf ("%d", &height); /* Gets the value from the user/keyboard */
printf ("Enter radius of base of cone as integer: "); Standard Identifier /
Library Function
scanf ("%d", &radius);
/* Compute the volume of the given cone */ Special Symbol /
volume = ((double) 1 / 3) * PI * radius * radius * height ; Operator
/* Display the resultant volume of the given cone */
printf ("Volume of cone with radius %d and height %d is %lf.\n", radius, height, volume);
return 0;
} Punctuation
C Language Elements Contd.
Preprocessor Directives
Begin with "#
Do NOT end with a semicolon ;
Tell the preprocessor to modify the program before
compilation
A preprocessor is a system program that modifies a C
program before compilation
ANSI (American National Standards Institute) C defines
several standard libraries
To use a library, you must include its header file in your code
using #include
A library is a collection of functions and symbols needed to
perform specific tasks or operations
#define can be used to instruct preprocess to replace each
occurrence of a textual constants (e.g., PI) with a value (e.g.,
3.14159)
Convention: constants are in all caps
C Language Elements Contd.
Function main
All C programs must define a main function
It is the place where program execution begins
Contains a series of declarations and executable statements
separated by punctuation to help compiler translate the
statements
Drives the rest of the program
Reserved words
Always in lowercase
Have special meaning (e.g., int, double)
Show up in blue within MS Visual Studio
C Language Elements Contd.
Standard Identifiers
Have special meaning in C
Represent names of operations (i.e. printf and scanf)
Can be redefined, but not recommended
If redefined, cant be used for original purpose
User-Defined Identifiers
Name memory cells used for computations ("variables")
Name our own custom algorithms (functions)
Must consist only of letters, numbers, and underscores
Must not begin with digits
Must not conflict with reserved words
Should not redefine standard C library identifiers
C Language Elements Contd.
Notes
C is case sensitive (pay attention to upper and lower case)
Choose identifier names wisely
They should be meaningful, indicating the role of the
variables they are naming
E.g., average, not a
Make them descriptive but not excessively long
Make sure that identifier names are sufficiently different, so
that you don't accidentally mix them up
Use underscores (_) or camel caps/case to distinguish
between words, i.e. average_score or averageScore
Variable Declarations
Declaring a variable reserves memory space for a value
It also associates a name with a memory cell
These names are user-defined identifiers
Variable data type precedes variable name:
double miles; /* will store # of miles */
int count; /* will store # of zeros found */
char initial; /* will store first initial */
Every variable must be declared!
All variables in C must be declared before any executable
statements!!! i.e. before statements like printf (), scanf (), etc.
Data Types
Data type = set of values + set of operations on those values
Can be associated with variables (changeable) or constants (non-
changeable)
C defines several standard data types
int
Models the integers (at least -32767 to 32767, but most
machines define 32-bit integers)
Several operations are defined, including +, -, *, /, and %
(mod), and comparisons (>, <, <=, >=, ==, !=)
Data Types Contd.
double
models real numbers (must include a decimal point)
not all real numbers can be modeled because of space
limitations (64 bits)
Several operations are defined, including +, -, *, and /, and
comparisons (>, <, <=, >=, ==, !=)
Scientific notation can be used to write double values (e.g.,
15.0e-3, 314e-01)
char
Models individual ASCII characters (8 bits)
Can compare characters (>, <, <=, >=, ==, !=)
When defining char variables in a program, use single
quotes: 'c',' ','"', etc.
Executable Statements
Follow variable and constant declarations
Do the work of the algorithm by transforming inputs into outputs

score1 score1
60 60

score2 Machine score2 Machine


70 language 70 language
encoding encoding
score3 of score3 of
compute compute
80 80
average average
program program
average average
??? 70.0
Executable Statements Contd.
Assignment statements
Store a computational result into a variable
The = operator does the assignment
The *, -, +, /, operators perform the computation
Example:
volume = (1/3) * PI * radius * radius * height; /* always 0
because of 1 / 3 */
Note: above will yield an int for 1 / 3 instead of a double, so
we need to perform a cast:
volume = ((double) 1 / 3) * PI * radius * radius * height;
We can also assign the value of one variable to another:
y = x; /* assigns y to the value of x */
y = -x; /* computes the negation of x, assigning
it to y */
Executable Statements Contd.
Input/output Statements
It is extremely useful to obtain input data interactively from
the user, and to display output results to the user
How can this be done in C?
The C input/output library defined in <stdio.h> (which you
must #include if you want to use it) includes several functions
that perform input and output
Executable Statements Contd.
Input/Output Statements (cont.)
The printf function can be used to output results to the user's
display
Example
printf("The student's average is %f.",average);

Function Function
name arguments Placeholder Print list

Notes
%f is a placeholder for double (%lf in scanf); %d is a
placeholder for int; and %c is a placeholder for char
Multiple placeholders can exist within a single format
string (see next example)
Executable Statements Contd.
Input/Output Statements (cont.)
Another example:
printf("Wow, %c%c%c%c %d sure is cool!\n",letter_1, letter_2,
letter_3, letter_4, course_num);
would display
Wow, CptS 121 sure is cool!
Assuming that letter_1 is 'C', letter_2 contains 'p', letter_3
contains 't', letter_4 contains 'S', and course_num contains
121.

Note that '\n' prints a newline (return), causing the cursor to


advance to the next line.
Executable Statements Contd.
Input/Output Statements (cont.)
The scanf function reads an input value from the keyboard
Its format is similar to that of printf
Example: scanf("%d",&score1);
forces the program to pause until the user enters a value
from the keyboard and hits the return key.
Notes
scanf interprets the input as an int (%d is a placeholder for
an int).
The int value is then stored into the variable score1. The &
("address of") operator tells scanf where to store the
inputted value.
If the & were omitted, scanf would only know the value of
score1, not where in memory it is located
Executable Statements Contd.
Input/Output Statements (cont.)
scanf should always be used in conjunction with a printf
statement that displays a prompt, so that the user knows that
an input value is expected
Example:
printf ("Enter radius of base of cone as integer: ");
scanf ("%d", &radius);

Notes
User may separate values with either spaces or returns
If more values are entered than are specified in a scanf,
they are saved ("buffered") for the next call to scanf
Executable Statements Contd.
return statement
In C, most functions, including main, return a value (just like a
mathematical function)
The return statement specifies the value to be returned
The type of the return value must match the declared return
value of the function
int main(void) { } indicates that an int is to be returned;
hence, main must return an int
In the main function, return(0) (a return value of 0) tells the
operating system that the program executed without error
General Structure of a C
Program
General template of a C program is as follows:
Comment block
preprocessor directives
main function heading
{
declarations
executable statements
}
Statements may extend over a single line (return is treated as a space)
Exception: Do not break up a statement in the middle of a reserved
word, constant, or quoted format string
More than one statement can go on a single line
The programs you write should adhere to good C style
Makes them more readable, but does not affect compilation
General Structure of a C
Program Contd.
What is good C style?
Insert blank space before and after commas and operators such as +,
=, /, *
Liberally comment your programs
Document the purpose of each variable where it is declared
Begin programs with a header section that indicates
Programmer's name ,Date of current version, Brief
description of what program does
/* Programmer:
* Date:
* Description: This program computes the
* volume of a cylinder.
*/
Program compilation and
execution
Input Program Output

Source code Preprocessor Expanded source

Expanded code Compiler Assembly source

Assembly source Assembler Object code

Object code Linker Executable code

Executable code Loader Execution


C Expressions & Operators
C Operators
An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations.
Operators used in programs to manipulate data & variables
C is very rich in built-in operators, classified into following number of
categories:
Arithmetic
Relational
Logical
Bitwise
Assignment
Increment/Decrement
Conditional
Arithmetic Operators
Table lists Cs arithmetic operators:

Integer division(/) truncates any fractional part (remainder).


Modulus operator (%) can not used be used on floating-point data. During
modulus operation, sign of the result is always the sign of the first
operand.
e.g.
5/2 -> 2
11%2 -> 1
Relational Operators
Relational refers to the relationships that values can have with one
another.
Expressions that use relational operators return 0 for false & 1 for
true
Logical Operators
Logical refers to the ways relationships can be connected.
Expressions that use logical operators return 0 for false & 1 for
true.

The truth table for logical operators is shown below:


Bitwise Operators
Bitwise operation refers to testing, setting, or shifting the actual bits
in a byte or word, which correspond to the standard char or int
data types.
Bitwise operator can not be used on float, double, long double or
void data types.
Assignment Operator
= used to assign the result of an expression to a variable. General
form: variable_name = expression;
Multiple assignments: x = y = z = 0;
Compound assignments: The statement of the form var = var
operator expression can be written as var operator = expression
e.g. x = x + 1 can written as x += 1
Increment/Decrement
++ adds 1 to its operand and -- subtracts 1 from its operand.
x = x +1 is same as ++x and x = x 1 same as --x
Both the increment and decrement operator may either in prefix
or postfix form.
When postfix (x++ or x--) is used with a variable in an expression,
the expression is evaluated first using the original value of the
variable and then the variable is incremented (or decremented) by
one.
When prefix (++x or --x) is used in an expression, the variable is
incremented (or decremented) first and then the expression is
evaluated using new value of the variable.
Conditional Operator
Also called ternary operator ?:
General form: exp1 ? exp2 : exp3
operation same as if-then-else statement
Operator Precedence &
Associativity
C Expressions
Expressions in C is any valid combination of operators, constants,
functions, and variables.
Expression is evaluated using precedence & associativity rule.
C Type Conversion
Implicit type conversion: C automatically converts any
intermediate values to the proper type so that the expression can
be evaluated without loosing any significance, called implicit type
conversion.
Rule: If the operands are of different types, the lower type is
automatically converted to higher type before operation
proceeds.
Explicit type conversion: When we force an expression to be a
specific type, called explicit type conversion.
General form: (data_type) expression;
e.g. int x;
float y;
x = (int) (y + 10.5);
Exercise
Number system and conversion:

Operator precedence and expressions


References
J.R. Hanly and E.B. Koffman, Problem Solving and Program Design
in C. 5th Edition. Pearson Education 2007
Brian W. Kernighan, Dennis Ritchie, The C Programming Language.
Prentice Hall. 2nd Edition.
E Balaguruswamy, Programming in ANSI C, 4th Edition, Tata
McGraw-Hill Education, 2008
J. B. Dixit, Programming in C, Third Edition, Firewall Media 2010

Potrebbero piacerti anche