REU C Programming Tutorial: Part I FIRST PROGRAM

Similar documents
Computer Programming

2. Numbers In, Numbers Out

EL2310 Scientific Programming

2. Numbers In, Numbers Out

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

Physics REU Unix Tutorial

EL2310 Scientific Programming

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

1. The Mac Environment in Sierra Hall 1242

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

1. The Mac Environment in SIE 1222

Informatica e Sistemi in Tempo Reale

Fundamentals of Programming

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

27-Sep CSCI 2132 Software Development Lecture 10: Formatted Input and Output. Faculty of Computer Science, Dalhousie University. Lecture 10 p.

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

Learning to Program with Haiku

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

Topic 6: A Quick Intro To C

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

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Hacking C Code - Local Machine

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

COSC2031 Software Tools Introduction to C

Week 1, continued. This is CS50. Harvard University. Fall Cheng Gong

Python Programming Exercises 1

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

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

C: How to Program. Week /Mar/05

COMP s1 Lecture 1

Tutorial - Using existing plugins in GCC

Work relative to other classes

The C standard library

Our Strategy for Learning Fortran 90

Algorithms and Programming I. Lecture#12 Spring 2015

Arithmetic Expressions in C

ANSI C Programming Simple Programs

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

Physics 306 Computing Lab 1: Hello, World!

Chapter 2 - Introduction to C Programming

Introduction to UNIX. Logging in. Basic System Architecture 10/7/10. most systems have graphical login on Linux machines

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

Programming I Laboratory - lesson 01

Chapter 2, Part I Introduction to C Programming

Getting started with C++ (Part 2)

MITOCW watch?v=0jljzrnhwoi

Fundamentals of Programming Session 4

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Molecular Statistics Exercise 1. As was shown to you this morning, the interactive python shell can add, subtract, multiply and divide numbers.

Practical Session 0 Introduction to Linux

Introduction to C Language

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Introduction to C An overview of the programming language C, syntax, data types and input/output

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013

Programming for Engineers Introduction to C

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

EL2310 Scientific Programming

Introduction to Programming in Turing. Input, Output, and Variables

Formatted Input/Output

Program Organization and Comments

Introduction: The Unix shell and C programming

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

C for C++ Programmers

Beyond this course. Machine code. Readings: CP:AMA 2.1, 15.4

Introduction to Linux

CS240: Programming in C. Lecture 2: Overview

Starting. Read: Chapter 1, Appendix B from textbook.

UIC. C Programming Primer. Bharathidasan University

Week - 01 Lecture - 04 Downloading and installing Python

Basic UNIX Commands BASIC UNIX COMMANDS. 1. cat command. This command is used to create a file in unix. Syntax: $ cat filename

A Fast Review of C Essentials Part I

EC 413 Computer Organization

Course Outline Introduction to C-Programming

Computers in Engineering. Moving From Fortran to C Michael A. Hawker

Introduction to Programming, Aug-Dec 2008

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

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

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Chapter 2. Basics of Program Writing

Tutorial 1 C Tutorial: Pointers, Strings, Exec

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Getting started with UNIX/Linux for G51PRG and G51CSA

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

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

CS16 Exam #1 7/17/ Minutes 100 Points total

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

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

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Our First Programs. Programs. Hello World 10/7/2013

Introduction to Linux. Woo-Yeong Jeong Computer Systems Laboratory Sungkyunkwan University

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

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Transcription:

REU C Programming Tutorial: Part I What is C? C is a programming language. This means that it can be used to send the computer a set of instructions in a human-understandable way, which the computer interprets and carries out. The computer does this by first using a compiler to interpret the code you write into something the computer can understand. Then, you ask the computer to execute this compiled code. We'll do some examples below. Why? The short answer is that computers can carry out calculations much faster than humans. Here we'll work on some very simple tasks, but the computer can be given very complicated sets of instructions. These can be used to solve physical equations that model everything from quantum mechanical processes, to the motion of biological molecules, to weather patterns, the motions of tectonic plates, planetary motion, and the motion of galaxies (as just a few examples). As computing power increases, modeling is becoming more and more useful to a wider variety of researchers. FIRST PROGRAM First, make a directory in your home directory called cprogs. Remember, the command for this is mkdir. Then, change into this directory using the cd command. The first program always used in traditional tutorials is called the "Hello, world" program. You'll learn how to get a computer to print output to the screen in this program. The program code is in between the horizontal lines below. Use vi to open a file called hello.c by typing vi hello.c at the shell command line. Then, type i to go into insert mode within the vi editor. Now write it into the file, and then his the escape key, followed by :wq to save the file. You should now be back at the shell command line. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^hello.c^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /* This is a comment. Everything here is ignored when the C program is compiled. */ printf("hello, world!\n"); return 0; That is the whole program. The "include" statements tell the C compiler to look for two libraries of pre-defined commands called stdio.h (standard input and output) and math.h (a math library including things like sin, cos, etc). Main is a function that is in every C program, and contains the lines of code you want to run. The printf command should be self-explanatory, and the \n is a newline character, that tells the computer to put a new line after the text. Finally, return 0 tells the main program that the code has successfully completed.

To run the code, first we need to compile it. To do this we will use a compiler called g++. At the shell command line, type g++ hello.c -o hello The -o means output, and so g++ will read the hello.c file, compile it into computer understandable language, and place the results in a file called hello. The file hello is an executable program. To run it, type./hello TASK 1: Try adding a few more printf lines to the program and get the computer to print out additional text. You'll have to recompile the program after modifying it. SIMPLE MATHEMATICAL OPERATIONS IN C It's convenient to write programs to do calculations. This is a simplest example of how to do this. More complicated examples would be a program with a large set of equations that need to be solved (Newton's equations for many atoms in a molecule for example). You would give an initial set of coordinates for the atoms, and possibly initial velocities, and then solve for the subsequent motion over time. Here, we are just going to multiply numbers together. Open a file called math.c using vi, and write the following code into the file, and then save and quit from vi. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^math.c^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ double b, product, sum, difference, dividend; int j; b = 4.5; j = 3; product = b*j; sum = b+j; difference = b-j; dividend = b/j; printf("the numbers multiplied are %f and %d.\n",b,j); printf("the value of product is %f.\n",product); printf("the value of sum is %f.\n",sum); printf("the value of difference is %f.\n",difference); printf("the value of dividend is %f.\n",dividend); return 0; To compile the program type g++ math.c -o math, and then to run the program type./math There are several variables in this program. They are b, product, sum, difference, dividend, and j. In a C program, you first have to define what data type each of the variables are. Everything except j is of type double. This means that they can be decimal numbers with lots of precision. The variable j is of

type int, which means it is an integer. It can only be a whole number. The other thing you'll notice are the printf statements. When you want to print a variable to output, you have to have a placeholder in the printf statement. For decimal numbers (also called floating point numbers) you need a %f, and for integers you need a %d. Then, after you close the quotes, you list the variables in the order the placeholders appear in the printf statement. In other words... printf("the numbers multiplied are %f and %d.\n",b,j); The %f corresponds to b, and %d corresponds to j. If you'll notice, this calculation program has limited use. It requires the user to change the values of b and j within the code to get a different set of calculations. TASK 2: Change the values of b and j in the program, then recompile the C program, and run it again. See that you get different values. Real scientific computing C programs won't usually have this step. Instead, you'll feed values of the different parameters you're interested in manipulating into the program from some external data file. We won't cover that here, but realize that it is possible to both read data in from files, and read data out to files (instead of to the screen) using C. LOGIC IN C PROGRAMMING if statements So far, we've learned how to print to the screen, and how to do simple calculations. The next step is computer logic. Sometimes we only want to carry out certain steps in a program when a particular condition is met, or we want to carry out some step a specific number of times before moving on to another part of the program. Logic allows us to do this. We'll learn about if statements, for loops, and while loops. Use vi to open a file called if_example.c and write the following code into the file. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^if_example.c^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ double a, b; a = 10; b = 5; if (a > b) { printf("%f is greater than %f.\n",a,b); if (a < b) { printf("%f is less than %f.\n",a,b); if (a==b) { printf("%f is equal to %f.\n",a,b);

The if statement checks to see if a condition is true, and then does something based on that. If the condition is true, statements inside of the { brackets will be evaluated. If the condition is not true, statements inside of the { are ignored. Inside of the () brackets is the argument of the if statement. This holds the condition that you are checking. The comparison operators in C are > (greater than), < (less than), == (equal to),!= (not equal to), <= (less than or equal to), and >= (greater than or equal to). To compile the code, type g++ if_example.c -o if_example at the shell command line, and then type./if_example to run the code. TASK 3: Change the values of a and b, recompile, and rerun the code and see that the different conditions all evaulate correctly. while loop/for loop Loops are just what they sound like. They are a statement that is evaluated over and over a certain number of times. That number of times could be determined by a counter index, or by whether or not a condition has yet been satisfied for example. Here we'll see how to do a couple of simple examples with these types of loops. First, use vi to open a file called for_loop_examples.c, and then put the following code into the file. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^for_loop_examples.c^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ double input, cube; int j; input = 5; cube = 1.0; for(j=1;j<=3;j++) { cube = cube*input; printf("the cube of %f is %f.\n",input,cube); if(cube>100.0) { printf("%f is greater than 100.\n",cube); else { printf("%f is less than or equal to 100.\n",cube); printf("try making the input variable larger.\n"); return 0;

The for loop takes several arguments in the () brackets. It works like this... for(initial counter value;condition that counter must meet;increment the counter) So, in this code, the counter j started at 1, the loop ends after j is no longer less than or equal to 3, and every time through the loop j is increased by 1 (that is what j++ does). To compile the code, tyep g++ for_loop_examples.c -o for_loop_examples at the shell command line. Then, to run the executable type./for_loop_examples and see what your output is. Note that we also introduced the else statement which is a statement that can follow the if statement to handle all other possiblities if you only need a it's this or that type of evaluation (otherwise you'd use multiple if statements). TASK 4: Change the value of the variable 'input' in the code in order to calculate the cube of a different number. Recompile and rerun the code to get the new output. TASK 5: How would you change the code in order to calculate the fourth power of a number? Make the modification and recompile and rerun the code to see if it works as you expect. Now, we're going to rewrite this code using a while loop to show that, basically, while loops and for loops are interchangeable with a few modifications. So, using vi open a file called while_loop_example.c and put the following code into the file. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^while_loop_example.c^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ double input, cube; int j; input = 5; cube = 1.0; j = 1; while(j<=3) { cube = cube*input; j++; printf("the cube of %f is %f.\n",input,cube); if(cube>100.0) { printf("%f is greater than 100.\n",cube); else { printf("%f is less than or equal to 100.\n",cube); printf("try making the input variable larger.\n");

return 0; You'll notice a couple of small differences in the while loop compared to the for loop. The while loop takes one argument in its () brackets, which looks like... while(condition to be met) So, while the condition is met, the stuff inside the while loop is evaluated. Once the condition is no longer met, the while loop is exited from. You'll notice we had to do two things differently than in the for loop case. First, we had to initialize the counter j outside of the loop. We do this in the line right before the while loop with the expression j = 1. Second, we have to increment j by hand within the loop, and we do this with the j++ command within the loop brackets {. Try compiling this code with the command g++ while_loop_example.c -o while_loop_example entered at the shell command line. Then, run the code with./while_loop_example and see the output. TASK 6: Change the value of 'input' in this code to see how the output changes, and that it changes in the same way as with the for loop. You'll have to recompile and rerun to see the output. TASK 7: Figure out how to change this code to calculate the fourth power of a number. Then, recompile and rerun to see that it works. END OF PART I There are many other nuances that we didn't go into in this tutorial. For example, the if statements, for loops and while loops can take multiple conditions, such as... if((j>=0 && j<=10)) or while((j<=0 j>=10)) The && is called the logical and. It tells the if statement that it should be evaluated in the case that j if greater or equal to zero AND it is less than or equal to 10. The is called the logical or. It tells the while loop that it should be evaluated when j is either less than or equal to 0 OR j is greater than or equal to 10, but NOT in between. So, as you see, there is quite a bit you can do with C. Next time we'll look at some more advanced topics, and hopefully try to modify some slightly more complicated codes now that we have some handle on these basic concepts.