Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7
Using Variables in Algorithms
An Introduction to Variables and Data
Types in Programming What is a Variable? • A variable is used for storing data. Programmers give specific names to variables. Once a variable is created, it can be used throughout the program. The data in the variable can change through the program.
• For example, in a video game, a variable is
used to store the number of lives you have. Each time your character dies, the number of lives decreases by 1. When the number of Data Types • In programming, a data type is the kind of value that a variable can hold:
• - Integer: Whole numbers (e.g., 3, 5, 10)
• - String: Alphanumeric text like a word or phrase (e.g., 'I am excited', 'Bob123') • - Character: Single letters, digits, or symbols (e.g., 'a', '5', '$') Algorithm 1: Creating Variables • In Algorithm 1, three variables are created: • -X • -Y • - answer
• All three variables are created to store an
integer. Algorithm 2: Using Variables • 1. The user inputs the first number. It is stored in variable X. • 2. The user inputs the second number. It is stored in variable Y. • 3. Decision: • - If X equals Y: Subtract Y from X and store the result in 'answer'. • - Otherwise: Add X and Y and store the result in 'answer'. • 4. Display the value stored in 'answer'. Algorithm 3: Using Variables in a Decision • 1. Ask the user to guess a number between 1 and 10. • 2. The number is stored in variable X. • 3. Decision: • - If X equals 7: Display 'You guessed the right number!' • - Otherwise: Display 'Try again!' Key Vocabulary • - Variable: A named container for data in a program. • - Integer: Whole number values. • - String: A sequence of characters or text. • - Character: A single letter, digit, or symbol.