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

Slides:



Advertisements
Similar presentations
Lecture 9: Character and String
Advertisements

Computer Programming w/ Eng. Applications
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
1 Key Concepts:  Data types in C.  What is a variable?  Variable Declaration  Variable Initialization  Printf()  Scanf()  Working with numbers in.
1 Introduction to Computers and Programming Class 3 Introduction to C Professor Avi Rosenfeld.
Chapter 2 Data Types, Declarations, and Displays
Introduction to C Programming
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
C programming for Engineers Lcc compiler – a free C compiler available on the web. Some instructions.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 2: Using Data.
Week 1 Algorithmization and Programming Languages.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
CSCI 171 Presentation 2. Program Components main() #include Variable Definition Function Prototype Program Statements Function Call Function Definition.
1 C Programming Week 2 Variables, flow control and the Debugger.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
E-1 University of Washington Computer Programming I Lecture 5: Input and Output (I/O) © 2000 UW CSE.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
Agenda  Take up homework  Loops - Continued –For loops Structure / Example involving a for loop  Storing Characters in variables  Introduction to Functions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Dr. Sajib Datta Jan 21,  Declare a variable ◦ int height; [note that no value is still assigned]  Assign a variable a value ◦ height =
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
USER INTERACTION AND VARIABLES Tarik Booker CS 290 California State University, Los Angeles.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
CSCE 206 Structured Programming in C
User Interaction and Variables
Revision Lecture
Chapter 2 Overview of C.
ICS103 Programming in C Lecture 3: Introduction to C (2)
By: Syed Shahrukh Haider
Introduction to C Programming
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
IDENTIFIERS CSC 111.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Introduction to CS Your First C Programs
INPUT & OUTPUT scanf & printf.
C Programming Variables.
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Chapter 2 - Introduction to C Programming
Week 2 Variables, flow control and the Debugger
Introduction to C Programming
Chapter 2 - Introduction to C Programming
Primitive Types and Expressions
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
Data Types and Arithmetic in C
Presentation transcript:

Programming 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, ,... double – double precision real number (8 bytes) char int float double

Unsigned Vs. Signed integer types can be signed or unsigned unsigned int ui; unsigned char uc; char  signed: -128 to +127  unsigned: 0 to +255 int  signed: −2,147,483,648 to +2,147,483,647  unsigned: 0 to +4,294,967,295

/* Convert cm to inches */ #include 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 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 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 USD into NIS. The exchange rate is 4 NIS for USD

Solution #include void main() { double usd = , 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 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 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 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 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 letter + 1 cm / 2.54 a = b  The value of assignment expression is the assigned (right hand side) value

cm * 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) = 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 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 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 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  unsigned Int ( different values)  signed  unsigned

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); }

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 void main() { int iA = 1000, iB = , iC = , iD = ; 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); }