Sei sulla pagina 1di 12

7/4/2020

Data types, variables, constants


Computer was modelled
Outline
after Human
2.1 Introduction
2.2 A Simple C Program: Printing a Line of Text
2.3 Another Simple C Program: Adding Two Integers Sensory Memory
( <1 sec)
2.4 Memory Concepts
2.5 Arithmetic in C
Short Term Memory
(<1 minute)

Long Term Memory


(Life Time)

http://www.human-memory.net/types_sensory.html

A simple model of the computer Input and output devices


Short term
Main
Memory
Memory

Sensory Input devices allow us to get information into the computer


Memory

Input
Output
Devices Devices Computer
Input Buffer Processor
Devices

Permanent
Long term
Storage
Memory

Input and output devices Input and output devices

Output devices allow us to get information out of the computer Input and output devices are known as peripherals

Output Input Output


Computer Devices Devices Computer Devices

1
7/4/2020

keyboards
Input/output devices
What input/output devices can you think of?

Mice speakers

headphones Printers

2
7/4/2020

monitors scanners

Digital cameras Huh?


• An Input device puts info into the CPU.

• An Output device reads info put out by the CPU.

Definition: Computer Program Example: Computer Program


Computer tell me what would be my balance
after 1 year if my starting balance is 1,00,000
A Computer program is a sequence of and interest rate is 10%.
instructions written to perform a specified Balance
task with a computer. New Balance
Rate
Processing
Year
OUTPUT
INPUT

COMPUTATION

3
7/4/2020

Introduction

• C programming language
– Structured and disciplined approach to program design
– Story  Paragraph  Sentence
– Program  Function  Statement

Steps for developing a program

1. Write your program


2. Check Correctness (Compile)
3. Execute

A Simple C Program: Printing a Line of A Simple C Program: Printing a Line of


Text Text (II)
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */ • int main()
3 #include <stdio.h>
4 – C programs contain one or more functions, exactly one of
5 int main()
6 { which must be main
7 printf( "Welcome to CSE 115!\n" );
8 – Parenthesis used to indicate a function
9 return 0;
10 }
– int means that main "returns" an integer value
Welcome to CSE 115! – Braces indicate a block
• The bodies of all functions must be contained in braces
• Comments
– Text surrounded by /* and */ is ignored by computer
– Used to describe program

• #include <stdio.h>
– Preprocessor directive - tells computer to load contents of a certain file
– <stdio.h> allows standard input/output operations

4
7/4/2020

A Simple C Program: Printing a Line of A Simple C Program: Printing a Line of


Text (III) Text (IV)
• printf( "Welcome to C!\n" ); • return 0;
– Instructs computer to perform an action
• Specifically, prints string of characters within quotes – A way to exit a function
– Entire line called a statement – return 0, in this case, means that the program terminated
• All statements must end with a semicolon normally
– \ - escape character
• Indicates that printf should do something out of the • Right brace }
ordinary
– Indicates end of main has been reached
• \n is the newline character

Printing special characters Basic Data types

What How
New line printf( "\n" );
Type Example Size Range Format Code
Tab printf( "\t" );
char A B C..Z 8 bits, -128 to +127 “%c”
Alarm printf( "\a" ); a b c..z 1 byte
@ $ % *
Double quote printf( "\"" );
int 32, 3, 4 ,5 32 bits, -2,14,74,83,648 to “%d”
Slash(\) printf( "\\" ); -4, -5, -6 4 bytes +2,14,74,83,647 “%i”
float 3.4, 5.25, 32 bits, 3.4E-38 to 3.4E+38 “%f”
Percent (%) printf( “%%" ); -2.3, -6.7 4 bytes
double 3.4, 5.25, 64 bits, 1.7E-308 to “%lf”
-2.3, -6.7 8 bytes 1.7E+308

Representing integers Representing fractions (float/double)

0.35 0.01011 458 111001010

.692 0.1011

458.692 111001010.1011

5
7/4/2020

Representing characters
Memory Concepts
Represent characters as integral numbers. This is called Coding.
ASCII  American Standard Code For Information Interchange • Variables
– Variable names correspond to locations 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) previous value
– Reading variables from memory does not change them
• A visual representation

a 45

Using Variables: Output Suppose we want……


Format specifier Variable

int a, b, c; printf(type, what); int a, b, c;


a = 3; Output:
a = 3; Output:

b = 8; b = 8;
11 The value of c: 11
c = a + b; c = a + b;
Type Format Code

printf("%d" , c); char "%c" printf("%d" , c);


int "%d"
"%i"
float "%f"
double "%lf"

You can do…… Or….

int a, b, c; int a, b, c;
a = 3; Output:
a = 3; Output:

b = 8; b = 8;
The value of c: 11 The value of c: 11
c = a + b; c = a + b;
printf("The value of c:"); printf("The value of c: %d",c);
printf("The value of c: %d",c);
printf("%d" , c);

6
7/4/2020

Using Variables: Output Data input


int a, b, c; float a = 8.958;
Format specifier Variable with & sign float b;
a = 3; printf("%f ", a);
scanf(type, where); scanf("%f", &b);
b = 8; double a = -9.8;

c = a + b; printf("%lf ", a); int a; double c;


printf("%d" , c); char a = ‘Z’; scanf("%i", &a); scanf("%lf", &c);
printf("%c", a); or char d;
char x = 65; scanf("%d", &a); scanf("%c", &d);
printf("%c", x);

Little QUIZ (What is the output if user Naming convention of a variable


enters 0)
• Capital letters A-Z, lowercase letters a-z, digits 0-
9, and the underscore character
int a; char a; • First character must be a letter or underscore
• Usually only the first 31 characters are significant
scanf("%i", &a); scanf("%c", &a); • There can be no embedded blanks
printf("%d", a); printf("%d", a); • Keywords cannot be used as identifiers
• Identifiers are case sensitive

Key words in C

Ke yw o rd s

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void Try to give meaningful name to your variables
default goto sizeof volatile
do if static while

7
7/4/2020

Some meaningful names Same valid/invalid variable names

• interest • First_tag
• balance • char
• year • Price$
• month • group one
• average_number
• int_
• 8boys

Arithmetic Operators for int Simple Example: Use of operators

• Arithmetic operators:
Write down a program that will take two integers
as input and will print the results of their addition,
subtraction, multiplication and division.
C o p era tion Arithm etic Alg eb ra ic C exp ressio n
op era to r exp ressio n
#include <stdio.h>
Addition + f+7 f + 7
int main(){
Subtraction - p–c p - c
int a,b;
Multiplication * bm b * m
scanf(“%d%d”,&a,&b);
Division / x/y x / y
printf(“Addition: %d\n”,a+b);
Modulus % r mod s r % s printf(“Subtraction: %d\n”,a-b);
printf(“Multiplication: %d\n”,a*b);
printf(“Division: %d\n”,a/b);

A Rahman
Working with int…examples Interchanging content using
function?
• Interchange two numbers:
main(){
– Given integers as input, can you interchange their content? x y
int x, y;
scanf(“%d%d”,&x,&y);
int t;
t = x;
x = y;
y = t;
printf(“%d %d”,x,y);

Pointers 48

8
7/4/2020

Working with int…examples Working with int…examples


• Convert height of a person: • Time difference of two cities.
 Given height in feet inch as input  convert it to inch  Think time as two separate integers: one quantity for hour and the
 Given height in inch as input  convert it to feet inch other quantity for minute as input
– Dhaka: 11:20
– India: 10:50

Working with int…examples Working with int…examples


• To extract digits of a number: • Interchange two numbers:
– Given a 4-digit number as input, can you reverse it? – Given integers as input, can you interchange their content?
– Modulus (%) and division (/) operators are good enough. • Convert height of a person:
 Given height in feet inch as input  convert it to inch
 Given height in inch as input  convert it to feet inch
• Time difference of two cities.
 Think time as two separate integers: one quantity for hour and the
other quantity for minute as input
– Dhaka: 11:20
– India: 10:50
• To extract digits of a number:
– Given a 4-digit number as input, can you reverse it?
– Modulus (%) and division (/) operators are good enough.

Arithmetic Operators for float or double Working with fractions: Example 1

• Arithmetic operators: Sonali Bank annually provides interests at a


C operation Arithmetic Algebraic C expression
certain rate to all its clients having a savings
operator expression
Addition + f+7 f + 7 account with the bank. Write down a program that
Subtraction - p–c p - c will take initial balance, and annual interest rates
Multiplication * bm b * m
Division / x/y x / y and will determine and print: b = 1,00,000, r = 10%
(1) Balance after one year interest1 = 100000*0.1
Integer division vs Fractional division = 10,000
(2) Balance after two years b1 = 1,00,000 + 10,000
Example: Integer division: Example: Fractional division: = 1,10,000
5/3 = 1 5.0/3.0=1.667
(3) Balance after n years where
n will also be input to your b1 = 1,10,000, r = 10%
What about: 5.0/3 or 5/3.0? 1.667 interest2 = 110000*0.1
program. = 11,000
b2 = 1,10,000 + 11,000
Fractional division!! = 1,21,000

9
7/4/2020

Type conversion Type conversion: Example

• Lower to higher auto-conversion (called auto-casting) In mathematics the floor, ceil and round of a fractional
int x = 9;
number x is defined as follows:
float y = x; //OK no warning no error floor(x) = the largest integer not exceeding x
ceil(x) = the smallest integer not below x
• Higher to lower still auto-casting but generates warning round(x) = the nearest integer to x
float x = 9.5;
According to the above definition when x = 2.3,
int y = x; //OK but generates warning but no error
floor(x) = 2, ceil(x) = 3 and round(x) = 2
int y = (int) x; // warning is gone
(a) If x = 2.7 what are its floor, ceil and round values?
• Work out the followings: (b) Write down a program that will take a positive
float x = 5/3; float x = 5.0/3; fractional number x as input and will print its floor and
int y = 5/3; int y = 5.0/3; rounded values (ceil will be shown later when we learn
x = 1.0 y = 1 x = 1.6667 y = 1 55
if-else).

Working with characters Operator precedence


• Write down a program that prints ASCII value of
• Arithmetic operators:
a character given as input. (Hint: characters could C o p era tion Arithm etic Alg eb ra ic C exp ressio n
op era to r exp ressio n
be thought of as numbers) Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
• Write down a program that will take a small letter
Modulus % r mod s r % s
as input and will print its previous letter. (Hint: as
characters could be thought of as numbers, you are • Rules of operator precedence:
allowed to subtract/add numbers with it) Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the


expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
• Write down a program that will take an uppercase *, /, or % Multiplication Division Evaluated second. If there are several, they are
letter as input and will convert it to lower case Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
letter. Subtraction evaluated left to right.

Arithmetic (II) Operator Precedence examples

• Arithmetic calculations are used in most programs • Find the values of the followings:
– Use * for multiplication and / for division
– Integer division truncates remainder
7 / 5 evaluates to 1 5+6*7-8/7 = 46
– Modulus operator returns the remainder
7 % 5 evaluates to 2
5*4/3 = 6
• Operator precedence
– Some arithmetic operators act before others (i.e., multiplication
before addition) 5.0*4/3 = 6.667
• 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 5/(6+7) – 8%8 = 0

10
7/4/2020

Increment and Decrement Operators Increment and Decrement Operators (II)


• Increment operator (++) can be used instead of c=c+1 • When variable is in expression, then pre-
• Decrement operator (--) can be used instead of c=c-1. increment and post-increment matters.
• Preincrement Preincrement
– Operator is used before the variable (++c or --c) Operator is used before the variable (++c or --c)
– Variable is changed, then the expression it is in is evaluated
Variable is changed, then the expression it is in is evaluated
• Postincrement
– Operator is used after the variable (c++ or c--) Postincrement
– Expression executes, then the variable is changed Operator is used after the variable (c++ or c--)
• When variable not in an expression Expression executes, then the variable is changed
– Preincrementing and postincrementing have the same effect. If c = 5, then
c = 5;
printf( "%d", ++c);
++c;
printf(“%d”,c); Prints 6
and printf( "%d", c++);
c++; Prints 5
printf(“%d”,c); Prints 6 in both cases. In either case, c now has the value of 6

Assignment Operators
(shorthand notations) Problem Solving Methodology (must
• Assignment operators abbreviate assignment expressions read)
c = c + 3;
can be abbreviated as c += 3; using the addition assignment
operator
1. State the problem clearly
• Statements of the form
variable = variable operator expression; 2. Describe the input/output information
can be rewritten as
variable operator= expression; 3. Work the problem by hand, give example
4. Develop a solution (Algorithm Development)
• Examples of other assignment operators:
d -= 4 (d = d - 4) and Convert it to a program (C program)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
5. Test the solution with a variety of data

Example 2 Example 1 (cont’d)

(x1,y1)

1. Problem statement (x2, y2) 3. Hand example


Compute the straight line distance  side12  side2 2

distance between two points in a plane side1 = 4 - 1 = 3


2. Input/output description side2 = 7 - 5 = 2
distance  side12  side2 2
Point 1 (x1, y1)
Distance between two points (distance)
Point 2 (x2, y2) distance  32  2 2
distance  13  3.61
66
65

11
7/4/2020

Example 1 (cont’d) Example 1 (cont’d)

4. Algorithm development and coding


a. Generalize the hand solution and list/outline the necessary
operations step-by-step
1) Take input for point1 (x1, y1) and point2 (x2, y2)
2) Compute side1=x2-x1 and side2=y2-y1
3) Compute distance  side12  side2 2
4) Print distance
b. Convert the above outlined solution to a program using any
language you want (see next slide for C imp.)

67 68

Example 1 (cont’d) Modification to Example 1

How will you find the distance between two other points (2,5) and (10,8)?
5. Testing
• After compiling your program, run it and see if it
gives the correct result.
• Your program should print out
The distance between two points is 3.61 x1=2, y1=5, x2=10, y2=8,

• If not, what will you do?

69 70

12

Potrebbero piacerti anche