1 / 45

Input, Output and Variables

This tutorial introduces basic output using printf() and the concept of variables in C programming. It covers integer variables, scanf() input, basic arithmetic, float variables, operator precedence, and casting.

Download Presentation

Input, Output and Variables

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Input, Output and Variables Ethan Cerami New York University Ethan Cerami, NYU

  2. This Week • Tuesday: • Basic Output: printf() • Introduction to Variables • Integer variables • Basic Input: scanf() • Thursday: • Basic Arithmetic • Float variables • Operator Precedence • Promotion/Casting Ethan Cerami, NYU

  3. Basic Output: printf () • printf () stands for “print formatted text.” • Prints any String of text directly to the computer screen. • String: Any text appearing between quotes, e.g. “hello” Ethan Cerami, NYU

  4. Sample Program /* Printing multiple lines with a single printf */ #include <stdio.h> main() { printf("Welcome\nto\nC!\n"); /* Wait for user */ getchar(); } Note the \n escape sequence creates a new line character. Welcome to C! Ethan Cerami, NYU

  5. Escape Characters • The \ character indicates an Escape sequence. • Examples \n New Line Character \t Tab Character \a The Alarm\Bell Character \\ Outputs a single \ Character \" Outputs a single " Character Ethan Cerami, NYU

  6. Outputting a Quote Character • Quotes designate the beginning and end of a String. Hence, if you try to output a quote, the compiler gets confused. • For example: printf ("He said, "Hello""); will result in a compilation error. • To do it correctly, you must escape the “ character. For example: printf ("He said, \“Hello\""); Ethan Cerami, NYU

  7. Variables • Variable: a small piece or “chunk” of data. • Variables enable one to temporarily store data within a program, and are therefore very useful. Note: variables are not persistent. When you exit your program, the data is deleted. To create persistent data, you must store it to a file system. Ethan Cerami, NYU

  8. Data Types • Every variable must have two things: a data type and a name. • Data Type: defines the kind of data the variable can hold. • For example, can this variable hold numbers? can it hold text? • C supports several different data types. We are only going to look at one today. Ethan Cerami, NYU

  9. C’s Three Main Data Types • integers: the simplest data type in C. Used to hold whole numbers, e.g. 5, 25. • floats: Used to hold fractional or decimal values, e.g. 3.14, 10.25. • chars: Used to hold individual characters, e.g. “c”, “e” • We will explore each one in detail in the next week. Ethan Cerami, NYU

  10. Bucket Analogy • It is useful to think of a variable as a bucket of data. • The bucket has a unique name, and can only hold certain kinds of data. balance is a variable containing the value 200, and can contain only whole numbers. 200 balance Ethan Cerami, NYU

  11. Variable Declaration • Before you use a variable, you must declare it. (Not all languages require this, but C certainly does.) • Examples: /* Creates an integer variable */ int number; /* Creates a float variable */ float price; /* Creates a character variable */ char letter; Ethan Cerami, NYU

  12. Example 1: Basic Arithmetic #include <stdio.h> main () { int x, y, z; x = 5; y = 10; z = x + y; printf ("x: %d\n", x); printf ("y: %d\n", y); printf ("z: %d\n", z); } Variable Declaration Variable Names Data Type Assignment Statements Ethan Cerami, NYU

  13. Assignment Statements • Assignments statements enable one to initialize variables or perform basic arithmetic. x = 5; y = 10; z = x + y; • Here, we simply initialize x and y and store their sum within the variable z. Note: If you forget to initialize your variables, the variable may contain any value. This is referred to as a garbage value. Hence, always initialize your variables! Ethan Cerami, NYU

  14. Printing Variables • To print a variable, use the printf() statement: printf ("x: %d\n", x); Format Specifier: Indicates the type of data to print. In this case, %d indicates whole digits or integer values. Name of variable to print. In this case, we print the variable x. Ethan Cerami, NYU

  15. Rules for Naming Variables • Variable Names: • Can contain letters, digits, or underscores _ • Cannot begin with a digit. • Examples of Valid Variable names • int variable1, variable_2; • Examples of Invalid Variable names: • int 1variable, variable#1 • Remember, C is case sensitive, e.g. variable1  VARIABLE1 Ethan Cerami, NYU

  16. Basic Input: scanf() • Input: any user supplied data. • Keyboard input, mouse input. • scanf (): read in keyboard input. Ethan Cerami, NYU

  17. Example 2: Using scanf() /* Addition program */ #include <stdio.h> #include <conio.h> main() { int integer1, integer2, sum; /* declaration */ printf("Enter first integer\n"); /* prompt */ scanf("%d", &integer1); /* read an integer */ printf("Enter second integer\n"); /* prompt */ scanf("%d", &integer2); /* read an integer */ sum = integer1 + integer2; /* assignment of sum */ printf("Sum is %d\n", sum); /* print sum */ /* Wait for user to Any Key */ getch(); return 0; /* indicate that program ended successfully */ } Ethan Cerami, NYU

  18. Quick Review { int integer1, integer2, sum; /* declaration */ printf("Enter first integer\n"); /* prompt */ scanf("%d", &integer1); /* read an integer */ printf("Enter second integer\n"); /* prompt */ scanf("%d", &integer2); /* read an integer */ sum = integer1 + integer2; /* assignment of sum */ printf("Sum is %d\n", sum); /* print sum */ /* Addition program */ #include <stdio.h> #include <conio.h> main() Ethan Cerami, NYU

  19. Quick Review: Comments /* Addition program */ Comments. Never underestimate the power of commenting! Your programs should always be well commented, and should include the following: • program description • author of program • date program was created Ethan Cerami, NYU

  20. #include <conio.h> • As mentioned last time, the #include statement includes another library so that you can reuse its functionality. • conio.h: Console Input/Output • Represents another library that deals specifically with keyboard input and output. • Contains the getch() method which we will soon explore. Ethan Cerami, NYU

  21. Quick Review: main () • You always need a main () function. • Program execution will always begin at main(). • Note, however, that the main() function can exist anywhere within your program, even at the very bottom. Ethan Cerami, NYU

  22. Variable Declaration /* Addition program */ #include <stdio.h> #include <conio.h> main() { printf("Enter first integer\n"); /* prompt */ scanf("%d", &integer1); /* read an integer */ printf("Enter second integer\n"); /* prompt */ scanf("%d", &integer2); /* read an integer */ sum = integer1 + integer2; /* assignment of sum */ printf("Sum is %d\n", sum); /* print sum */ int integer1, integer2, sum; /* declaration */ Ethan Cerami, NYU

  23. Variable Declaration • Variable declaration: int integer1, integer2, sum; • This statements creates three variables, integer1, integer2, and sum. All are set to the integer data type. • integer1, integer2, and sum can therefore only hold whole numbers. Note: Variable declaration must occur at the very top of your function. (you cannot stick it somewhere in the middle of your function!) Ethan Cerami, NYU

  24. Basic Input: scanf () /* Addition program */ #include <stdio.h> #include <conio.h> main() { int integer1, integer2, sum; /* declaration */ printf("Enter second integer\n"); /* prompt */ scanf("%d", &integer2); /* read an integer */ sum = integer1 + integer2; /* assignment of sum */ printf("Enter first integer\n"); /* prompt */ scanf("%d", &integer1); /* read an integer */ Ethan Cerami, NYU

  25. Basic Input: scanf() • If you want to read in data from the user, we use the scanf() function. • scanf() reads in data from the keyboard, and stores it in a specific variable. • Once stored in a variable, you can manipulate the data any way you want. • Very useful for creating interactive applications which require input from the user. Ethan Cerami, NYU

  26. scanf() Syntax • scanf has a very specific syntax, consisting of three parts: scanf("%d", &integer1); Format specifier: indicates the kind of data to expect. In this case, %d stands for digits, e.g. whole numbers or integers. Note the & character. Without it, your computer may crash! (We will return to the exact meaning of the & character after the midterm.) Indicates where to store the data. In this case, if the user types 5, the number 5 is stored in integer1. Ethan Cerami, NYU

  27. Two more tid-bits /* Addition program */ #include <stdio.h> #include <conio.h> main() { int integer1, integer2, sum; /* declaration */ printf("Enter first integer\n"); /* prompt */ scanf("%d", &integer1); /* read an integer */ printf("Enter second integer\n"); /* prompt */ scanf("%d", &integer2); /* read an integer */ sum = integer1 + integer2; /* assignment of sum */ printf("Sum is %d\n", sum); /* print sum */ } /* Wait for user to Any Key */ getch(); return 0; /* indicate that program ended successfully */ Ethan Cerami, NYU

  28. getch() Statement • getchar() • Contained in stdio.h • Waits for the user to Press ENTER • getch() • Contained in conio.h • Waits for the user to Press any key • Feel free to use either one. Ethan Cerami, NYU

  29. Inter-Program Communication • When you run your program in Windows, your program runs “on top” of Windows. • For example: Hello World Program Windows Operating System Ethan Cerami, NYU

  30. Communicating with Windows • At the end of your program, you can tell Windows whether your program was successful or not. • You communicate with windows via a return statement. • Generally, return 0 indicates that everything ran just fine. -1 indicates that an error occurred. • You will notice that all programs in the Text Book include a return statement. But, the programs in the packet may or may not (for this course, either option is fine, but some compilers may require a return statement.) Ethan Cerami, NYU

  31. Return 0 • return 0 indicates that your program ended successfully. Hello World Program “Hello Windows, everything ran just fine” Windows Operating System Ethan Cerami, NYU

  32. Basic Mathematical Operators • + - Addition / Subtraction • * Multiplication • / Integer Division • % Modulus Division Ethan Cerami, NYU

  33. Integer Division - The Problem • Suppose you have the following code: • Using a calculator, the answer is 1.75. • But x can only hold integer values. 1.75 is clearly not an integer value. int x; x = 7 / 4; Ethan Cerami, NYU

  34. Integer Division - Solution • To understand the solution, you need to remember your 3rd Grade Math (really.) • 7/4 = 1 (Integer Division) • 7%4 = 3 (Modulus Division) 1 The answer: 1 remainder 3 4 7 4 3 Ethan Cerami, NYU

  35. Example: Integer Division /* Integer and Modulus Division */ #include <stdio.h> main () { int x = 5, y =10; printf ("5/10: %d\n", x/y); printf ("5%%10: %d\n", x%y); getchar(); } 5/10: 0 5%10: 5 Ethan Cerami, NYU

  36. Modulus Division (cont.) • Second Example: • No matter what, you answers must be integers. 0 5/10 = 0 5%10 = 5 10 5 0 5 Ethan Cerami, NYU

  37. Operator Precedence • Here’s another problem. What’s the answer to this? x = 7 + 3 * 6; • Two Options (depending on the order of operations): • Perform addition first: 7 + 3 = 10  10 * 6 = 60 • Perform multiplication first: 3*6 =18  7+18 = 25 • Which option is correct? Clearly, we cannot have this kind of ambiguity. Ethan Cerami, NYU

  38. Operator Precedence • Rules for evaluating mathematical expressions. • Every programming language has similar rules. • From left to right: • Parentheses are always evaluated first. • Multiplication, division and modulus are evaluated next. • Addition and subtraction are evaluated last. Ethan Cerami, NYU

  39. Operator Precedence • Hence, option #2 is always correct: x = 7 + 3 * 6; Evaluates to x = 7 + 18 = 25 Ethan Cerami, NYU

  40. Float Data Types • Float Data Type: Data type that can hold numbers with decimal values, e.g. 5.14, 3.14. • Floats can be used to represent many values: • money • long distances • weight, etc. Ethan Cerami, NYU

  41. Float Example (Program 2.2) /* Float Example Program */ #include <stdio.h> main () { float var1, var2, var3, sum; var1 = 87.25; var2 = 92.50; var3 = 96.75; sum = var1 + var2 + var3; printf ("Sum: %.2f", sum); getchar(); } %f: indicates floating values %.2f displays a floating point value with 2 decimal points. Output: Sum: 276.50 Ethan Cerami, NYU

  42. Challenge: Find an Average • Suppose you want to determine a student’s average. int num = 4; float avg = 90+92+95+100/num; • Problem #1: Operator Precedence • By rules of operator precedence, 100/4 is evaluated first. Hence, avg is set to: 302. • To solve this problem, use (): float avg = (90+92+95+100)/num; Ethan Cerami, NYU

  43. Finding an Average • Problem #2: • 90, 92, 95, 100 and 4 are all integers. Hence, this is integer division. • Integer division can result in data truncation (or loss of data.) • Hence, avg is set to: 94, but the students real average is 94.25. • There are actually three ways to solve this problem. Ethan Cerami, NYU

  44. Rules of Promotion • Promotion: when mixing ints and floats, everything is promoted to floats. • In our average example, there are three ways to force promotion, and get the right answer of 94.25: 1. change num to a float: float num = 4.0; float avg = 90+92+95+100/num; Ethan Cerami, NYU

  45. Rules of Promotion 2. Use a Cast Operator int num = 4; float avg = 90+92+95+100/(float)num; In this case, num is explicitly cast to a float. And, because we have one float, everything else is promoted. Note that you can also use the (int) cast to cast a float to an integer. 3. Divide by 4.0 float avg = 90+92+95+100 / 4.0; Ethan Cerami, NYU

More Related