CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

Similar documents
CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection

CpSc 1111 Lab 4 Formatting and Flow Control

CpSc 1111 Lab 5 Formatting and Flow Control

CpSc 1111 Lab 9 2-D Arrays

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Variables and Operators 2/20/01 Lecture #

Programming for Engineers Introduction to C

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Lecture 3 Tao Wang 1

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

CpSc 1111 Lab 1 Introduction to Unix Systems, Editors, and C

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CpSc 101, Fall 2015 Lab7: Image File Creation

CpSc 1010, Fall 2014 Lab 10: Command-Line Parameters (Week of 10/27/2014)

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

COMP s1 Lecture 1

2. Numbers In, Numbers Out

Lecture 2: C Programming Basic

Basics of Programming

C: How to Program. Week /Mar/05

Reserved Words and Identifiers

C Programming

Full file at

CS 211 Programming Practicum Fall 2018

2. Numbers In, Numbers Out

Creating a C++ Program

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

CMSC 104 -Lecture 6 John Y. Park, adapted by C Grasso

Lecture 3. More About C

Fundamental of Programming (C)

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Full file at C How to Program, 6/e Multiple Choice Test Bank

Introduction: The Unix shell and C programming

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Chapter 2 - Introduction to C Programming

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Our Strategy for Learning Fortran 90

Midterms Save the Dates!

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

LECTURE 3 C++ Basics Part 2

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

C Program Structures

Chapter 1 & 2 Introduction to C Language

Topic 6: A Quick Intro To C

Chapter 7. Basic Types

Lecture 8: Structs & File I/O

Physics 306 Computing Lab 1: Hello, World!

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

Use of scanf. scanf("%d", &number);

Fundamentals of Programming Session 4

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Computer Programming CS F111

ET156 Introduction to C Programming

Quiz1 Fall 2007 October 2 nd, UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 1 Solution. Examiner:Ritu Chaturvedi Dated :October 2nd, 2007.

CSCI 2132 Software Development. Lecture 8: Introduction to C

Bits, Words, and Integers

Informatica e Sistemi in Tempo Reale

Fundamentals of Programming

Input / Output Functions

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

Some Computer Preliminaries

CS Programming In C

3. Simple Types, Variables, and Constants

Lecture 2 Tao Wang 1

Visual C# Instructor s Manual Table of Contents

Lectures 5-6: Introduction to C

Reviewing all Topics this term

ANSI C Programming Simple Programs

Copy: IF THE PROGRAM or OUTPUT is Copied, then both will have grade zero.

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Other Loop Options EXAMPLE

Computer System and programming in C

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Operators and Expressions:

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Basic Assignment and Arithmetic Operators

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Arithmetic type issues

Lectures 5-6: Introduction to C

Today s Learning Objectives

Programming in C++ 5. Integral data types

CS4023 Week06 Lab Exercise

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

Program Organization and Comments

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Transcription:

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection Overview By the end of the lab, you will be able to: declare variables perform basic arithmetic operations on integer variables use fprintf to print out integer values use redirection to send output to a file use the Unix command cat to echo the contents of a file to the screen Background Information If you remember from last week s lab, you were given a program with errors that you had to correct. The program contained variables as well as printf() and scanf() function calls. This week, you will be writing a program declaring variables, initializing some and assigning results of mathematical expressions to others. You will see some of the precedence rules with the mathematical expressions. Some background information of the concepts from this lab are shown below, some repeated from last week and some new. Variables As you learned last week in lab and lecture, a variable is a symbolic name for a memory location where values are stored. We, as programmers, can access the memory locations needed in our programs much easier by name rather than by the actual address of the memory location. In the C language, every variable must be declared. To declare a variable, its type must be indicated: int, float, _Bool, double, char, etc. It is preferable to use meaningful variable names, which improves program readability. Integer Variables You also learned last week that the int type is used for integral numbers, or integers numbers without decimal places. Don t forget that usually, variables are all declared at the beginning of a function. The following are examples of int variable declarations: int sidelength; int area; Variables that have not been given a value at any point contain garbage they will have the value of whatever had been in that memory location the last time it was used. In C, you must never assume that variables have an initial value of 0 upon declaration. You can initialize a variable upon declaration (such as sidelength below), or assign it a value at some point later in the program (area below). int main(void) { int sidelength = 3; int area; area = sidelength * sidelength; printf( The area of a square with side length of %i, sidelength); printf( is: %i \n, area); } return 0; 1

There are also optional modifiers that can be used with integers: long, long long, short, unsigned, and signed. An integer, by default, is a signed value. For an integer to be a signed value, you can declare it as signed int or just simply as int. The format for declaring an integer variable is the following: <optional modifier> <type_name> <variable_name> The number of bits that a data type uses depends on the system. For example, integers are guaranteed to be at least 32 bits big, but sometimes may be 64 bits big. On our system, they take up 32 bits. Type short int long int long long int Size 16 bits (guaranteed to be at least 16 bits) 32 bits (guaranteed to be at least 32 bits; sometimes they are 64 bits) 64 bits 64 bits The following are examples of different integer variable declarations: int value1; // signed value by default // at 32 bits big, the range is from: // -2,147,483,648 to +2,147,482,647 unsigned int value2; // at 32 bits big, the range is from: // 0 to +4,294,967,295 unsigned short has16bits; // guaranteed to be at least 16 bits // (it is 16 bits on our system) long int the_sum; // 64 bits Basic math operations can be performed on integer variables. The following table shows a few examples. Example Description y = 3; x = 5; assigns the value 3 to y and 5 to x z = x + y; assigns the sum of x and y to z z = x + 5; assigns the sum of x and 5 to z x += 4; same as x = x + 4; adds 4 to x a = x - y; assigns the difference of x and y to a z -= 1; same as z = z 1; subtracts 1 from z z *= 2; same as z = z * 2; multiplies z by 2 z = x * y; assigns the product of x and y to z z = x / y; assigns the integer dividend of x and y to z * Be CAREFUL with integer division! 2

Performing Operations on Variables Expressions consist of a collection of operators, variables, and constants. Operators can be grouped into several classes. Assignment: = assigns the value of the expression on the right side to the variable on the left side. Arithmetic: + - * / add, subtract, multiply, divide Comparative: ==!= < <= > >= equal to, not equal to, less than, less than or equal to, greater than, greater than or equal to Statements are expressions followed by a semicolon. The most commonly encountered statements are: Assignment statement: x = y + 2; Function invocation: howmany = scanf("%d", &v1); howmany = fscanf(stdin, "%d", &v1); printf("hello World!\n"); // fscanf() discussed further down Expressions Are Built By Combining Operators and Operands Suppose the variable v1 currently has value 4 and v2 has value 3. What is the value of the following expression? v1 + 5 * v2 / 3 * v1 The C compiler has a set of immutable rules for evaluating such expressions. The rules are called precedence (e.g. multiply and divide are done before add and subtract) and associativity (e.g. a collection of multiply and divides is evaluated left to right so 42 / 6 * 7 = 49 and NOT 1), but they are hard to remember. We can ensure that the compiler does what we want by building our expressions from parenthesized sub-expressions. Such expressions are always evaluated innermost parentheses first. All of these expressions have different values. What values will each of these expressions have? v1 + ((5 * v2) / (3 * v1)) v1 + (5 * (v2 / 3)) * v1 ((v1 + 5) * v2) / (3 * v1) fprintf() and fscanf() Last week, the lab write-up contained some background information about the 3 files that the C run-time system automatically opens up when a program is run. Do you remember what they are? You already know that the printf() function prints to standard output (usually the screen), and the scanf()function gets input from standard input (usually the keyboard). 3

The fprintf() and fscanf()functions can be used as well. These are described below. fprintf() The fprintf() function is similar to the printf() function except that fprintf() has an additional argument as the first argument which specifies where the output will be sent to. If sending output to the screen, the following two statements are essentially the same in that they will both send the same message to the terminal window: printf( I love programming!\n ); fprintf(stdout, I love programming!\n ); But, later in the semester, you will see that you can send output to a file specified as the first argument in the fprintf() function. fscanf() The fscanf() function is similar to the scanf() function except that fscanf() has an additional argument as the first argument which specifies where the input is coming from. If the input is coming from the keyboard, the following two statements are essentially the same in that they will both be getting the input from the keyboard and putting it into the memory location (variable) that we are calling userinput: scanf( %d, &userinput); fscanf(stdin, %d, &userinput); But, later in the semester, you will see that you can get input from a file, specified as the first argument in the fscanf() function. More Fun With Unix In Unix, you can use a redirection operator to send output that would otherwise be going to the screen to a file. You can also use redirection for input as well. For this lab, you will use redirection for the output. For example, when executing a program, the > operator may be used on the command line to cause the standard output to be redirected to a file:./a.out > output.txt Unix also provides a command that will echo the contents of a file to the screen. To view the contents of a file, you could use your editor of choice to open the file, or you can use the following Unix command, which will show the contents to the screen without opening the file in the editor: cat output.txt Lab Assignment Reminder About Formatting and Comments The top of your file should have a header comment, which should contain: o Your name o Course and semester o Lab number o Brief description about what the program does o Any other helpful information that you think would be good to have. Variables should be declared at the top of the main function, and should have meaningful names. Always indent your code in a readable way. Some formatting examples may be found here: https://people.cs.clemson.edu/~chochri/assignments/formatting_examples.pdf Don t forget to use the Wall flag when compiling, 4 for example: gcc Wall lab3.c

Create a file called lab3.c. In it, provide a C program that will do the following: 1. Declare four integers variables intvar1, intvar2, intvar3, and intvar4. 2. Initialize intvar1 to the value 4; initialize intvar2 to the value 3. 3. Declare four more integer variables exp1, exp2, exp3, and exp4. 4. Assign the value of each of the following expressions to variables exp1 and exp2 respectively: exp1 = intvar1 + ( (5 * intvar2) / (3 * intvar1) ); exp2 = intvar1 + (5 * (intvar2 / 3)) * intvar1; 5. Using the fprintf() function, print to standard output the values of the variables (your output should look like the following): intvar1 = 4 and intvar2 = 3 exp1 = 5 exp2 = 24 6. Compile and run and verify that your output looks like the above lines. Notice that using the Wall option with gcc will produce warnings about unused variables at this point. You should always fix any warnings that you get when compiling because many times, they are indicative of a problem that does affect your program. 7. Assign to intvar3 to the value 5; assign to intvar4 the value 3. 8. Assign the value of each of the following expressions to variables exp3 and exp4 respectively: exp3 = (intvar4 % 2) / (intvar4 / intvar3); exp4 = 2 + intvar3 * intvar4; 9. Using the fprintf() function, print to standard output the values of the variables. The new portion of your output should look like the following: intvar3 = 5 and intvar4 = 3 exp3 = 1 exp4 = 17 10. Compile and run. What happens and why? Do you get the expected new output? Write your answer in the header comment portion of your lab3.c file. 11. Change the value of intvar3 to 3 and change the value of intvar4 to 5. Then compile and run and verify that your output looks like the lines above (except with 3 for intvar3 and 5 for intvar4). 12. Run the program again but redirect the output to a file. The > operator may be used on the command line to cause the standard output to be redirected to a file:./a.out > output.txt Type ls to ensure that you do have an output.txt file. To view the contents of the text file that contains the output (called output.txt above), you can use your editor of choice to open the file, or you can use the cat command to show the contents of the file to the screen without opening the file in the editor. Use the clear command first and then the cat command: clear cat output.txt 5

You should see the following output printed to the screen (which should be the contents of your output file): intvar1 = 4 and intvar2 = 3 exp1 = 5 exp2 = 24 intvar3 = 3 and intvar4 = 5 exp3 = 1 exp4 = 17 Turn In Work Show your ta that you completed the assignment. Then submit your lab3.c program and your output.txt file using the handin page: http://handin.cs.clemson.edu Grading Rubric For this lab, points will be based on the following: Functionality 75 (-5 if warnings when compile) Formatting 10 Inclusion of output.txt 5 Inclusion of answer in header comment 5 Use of fprintf() function 5 6