You are on page 1of 55

MODULE 1:

INTRODUCTION TO
COMPUTERS AND C
PROGRAMMING

CS101
Objectives
• At the end of module, student will be able to learn the
following:
o Introduction to programming languages
o Basics of a typical C program development environment
o Steps in designing a program to solve a problem
o Algorithms / Pseudocode / Flowchart
o Simple C programs
o Variables and Data Types
o Operators, Expressions and Statements
What is Programming?
• Programming is instructing a computer to do
something for you with the help of a programming
language

• The two roles of a programming language:


o Technical: It instructs the computer to perform
tasks.
o Conceptual: It is a framework within which we
organize our ideas about things and processes.
Programming Language
• Formal Language used to communicate to a
computer.
• A programming language contains
instructions for the computer to perform a
specific action or a specific task:
o 'Calculate the sum of the numbers from 1 to 10‘
o 'Print “I like programming”‘
o 'Output the current time'
Programming Language
• Can be classified into as a special-purpose and
general-purpose programming languages.
• Special-purpose : is design for a particular type of
application
o Structured Query Language (SQL)
• General-purpose : can be used to obtain solutions for
many types of problems
o Machine Languages
o Assembly Languages
o High-Level Languages
Machine Language
• The only language that the processor actually 'understands‘
• Consists of binary codes: 0 and 1
o Example: 00010101
11010001
01001100
• Each of the lines above corresponds to a specific task to be
done by the processor.
• Programming in machine code is difficult and slow since it is
difficult to memorize all the instructions.
• Mistakes can happen very easily.
• Processor and Architecture dependent
Assembly Language
• Enables machine code to be represented in words and
numbers.
• Example of a program in assembler language:
LOAD A, 9999
LOAD B, 8282
SUB B
MOV C, A
LOAD C, #0002
DIV A, C
STORE A, 7002

• Easier to understand and memorize (called Mnemonics),


compared to machine code but still quite difficult to use.
• Processor and Architecture dependent
High-Level Language
• Use more English words. They try to resemble English
sentences. Therefore, it is easier to program in these languages.
• The programming structure is problem oriented - does not
need to know how the computer actually executes the
instructions.
• Processor independent - the same code can be run on different
processors.
• Examples: Basic, Fortran, Pascal, Cobol, C, C++, Java
• A high level language needs to be analyzed by the compiler and
then compiled into machine code so that it can be executed by
the processor.
C Programming
Language
Why 'C' ?
• Because based on 'B'; developed at Bell Laboratories
• Developed by Dennis Ritchie at Bell Laboratories in
the 1960s
• In cooperation with Ken Thomson it was used for
Unix systems
• The C Language was only vaguely defined, not
standardized, so that almost everyone had his own
perception of it, to such an extend that an urgent need
for a standard code was creeping up
C Development
Environment
• Editor
Phase 1 Disk
Program is created using
the Editor and stored on
Disk.
• Preprocessor
Phase 2 Disk
Pre-processor program
processes the code.

• Compiler
Phase 3 Disk
Compiler creates object
code and stores it on Disk.

Linker links object code with


• Linker
Phase 4 Disk libraries, creates a.out and
stores it on Disk

• Loader
Phase 5 Disk
Loader puts Program in
Memory

CPU takes each instruction


• CPU (Execute)
Phase 6 Disk
and executes it, storing new
data values as the program
executes.
C Development
Environment

Entering, translating, and running a High-Level Language


Program
Software Development Method (SDM)

Is a framework that is used to structure, plan, and


control the process of developing an information
system, which include the following steps:
1. Specification of needs
2. Problem analysis
3. Design algorithm
4. Implementation
5. Testing and verification
6. Documentation
Design Algorithm
• An algorithm can be represented using pseudocodes or
flowcharts:
1. Pseudocode: is a semiformal, English-like language with
limited vocabulary that can be used to design and describe
algorithms.
2. Flowcharts: is a graph used to depict or show a step by step
solution using symbols which represent a task

prepared by NI, edited by MAF


Pseudocodes: The Sequence control structure

• A series of steps or statements that are executed in the order they


are written in an algorithm.
• The beginning and end of a block of statements can be optionally
marked with the keywords begin and end.
• Example-1:
Begin
Read the birth date from the user.
Calculate the difference between the birth date
and today’s date.
Print the user age.
End
Flowchart – example-1
Flowchart Symbols

Begin
Terminal symbol - indicates the beginning
and end points of an algorithm.

Read birth date Process symbol - shows an instruction other


than input, output or selection.

Input-output symbol - shows an input


Calculate or an output operation.
Age = current year – birth date

Selection symbol - shows a selection process


for two-way selection.
Display
age

Flow lines - indicate the logical sequence of


execution steps in the algorithm.
End
Pseudocodes: The Selection control structure

• Defines two courses of action depending on the outcome of a


condition. A condition is an expression that is, when
computed, evaluated to either true or false.
• The keyword used are if and else.
• Format: Example-2:
if condition
if age is greater than 55
then-part print “Retire”
else else
print “Work Work Work”
else-part
end_if
end_if
Flowchart – example-2
Begin

Read age

YES Age > 55? NO

print “retired” print “keep working”

End
Pseudocodes: The Repetition control structure

• Specifies a block of one or more statements that are


repeatedly executed until a condition is satisfied.
• Example-3: Summing up 1 to 10
set cumulative sum to 0
set current number to 1
while current number is less or equal to 10
add the cumulative sum to current number
add 1 to current number
end_while
print the value of cumulative sum
Flowchart – example 3
Begin

sum = 0
current_number = 1

NO
current_number <= 10? print sum

YES
End
sum = sum + current_number
current_number = current_number + 1
A Simple Program in C
#include <stdio.h>

int main()
{
printf("I like programming in C.\n");
return 0;
}
A Simple Program in C -
explanation

#include <stdio.h>
standard Library, input-output, header-file

Begin of program

void main()
{ Start of Segment

Function for printing text


printf("I like programming in C.\n");

Insert a new line End of statement


}
End of Segment
C Output

I like programming in C.
C Program Structure
• An example of simple program in C

#include <stdio.h>

void main()
{
printf(“I love programming\n”);
printf(“You will love it too once ”);
printf(“you know the trick\n”);
}
The output
• The previous program will produce the following output on
your screen
I love programming
You will love it too once you know the trick
Preprocessor directives
• a C program line begins with # provides an instruction to the
C preprocessor
• It is executed before the actual compilation is done.
• The most common directive :
o #include

• In our example (#include<stdio.h>) identifies the header file


for standard input and output needed by the printf().
Function main
• Identify the start of the program
• Every C program has a main ( )
• 'main' is a C keyword. We must not use it for any other
variable.
• 2 common ways of main declaration

int main() void main()


{ {

return 0;
} }
The curly braces { }
• Identify a segment / body of a program
o The start and end of a function
o The start and end of the selection or repetition block.
• Since the opening brace indicates the start of a segment with
the closing brace indicating the end of a segment, there must
be just as many opening braces as closing braces (this is a
common mistake of beginners)
Statement
• A specification of an action to be taken by the computer as
the program executes.
• Each statement in C needs to be terminated with semicolon
(;)
• Example:
#include <stdio.h>
void main(void)
{
statement
printf(“I love programming\n”);
printf(“You will love it too once ”);
statement
printf(“you know the trick\n”);
} statement
Statement cont…
• Statement has two parts :
o Declaration
• The part of the program that tells the compiler the names of memory cells in a
program
o Executable statements
• Program lines that are converted to machine language instructions and executed by
the computer
C program skeleton
• In short, the basic skeleton of a C program looks like this:

#include <stdio.h>
void main(void) Preprocessor directives
{
Function main
statement(s);

} Start of segment

End of segment
Variables
• Variable  a name associated with a memory cell whose
value can change
• Variable Declaration: specifies the type of a variable
o Example: int num;

• Variable Definition: assigning a value to the declared


variable
o Example: num = 5;
Constants
• Entities that appear in the program code as fixed values.
• Any attempt to modify a CONSTANT will result in error.
• Example:
o const int MAX_NUM = 10;
o const double PI= 3.14;
Constants cont…
o Character constants
• A character enclosed in a single quotation mark
• Example:
o const char letter = ‘n’;
o const char number = ‘1’;
o printf(“%c %c %c”, letter,‘S’,number);
• Output would be: n S l
Keywords
• Key words - Reserved Words
o Keywords that identify language entities such as statements, data types, language
attributes, etc.
o Have special meaning to the compiler, cannot be used as identifiers (variable, function
name) in our program.
o Should be typed in lowercase.
o Example: const, double, int, main, void,printf, while, for, else (etc..)
Rules Example
Rules for naming Variables/ H2o
Constants
Can contain a mix of character and numbers. However it
cannot start with a number
First character must be a letter or underscore Number1
_area
Can be of mixed cases including underscore character XsquAre
my_num
Cannot contain any arithmetic operators R*S+T
… or any other punctuation marks #@x%!!
Cannot be a C keyword/reserved word struct; printf;

Cannot contain a space My height


… identifiers are case sensitive Tax != tax
Basic Data Types
• There are 4 basic data types :
o int
o float
o double
o char
• int
o used to declare numeric program variables of integer type
o whole numbers, positive and negative
o keyword: int
int number;
number = 12;
Basic Data Types cont…
• float
o fractional parts, positive and negative
o keyword: float
float height;
height = 1.72;
• double
o used to declare floating point variable of higher precision
or higher range of numbers
o exponential numbers, positive and negative
o keyword: double
double valuebig;
valuebig = 12E-3; (is equal to 12X10-3)
Basic Data Types cont…
• char
o equivalent to ‘letters’ in English language
o Example of characters:
• Numeric digits: 0 - 9
• Lowercase/uppercase letters: a - z and A - Z
• Space (blank)
• Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
o single character
o keyword: char
char my_letter;
my_letter = 'U'; The declared character must be
enclosed within a single quote!
Objectives
• In this chapter, you will learn about:
o Arithmetic operators
• Unary operators
• Binary operators
o Assignment operators
o Equalities and relational operators
o Logical operators
o Conditional operator
Arithmetic Operators I
• In C, we have the following operators (note that all these
example are using 9 as the value of its first operand
coefficient)
Operation Operator Operand Value After
Addition + 2 11
Subtraction - 2 7
Multiplicati * 2 18
on
Division / 3 3
Increment ++ + 10
Decrement -- - 8
Modulus % 2 1
(reminder)
Arithmetic Operators II
• There are 2 types of arithmetic operators in C:
o unary operators
• operators that require only one operand.
o binary operators.
• operators that require two operands.
Unary Operator
C Operation Operator Example
Positive + a=+3
Negative - b=-a
Increment ++ i++
Decrement -- i--

• The first assigns positive 3 to a


• The second assigns the negative value of a to b.
• i++ is equivalent to i = i + 1
• i-- is equivalent to i = i-1
PRE- / POST-Increment
• It is also possible to use ++i and --i instead of i++ and i--
• However, the two forms have a slightly yet important difference.
• Consider this example:
int a = 9; printf(“%d\n”, a);
printf(“%d\n”, a++); a=a+1;
printf(“%d”, a); printf(“%d”, a);

• The output would be:


9
10
PRE- / POST-Increment
cont…
• But if we have:
int a = 9;
printf(“%d\n”, ++a);
printf(“%d”, a);
• The output would be:
10
10
• a++ would return the current value of a and then increment
the value of a
• ++a on the other hand increment the value of a before
returning the value
The following table illustrates the difference between the prefix and postfix

modes of the increment and decrement operator.

int R = 10, count=10;

++ Or -- Equivalent R value Count


Statement Statements value
R = count++; R = count;
count = count + 1 10 11
R = ++count; count = count + 1;
R = count; 11 11
R = count --; R = count;
count = count – 1; 10 9
R = --count; Count = count – 1;
R = count; 9 9
Binary Operators
C Operation Operator Example
Addition + a+3
Subtraction - a-6
Multiplication * a*b
Division / a/c
Modulus % a%x

• The division of variables of type int will always


produce a variable of type int as the result.
• You could only use modulus (%) operation on int
variables. Usually between two int. numbers
Assignment Operators
• Assignment operators are used to combine the '='
operator with one of the binary arithmetic operators
• In the following slide, All operations starting from
c=9
Equivalent Example Results Operator
Statement
c=c+7 c += 7 c = 16 +=
c=c–8 c -= 8 c=1 -=
c = c * 10 c *= 10 c = 90 *=
c=c/5 c /= 5 c=1 /=
c=c%5 c %= 5 c=4 %=
Precedence Rules
• Precedence rules come into play when there is a mixed of arithmetic
operators in one statement. For example: x = 3 * a - ++b%3;
• The rules specify which of the operators will be evaluated first.

Precedence Operator Associativity Level


1 (highest) () Left to right
2 Unary ++ -- Right to left
3 */% Left to right
4 +- Left to right
6 (lowest) = += -= *= /= %= Right to left
Precedence Rules cont…
• For example: x = 3 * a - ++b % 3;
how would this statement be evaluated?

• If we intend to have the statement evaluated differently from


the way specified by the precedence rules, we need to specify
it using parentheses ( )
• Using parenthesis, we will have
x = 3 * ((a - ++b)%3);
• The expression inside a parentheses will be evaluated first.
• The inner parentheses will be evaluated earlier compared to
the outer parentheses.
Equality and Relational
Operators
• Equality Operators:
Operator Example Meaning
== x==y x is equal to y
!= (Exclamation Mark) x!=y x is not equal to y
• Relational Operators:

Operator Example Meaning


> x>y x is greater than y
< x<y x is less than y
>= x>=y x is greater than or equal to
y
<= x<=y x is less than or equal to y
Logical Operators
• Logical operators are useful when we want to test
multiple conditions.
• There are 3 types of logical operators and they work the
same way as the boolean AND, OR and NOT operators.
• && - Logical AND
o All the conditions must be true for the whole expression to be true.
o Example: if (a == 10 && b == 9 && d == 1)
means the if statement is only true when a == 10 and
b == 9 and d == 1.
Logical Operators cont…
• || - Logical OR
o The truth of one condition is enough to make the whole expression true.
o Example: if (a == 10 || b == 9 || d == 1)
means the if statement is true when either one of a, b or d has the right value.

• ! - Logical NOT (also called logical negation)


o Reverse the meaning of a condition
o Example: if (!(points > 90))
means if points not bigger than 90.
Conditional Operator
• The conditional operator (?:) is used to
simplify an if/else statement.
• Syntax:
Condition ? Expression1 : Expression2
• The statement above is equivalent to:
if (Condition)
Expression1
else
Expression2
Conditional Operator
cont…
• Example 1:
if/else statement:
if (total > 60)
grade = ‘P’
else
grade = ‘F’;
conditional statement:
total > 60 ? grade = ‘P’: grade = ‘F’;
OR
grade = total > 60 ? ‘P’: ‘F’;
Conditional Operator
cont…
• Example 2:
if/else statement:
if (total > 60)
printf(“Passed!!\n”);
else
printf(“Failed!!\n”);

Conditional Statement:
printf(“%s!!\n”, total > 60? “Passed”: “Failed”);

You might also like