Physics 306 Computing Lab 1: Hello, World!

Similar documents
ENCM 339 Fall 2017: Editing and Running Programs in the Lab

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

Informatica e Sistemi in Tempo Reale

Fundamentals of Programming

3/13/2012. ESc101: Introduction to Computers and Programming Languages

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lab 1 Introduction to UNIX and C

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

Getting started with UNIX/Linux for G51PRG and G51CSA

Lab 1 Introduction to UNIX and C

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Saint Louis University. Intro to Linux and C. CSCI 2400/ ECE 3217: Computer Architecture. Instructors: David Ferry

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

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

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

COMP s1 Lecture 1

CENG393 Computer Networks Labwork 1

Chapter 2. Editing And Compiling

Notes By: Shailesh Bdr. Pandey, TA, Computer Engineering Department, Nepal Engineering College

Intermediate Programming, Spring Misha Kazhdan

Hacking C Code - Local Machine

AN INTRODUCTION PROGRAMMING. Simon Long

Introduction to Linux

Using the Zoo Workstations

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

1. The Mac Environment in Sierra Hall 1242

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

1. The Mac Environment in SIE 1222

last time in cs recitations. computer commands. today s topics.

CSC111 Computer Science II

Introduction: The Unix shell and C programming

Computer Programming: Skills & Concepts (CP) Variables and ints

Practical Session 0 Introduction to Linux

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Week 1: Introduction to R, part 1

APPM 2460 Matlab Basics

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

printf( Please enter another number: ); scanf( %d, &num2);

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

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

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

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

EL2310 Scientific Programming

15-122: Principles of Imperative Computation

If Statements, For Loops, Functions

CSC209. Software Tools and Systems Programming.

Lab: Supplying Inputs to Programs

Arithmetic Expressions in C

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

The Very Basics of the R Interpreter

EXCEL BASICS: MICROSOFT OFFICE 2007

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

Part II Composition of Functions

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

Parallel Programming Pre-Assignment. Setting up the Software Environment

CSC105, Introduction to Computer Science I. Introduction. Perl Directions NOTE : It is also a good idea to

Spectroscopic Analysis: Peak Detector

Intro to HPC Exercise

ESSENTIALS LEARN CODE WITH PROGRAM WITH THE WORLD S MOST POPULAR LANGUAGE ON. Raspberry Pi YOUR. Written by Simon Long

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia

Preprocessor Directives

Science One CS : Getting Started

Linux Systems Administration Shell Scripting Basics. Mike Jager Network Startup Resource Center

3. Simple Types, Variables, and Constants

EL2310 Scientific Programming

CpSc 1111 Lab 4 Formatting and Flow Control

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

The C language. Introductory course #1

CS50 Supersection (for those less comfortable)

CS451 - Assignment 8 Faster Naive Bayes? Say it ain t so...

Computers and Computation. The Modern Computer. The Operating System. The Operating System

Using GitHub to Share with SparkFun a

C Introduction Lesson Outline

Introduction to C Programming

CSC209. Software Tools and Systems Programming.

Lesson 1: Writing Your First JavaScript

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Introduction to Programming

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

notice the '' you must have those around character values, they are not needed for integers or decimals.

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

CS 231 Data Structures and Algorithms, Fall 2016

Chapter 2. Basics of Program Writing

27-Sep CSCI 2132 Software Development Lab 4: Exploring bash and C Compilation. Faculty of Computer Science, Dalhousie University

How to approach a computational problem

PRINCIPLES OF OPERATING SYSTEMS

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

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

ENCM 335 Fall 2018 Lab 2 for the Week of September 24

ECGR 4101/5101, Fall 2016: Lab 1 First Embedded Systems Project Learning Objectives:

Math 25 and Maple 3 + 4;

Teacher Activity: page 1/9 Mathematical Expressions in Microsoft Word

Intro. Scheme Basics. scm> 5 5. scm>

Software Lesson 1 Outline

Chapter 4. Unix Tutorial. Unix Shell

NCMail: Microsoft Outlook User s Guide

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #03 The Programming Cycle

EXCEL BASICS: MICROSOFT OFFICE 2010

Transcription:

1. Introduction Physics 306 Computing Lab 1: Hello, World! In today s lab, you will learn how to write simple programs, to compile them, and to run them. You will learn about input and output, variables, and loops. If you have done computing before, the first couple weeks of the computer lab may be very simple for you. That s fine. In each of sections 3 through 7 below, you will work with variants of a single computer program. As you work each section, print out enough from the program (such as its original code and a copy of its output) to prove that you have done it, or talk to your instructor while in the lab so that he can mark down the fact that you did that part of the experiment. This week, work as far as you can in the writeup in two hours. If you get through it all in less than two hours, you can leave early. We will adjust the content of next week s lab depending on how far people get this week. Working computers can be both incredibly gratifying and incredibly frustrating. The main source of frustration is that a minor error (for example, a missing semi-colon) can cause a program to utterly fail to work, and the computer system will often not give you a clear explanation as to why it is failing. If you find yourself stuck on a point, get help talk to your friends in the class or to your instructor. 2. Setting up the computer We want to jump right in and start writing programs. But first, you need to have a place on the computer to store your work. Check your machine s desktop. If there is not a Physics306 folder, please make one. Make sure there are no spaces in the folder name (i.e., no space between Physics and 306. ) Within the Physics306 folder, make a folder for yourself (e.g., use the name part of your Bryn Mawr or Haverford E-mail address.) Again, make sure there are no spaces in the folder name. To make new folders in the MacOS finder, use shift- -N. 1

3. Hello, world! Start Microsoft Word. Create a new document. Select Tools AutoCorrect..., click on AutoCorrect, and de-select everything. This prevents Word from automatically capitalizing things as you type. Enter the following. It is important to get everything exactly right. #include <stdio.h> int main() { printf("hello, world!\n"); } Select File Save As..., and save the file using name hello.c and format Text Only with Line Breaks. When you specify the format (in the pull-down menu), Word might try to give the file name a.txt extension. Change it back to.c if necessary, so that the file name is hello.c. Save the file in the folder with your name. If Word is not displaying directories, click on the little arrow to the right of the file name in the Save as window, and a directory display will open up. After you click save, Word will give you a warning that formatting information will be lost. Click yes to continue saving the document. Next, start the Terminal program by clicking on the Terminal icon on the dock. It looks like this:. If you don t see this icon, you can run the Terminal program from the Finder. Type shift- -U to go to the Utilities folder, and click on Terminal there. (Note: if you are familiar with the X11 window system, feel free to use xterms with X11 instead of the MacOS Terminal program.) When the terminal pops up, it will display a message similar to this: mathphysics-dhcp174:~/ student$ This is called the prompt. The computer is waiting for you to type something. The prompt lists the computer name ( mathphysics-dhcp174 in this example). Although not yet obvious, the prompt also tells you which folder you are working in. Type cd Desktop/Physics306/myname, replacing myname with the name of the folder you created earlier. Whenever you type something like this, press return when you are done. You are now working within the folder you made on the desktop. We will usually use the word directory instead of folder, but they mean the same thing. Notice that the prompt has changed to reflect the new directory name. You can type pwd to see which directory you are working in. Type ls to list the files in the directory. There should be just a single file, hello.c, which you created a few minutes ago. 2

You are now ready to compile and run this program. Type gcc -o hello hello.c. If the computer prints error messages, then there is something wrong with your hello.c program. Double-check that it looks exactly like the listing above. If you can t find any problems, but you continue to get error messages, talk to your instructor. Type ls again. Now, in addition to hello.c, there is a second file, called hello. This file contains the actual computer instructions needed to execute the commands listed in hello.c. In other words, it is a computer program which you can run. Type./hello. (Notice the sequence: period, slash, hello.) The hello program will run and print out a message. If it does not do so, double check your program again. If you can t get it to work, ask for help. There are a number of lines in your short hello.c program which probably just look like gibberish, but it should be clear which part of the program is responsible for writing out the hello message. We ll talk about the rest of the gibberish on some other day. Modify the code to print out your name or the name of your pet fish or the name of your favorite math theorem. What s that \n thing in the program? Try leaving out the \n. What happens? What happens if you put an extra \n into the program, for example, hello\n, world!\n? Try it! There are other things you might try: \t, \b, \a. Instead of having the program s output be written to the terminal screen, you can have it saved in a file. Run./hello > a.txt. Nothing is displayed on the screen when you run this. Type ls and you will see that there is a new file, a.txt, in the directory. You could look at this file with a standard text editor like Word or TextEdit. Or, you can write it to the screen by typing cat a.txt. In fact, you can write any file to the screen. Try typing cat hello.c. To print any of these files, you can open them in Word or TextEdit and use the print ( -P) command. Or, in terminal, you can type, for example, lpr xyz.txt where xyz.txt is the name of the file. At the moment, it seems that the computers are set up to print to the printer in the computer lab, but sometimes they request the wrong paper tray. You may have to walk over to the printer and hit the checkmark button on the printer to get it to behave. 3

4. Arithmetic Time for another program. Use Word to enter the following. Give it a new name, such as multiply.c. If you would rather use a different editor (like MacOS s TextEdit, or the Unix editors vi or emacs), that s great. If you are going to do a lot of programming, you should learn to use vi or emacs. But please leave that for another day and get back to typing the following code into the computer. #include <stdio.h> int main() { int a, b, c; printf("type two numbers separated by a space:\n"); scanf("%d %d",&a,&b); c = a * b; } printf("the product of %d and %d is %d\n",a,b,c); Compile this and run it in the same way as you ran the hello program. When you type gcc -o multiply multiply.c, what you are doing is telling the computer to compile your program (i.e., to turn it into something the computer can run). The original file, that you wrote, is called the source code, and the runnable program produced by the compiler is called the executable or the binary file. The gcc command tells the compiler to put the executable into a new file called multiply. You can call the executable anything you wish; just change what is after the -o in the gcc command. You can also leave out the -o part entirely, and just write gcc multiply.c. What is the executable called in this case? Try it and see. By the way, the computer language you are using is called C. Our use of C is a somewhat arbitrary choice. Many computer languages would be capable of doing the work we want to do. What you learn using C you can easily apply to other languages. The C complier is, confusingly, called gcc. In MacOS (and many other systems), you can type cc instead of gcc, and the computer will run the same compiler. Different computers have different C compilers. The gcc compiler is very commonly used on MacOS, Linux, and other Unix-based computer systems. When you put.c at the end of a file name, that tells the compiler that it is a C program. Getting back to your program, once you ve convinced yourself that it works, change it to divide a by b instead of multiplying them together. Compile the program and try it out. What happens if you try to divide 10 by 3? Hmmm, looks like the program 4

only understands integers. Could that word int in the program have something to do with this? Try changing int a, b, c; to float a, b, c;, and change the characters %d to %f (in four separate places ). What happens? The process of defining a variable to be int or float or something else is called declaring the variable. Every variable you use must be declared before you use it. By now you will have noticed that every statement (that is, every command within a program) ends with a semi-colon. The only exception is the first line, which starts with a pound sign, #. The use of semi-colons to separate one statement from the next is a feature of many (but by no means all) computer languages. Ends of lines have no significance in C. You can put a single statement on multiple lines, for example: c = a * b; And you can put multiple commands on a single line: printf("type two numbers:\n"); scanf("%d %d",&a,&b); c=a*b; What s going on in the printf and scanf lines? Technically, these are both C functions. Among other things, this means that, in a program, they are always followed by something in parenthesis. In fact, it is common to call these functions printf() and scanf(). The parentheses are included in the names, even in casual conversation. (How do you pronounce punctuation marks? Look up Victor Borge phonetic punctuation on YouTube. But wait until after lab to do that.) So, what does printf() do? As you have gathered by now, printf() prints things out, that is, it writes them to the screen. Writing a bunch of letters to the screen is straightforward: printf("salut le Monde!\n"); The thing inside the quotation marks is called a format string. If you want to print an integer variable, put the characters %d in the format string, and list the variable name after the string: int a; a = 7; printf("my favorite number is %d.\n", a); If you want to print out more than one variable, put more than one %d in the format string: int a, b; a = 7; b = 3; printf("my favorite number is %d, but I also like %d.\n", a, b); You can print the same variable more than once: 5

int a; a = 7; printf("i love %d! %d is my favorite! %d! %d! %d!\n",a,a,a,a,a); To print a floating point number, use %f instead of %d : float a; a = 7.543; printf("personally, I prefer %f. I love decimals.\n",a); Printing both integers and floats is no problem: printf() function call: float a; int b; a = 7.543; b = 7; printf("the best is %f, but %d is also pretty good.\n",a,b); There are many, many other features of printf(). We ll talk about the some other time. The scanf() function is more-or-less the opposite of the printf() function. It takes one line of input from the keyboard and stores whatever is typed there into one or more variables: int a, b; float c; printf("type two integers separated by a space:\n"); scanf("%d %d",&a,&b); printf("now type in a floating point number:\n"); scanf("%f",&c); Note the peculiarity that you need to put & before the variable name in a scanf() function call. We ll talk about why that is at some later date. Are you tired of typing./ every time you run a command? In your terminal, type the following: echo $PATH. If you run a program like multiply without specifying which directory it is in, the computer will search all the directories listed in $PATH. The directory in which you are currently working is not on that list, so you have to specify it manually. That s what the./ is all about. The period means the current working directory. To add it to the path, do the following: PATH=.:$PATH. Now you can simply type multiply without the period and slash. You ll probably want to make this change to $PATH every time you start a terminal. 6

5. Going for a loop Now try this: #include <stdio.h> int main() { int i; float pi; float a; pi = 3.14159265; } for (i=0; i<10; i++) { a = i*pi; printf ("%d times pi is approximately %f\n",i,a); } Compile and run this program. The program executes the same statements ten times, each time with a different value of i, starting at 0 and going as high as 9. This sort of thing is called a loop. In this program, i starts off at 0 (i=0), it is incremented by one each time the loop is run (i++), and it runs as long as i is less than 10 (i<10). The ten passes through the loop are called iterations of the loop, and i is called the loop index. The code that is run ten times is enclosed by brackets after the for command. 6. A variable-length loop Modify the above program so that it asks the user how many iterations he or she wants, and sets the upper limit of i to that value. You will need to add a new variable to the program to do this. If have trouble figuring out how to do this, ask someone for help. If you do something wrong and your program looks like it will run forever, type ctrl-c to stop it. 7. Factorial; how big can an integer be? You know that the a factorial, often written a!, is the product of the integers from 1 thorough a. So, for instance, 5! = 1 2 3 4 5 = 120. 7

Write a program which uses a loop to calculate the factorial of some number (we ll call it n). Do this by declaring a variable n, initially setting it to 1, and then multiplying it by the loop index in each iteration through the loop. Do everything with integers. Once you ve gotten that working, see how high a number you can calculate before problems start arising. There is a maximum value which integer numbers in this implementation of C are allowed to have. If you try to make a larger integer, strange things can happen. Explore! That s enough for today!.... Note: The idea of starting programming by writing a Hello, world program was popularized in the classic text The C Programming Language by Brian Kerninghan and Dennis Richie. It has become the de facto standard first program to write when learning any computer language. For more about this program, check out the Hello world program entry in Wikipedia. 8