45
Programming Variables

Programming Variables. Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.) They

Embed Size (px)

Citation preview

Programming

Variables

Variables

Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.)

They contain the data your program works with

Variable Declaration Before using a variable, one must declare it. Variables declaration may only appear at the

beginning of a block. The declaration first introduces the variable type,

then its name. When a variable is declared, its value is

undefined.

int integer;float small_real;double big_real;char c1, c2;

Type Identifier

Naming Rules

Letters, digits, underscores i CSE_5a a_very_long_name_that_isnt_very_useful fahrenheit

First character cannot be a digit 5a_CSE is not valid!

Case sensitive CSE_5a is different from cse_5a

Variables in Memory

5

int my_int = 5;

double my_double = 3.5;

3.5

my_int

my_double

memory

Initialization

Variables in Memory

5

Whenever we write the variable name (e.g. my_int), we ask to read the value of that variable

If we write &variable_name, we ask for the address of that variable

3.5

my_int

my_double

memory

Example: Variable Declarations

int i, j;

char c;

float f1 = 7.0,

f2 = 5.2;

double d;

Primitive Data Types char – character (1 byte)

‘a’, ‘b’, ‘c’ ..., ‘A’, ‘B’, ‘C’, ... ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘0’ ‘_’ ‘,’ ‘#’ ‘$’ ‘^’ ‘*’ ‘@’ ‘!’ ....

int – integer number (4 bytes). 0, -1, 1, -2, 2, ....

float – real number (4 bytes) 0.5, 3.2, 4.0, -5.122323, ...

double – double precision real number (8 bytes)

char

int

float

double

/* Convert cm to inches */#include <stdio.h>

void main(){

double cm = 5.0, inches;

inches = cm / 2.54;printf("5.0 cm are equal to %g inches\n", inches);

}

Example

/* Convert cm to inches */#include <stdio.h>

void main(){

double cm = 5.0, inches;

inches = cm / 2.54;printf("5.0 cm aer equal to %g inches\n", inches);

}

Example

Initialization

Assignment

Assign the identifier on the left hand side the value of the expression on the right hand side.

/* Convert cm to inches */#include <stdio.h>

void main(){

double cm = 5.0, inches;

inches = cm / 2.54;printf("5.0 cm are equal to %g inches\n", inches);

}

Example

What is THAT?

Printing Variable Values

printf – prints formatted data to the standard output (usually the screen)printf("This is equal to %g inches\n", inches);

The sequence %g is a special sequence, it is not printed!

It indicates to printf to print the value of a real variable following the printed string.

printf Conversion Codes

%c – a character %d – an integer, %u – an unsigned integer. %f – a float %e – a float in scientific representation %g – whichever is better between %e and %f %lf – a double %% - the ‘%’ character

Exercise

Write a program the converts 1250.25 USD into NIS.

The exchange rate is 4 NIS for USD

Solution

#include <stdio.h>

void main(){ double usd = 1250.25, xrate = 4.0, nis;

nis = usd * xrate;

printf("%g USD = %g NIS (exchange rate = %g)\n", usd, nis, xrate);

}

Problem?

Getting Input From the User

scanf("%lf", &usd);

This statement waits for the user to type in a double value, and stores it in the variable named ‘usd’.

To get 2 doubles from the user, use –scanf("%lf%lf", &usd, &xrate);

scanf Conversion Codes

%c – a character %d – an integer, %u – an unsigned integer. %f – a float %e – a float in different representation %lf – a double

Example printf/scanf

void main(){

int num, num1;

/* Initialize the variables and display their contents. */num = 3;num1 = 5;printf("Before scanf: num is %d and num1 is %d\n", num, num1);

/* Get two values from the user and store them in the variables */printf("Enter two numbers\n");scanf("%d%d", &num, &num1);

/* Display the content of the variables */printf("After scanf: num is %d and num1 is %d\n", num, num1);

}

Exercise

Change your previous solution:

Get the amount of USD and the exchange rate as input from the user.

Solution

#include <stdio.h>

void main(){ double usd, xrate, nis;

printf("Please enter amount of dollars: "); scanf("%lf", &usd); printf("Please enter the exchange rate: "); scanf("%lf", &xrate);

nis = usd * xrate;

printf("%g USD = %g NIS (exchange rate = %g)\n", usd, nis, xrate);}

Char

A char variable is used to store a text character:Letters.Digits.Keyboard signs.Non-printable characters.But also small numbers (0 to 255 or -128 to

127).

Text as Numbers

Every character is assigned a numeric code.

There are different sets of codes:ASCII (American Standard Code for

Information Interchange) – most common.EBCDIC – ancient, hardly used today.Maybe others.

We will use ASCII

The ASCII Table

Character Encoding

Most of the time, you don't care what the particular encoding is.

The table above shows only 128 characters (7 bits). Some are non-printable.

Extended ASCII code contains 256 characters.

Encoding Example

#include <stdio.h>

void main(){

char c = 'b';

printf("c as a character is %c\n", c);printf("c as an integer is %d\n", c);printf("The character after %c is %c\n",

c, c + 1);}

c as a character is bc as an integer is 98The character after b is c

Another example

/* Get the position of a letter in the abc */#include <stdio.h>

void main(){

char letter;

printf("Please enter a lowercase letter\n");scanf("%c", &letter);printf("The position of this letter in the abc is %d\n", letter - 'a' + 1);

}

Exercise

Write a program that accepts as input – A lowercase letter

and outputs – The same letter in uppercase

Do not use the ASCII table directly

(e.g., if the input is ‘g’, the output should be ‘G’)

Solution

/* Convert a letter to uppercase */#include <stdio.h>

void main(){

char letter;

printf("Please enter a lowercase letter\n");scanf("%c", &letter);printf("This letter in uppercase is %c\n", letter - 'a' + 'A');

}

Expressions

“Things” that have value and type 1, 2.5, ‘a’ cm, letter

We can build complex expression from simple ones using operators.

Arithmetic Operators

+ Addition - Subtraction * Multiplication / Division % Modulo = Assignment

Complex Expressions

1 + 2 letter + 1 cm / 2.54 a = b

The value of assignment expression is the assigned (right hand side) value

1 + 0.5cm * 3

When operands of two different types are involved in an operation, the operand of the ‘weaker’ type is promoted to the other type

char → int → float → double.

The result of the operation has the higher type. When the operands are of the same type, the

result is of that type as well.

Mixing Types

3 + 4 = 7 (int + int → int) 3.0 + 4 = 7.0 (double + int →

double) 3 / 4 = 0 (int / int → int) 3.0 / 4 = 0.75 (double / int →

double)

Mixing Types - Example

Example -

A program that sums the digits of a number with three digits.

For example:The input 369 yields the output 18

void main(){

int sum = 0, num;

printf("Enter 3-digits number\n");scanf("%d", &num);

sum = sum + num % 10;num = num / 10;

sum = sum + num % 10; num = num / 10;

sum = sum + num % 10;

printf("The sum of the digits is %d\n", sum);}

Sum Digits

Exercise

Copy the above program Run in the debugger and see how it works

Sometimes it is desirable for a variable of one type to be considered as belonging to another in an operation

We say the variable is cast to the new type. The casting operator is of the form: (type) For example, (float)i casts the variable i to

a float.

Casting

#include <stdio.h>

void main(){

int a = 1, b = 2;

printf("%d / %d = %d\n", a, b, a/b);printf("%d / %d = %g\n", a, b, (float)a / b);

}

Casting Variables

1 / 2 = 01 / 2 = 0.5

Find The Problem

#include <stdio.h>

void main(){ int a = 10; int b = 20;

printf("The average of %d and %d is %d\n", a, b, (a + b) * (1 / 2));}

Will This Work?

#include <stdio.h>

void main(){

int a = 10; int b = 20;

printf("The average of %d and %d is %d\n", a, b, (a + b)*(1.0 / 2));}

The unsigned qualifier

Normally, the last bit of a variable serves as a sign bit.

We can use all the bits to represent the value by declaring a variable as unsigned.

To declare a variable as unsigned we add the ‘unsigned’ keyword before its type. unsigned int; unsigned char;

sign(-/+) value

Unsigned Range

Char (256 different values)signed -127..+128unsigned 0..+255

Int (4294967296 different values)signed -2147483648.. +2147483647unsigned 0.. +4294967295

Unsigned - output

When using printf We use %d for signed variables and %u for unsigned ones

void main()}

unsigned char u = 200; char s;

printf("%d\n", u); printf("%u\n", u);

s = u;

printf("%d\n", s); printf("%u\n", s);

{

200

-56

4294967240

Overflow

Happens when a variable gets assigned a value that is outside of its range

This is equivalent to saying that the number of bits required to encode the value exceeds the number of bits in the variable

The value of the variable will usually be corrupted

Overflow Example

#include <stdio.h>

void main(){

int iA = 1000, iB = 1000000, iC = 3000000, iD = 5000000;printf ("%d * %d = %d\n", iA, iB, iA*iB);

printf ("%d * %d = %d\n", iA, iC, iA*iC); printf ("%d * %d = %u\n", iA, iC, iA*iC);

printf ("%d * %d = %u\n", iA, iD, iA*iD);}

1000000000-1294967296

3000000000705032704