Click here to load reader

1 Programming in C Hello World! Soon I will control the world! Soon I will control the world!

Embed Size (px)

Citation preview

Microsoft Visual Basic 2008: Reloaded 3e

Chapter 3Your First ProgramProgramming in C

Hello World!Soon I willcontrol the world!##1V2111 Ch 031/3/2012 9:27 AMIntroduction to CC languageFacilitates a structured and disciplined approach to computer program designProvides low-level accessHighly portable

#Is C the best language? C has a couple of advantages.It helps create a structured disciplined approach to computer program design.C provides low-level access while being a higher level language.C is also highly portable to different computer systems.

2V2111 Ch 031/3/2012 9:27 AMProgram BasicsThe source code for a program is the set of instructions written in a high-level, human readable language.X = 0;MOVE 0 TO X.X := 0The source code is transformed into object code by a compiler. Object code is a machine usable format.The computer executes a program in response to a command.

#Lets go over some basics.You write a program in some programming language creating the source code using an editor.A compiler is involved in translating the source code to object code which resembles machine language.There may be other programs involved in this process.Upon command, the computer or operating system executes the object code by loading it into memory and fetching the first instruction in the program.3V2111 Ch 031/3/2012 9:27 AMBasics of a Typical C EnvironmentPhases of C Programs:EditPreprocessCompileLinkLoadExecute

Loader

PrimaryMemory

Program is created inthe editor and storedon disk.

Preprocessor programprocesses the code.

Loader puts programin memory.

CPU takes eachinstruction andexecutes it, possiblystoring new datavalues as the programexecutes.

Compiler

Compiler createsobject code and storesit on disk.

Linker links the objectcode with the libraries,creates a.out andstores it on disk

Editor

Preprocessor

Linker

CPU

PrimaryMemory

...

...

...

...

Disk

Disk

Disk

Disk

Disk

#In chapter 2, I talked about the detailed steps that we go through in a development environment that takes us from entering the program to executing the program. The programs and number of steps can vary depending on the OS and the language.4V2111 Ch 031/3/2012 9:27 AMGCC Program BasicsThe basic program writing sequence:create or modify a file of instructions using an editorUnix: Pico, vi, emacs, compile the instructions with GCCexecute or run the compiled programrepeat the sequence if there are mistakesPico:http://www.bgsu.edu/departments/compsci/docs/pico.html

#Lets look at a more general case using GCC, the GNU C Compiler. GNU is a free Unix-like operating system.

1st we create or modify a file using an editor. Popular editors include Pico, Vi, and Emacs. I will be using Pico in class because it is a very simple editor to learn.

2nd we compile our C program using GCC. If there are errors, we go back to #1.

3rd we execute the program. If there are errors, we go back to #1.5V2111 Ch 031/3/2012 9:27 AMStructure of a C Program Every C program must have a main function...

main functionfunction 1function n#Each C program is composed of functions. Execution starts with a function named main. This and other functions in the program can invoke or call other functions.

What do these functions look like?6V2111 Ch 031/3/2012 9:27 AMFunctionsEach function consists of a header followed by a basic block.General format:

fn-name (parameter-list) basic block

header#The definition of a function starts with a header statement. The header specifies the type of the value that is to be returned to the caller, the name of the function, and parameters that are to be passed to the function.

The header is followed by a basic block.7V2111 Ch 031/3/2012 9:27 AMThe Basic BlockA semi-colon (;) is used to terminate a statementA block consists of zero or more statementsNesting of blocks is legal and commonEach interior block may include variable declarations

{ declaration of variables executable statements}#A basic block is enclosed in braces and starts with statements to declare variables which is then followed by executable statements. Statements within the block end in a semi-colon.

As we will see, blocks can be nested creating blocks within blocks.8V2111 Ch 031/3/2012 9:27 AMReturn statement(p. 126)return expressionSets the return value to the value of the expressionReturns to the caller / invoker

Example:

#The header specifies the type of the value to be returned to the caller. The return statement specifies the actual value to be returned. After the keyword return, you code an expression specifying the value to be returned. The return statement not only sets the return value but it also immediately returns to the caller.

Here we see an example of a main function. Main should return an int, an integer value. At the end of main in this example, a zero is returned to the caller, probably the operating system, indicating that the program executed normally.9V2111 Ch 031/3/2012 9:27 AMSSHOn-CampusSSH to one of the machines in the listmachine.cs.clemson.eduOff-CampusSSH to access.cs.clemson.edussh machine.cs.clemson.edu

#To develop our first program we want to log into a SOC machine.> SSH + resize window> Go over on-campus vs off-campus

10V2111 Ch 031/3/2012 9:27 AMGo Tigers!!! Our First Program

mkdir cpsc111cd cpsc111pico ch03First.c#Lets develop our first program.

mkdir cpsc111 (Lab will be making lab111) Unix and C are case sensitivecd cpsc111 You will learn more commands in the first labpico ch03First.c > Enter program without comments > Point out #include > Point out free form > Point out {} conventions11V2111 Ch 031/3/2012 9:27 AMCompiling and Running a ProgramTo compile and print all warning messages, type gcc Wall prog-name.cIf using math library (math.h), type gcc Wall lm prog-name.cBy default, the compiler produces the file a.out#> Compile the program> Math library option> Compiled program = a.out

12V2111 Ch 031/3/2012 9:27 AMCompiling and Running a ProgramTo execute the program type ./a.outThe ./ indicates the current directoryTo specify the file for the object code, for example, p1.o, typegcc Wall prog1.c o p1.o then type./p1.o to execute the program

#> Run the program> Recompile with -o

13V2111 Ch 031/3/2012 9:27 AMCommentsMake programs easy to read and modifyIgnored by the C compilerTwo methods:// - line comment- everything on the line following // is ignored

/* */ - block comment- everything between /* */ is ignored

#A good programming practice is to place comments in your program to document the program and make it more readable. Comments are ignored by the compiler. There are two ways to place comments in a C program.

First, by placing double slashes on a line, everything following the // will be ignored. If the // is the first thing on a line, the entire line will be a comment. If it is after a statement, the remainder of the line is ignored.> Add beginning comments> Add return stmt comments

If you need to comment out a number of consecutive lines, there is a second method. Using this method, you start the comment with a slash-asterisk and end it with an asterisk-slash. Anything between a slash-asterisk and an asterisk-slash will be ignored.> Convert beginning comments to /* */14V2111 Ch 031/3/2012 9:27 AMPreprocessor Directive: #includeA C program line beginning with # that is processed by the compiler before translation begins. #include pulls another file into the source

causes the contents of the named file, stdio.h, to be inserted where the # appears. Such a file is commonly called a header file.s indicate that it is a compiler standard header file.

#A line beginning with a pound or number sign is a pre-processor statement. These statements are processed before the actual statements are compiled. The #include, inserts another file into the source at that point.

In this example, we are inserting the contents of stdio.h, a header file which contains function headers for standard input-output. The s indicate that this is a standard compiler file and is to be pulled from the compilers standard location.15V2111 Ch 031/3/2012 9:27 AMIntroduction to Input/OutputInput data is read into variablesOutput data is written from variables.Initially, we will assume that the user enters data via the keyboardviews output data in a terminal window on the screen

#There are many methods for input and output in C. Input is reading data from an input device and placing it into variables, memory within our program. Output is writing data from variables to an output device. Initially we will be processing input data from the keyboard and output data to a terminal window.16V2111 Ch 031/3/2012 9:27 AMProgram Input / OutputThe C run-time system automatically opens two files for you at the time your program starts:stdin standard input (from the keyboard)stdout standard output (to the terminal window in which the program started)Later, how to read and write files on diskUsing stdin and stdoutUsing FILEs#When you run your C program, there are two files that are automatically defined and opened for you. File stdin is used to read data from the keyboard. File stdout is used to write data to the terminal window.

Later on we will learn how to read and write files on disk, first using stdin and stdout and then using our own file definitions.17V2111 Ch 031/3/2012 9:27 AMConsole Input/OutputDefined in the C library included in Must have this line near start of file: #include Includes input functions scanf, fscanf, Includes output functions printf, fprintf,

#The functions for performing I/O to the console or terminal are defined in stdio.h so we must include this file near the start of our program. It includes scanf for input and printf for output.

V218111 Ch 031/3/2012 9:27 AMConsole Output - printfPrint to standard output, typically the screenGeneral format (value-list may not be required): printf("format string", value-list);

#Function printf is used to write to stdout, generally the console terminal. The first argument, the format string, specifies how to print out the values. The comma separated value-list is optional. We will be looking at this in the future.V219111 Ch 031/3/2012 9:27 AMConsole OutputWhat can be output?Any data can be output to display screenLiteral valuesVariablesConstantsExpressions (which can include all of above)NoteValues are passed to printfAddresses are passed to scanf#With printf you can output literal constant values, variables, named constants, and expressions. Values are passed to printf. The scanf function for input, however, uses the address of variables to specify where the input is to be placed.20V2111 Ch 031/3/2012 9:27 AMConsole OutputWe canControl vertical spacing with blank linesUse the escape sequence "\n, new lineControl horizontal spacingSpacesUse the escape sequence \t, tabSometimes undependable.#You can control spacing between lines by outputting blank lines. A \n in the format string says to insert a new line character which says to go to a new line. Two new line characters printed together will print a blank line.

You can control spacing between characters with spaces or with tab characters. Placing a \t in the format string inserts a tab character in the output which will advance to the next tab stop. Using tabs can be undependable for formatting output so you must be careful in using them.21V2111 Ch 031/3/2012 9:27 AMConsole Output - ExamplesSends string "Hello World" to display, skipping to next line

Displays the lines Good morning Ms Smith.

#The first example here shows the new-line at the end of a line which places you on the next line for output. If you dont use it, you are left at the end of the line and the next output will be printed there.> Divide Go Tigers into two printfs

You can have more than one new-line in one printf function to print multiple lines in one statement. The second example here prints Good morning, goes to a new line, prints Ms Smith., and then goes to a new line. The next output would appear after the Ms Smith line.

You always want to go to a new line after your last line outputted in your program. If you dont, the Unix prompt will appear at the end of your last line.> Before Win line, printf(Go\nGo\nGo\n\n)

22V2111 Ch 031/3/2012 9:27 AMProgram Output: Escape Character \Indicates that a special character is to be output

#\r is used to return to the beginning of the current line.\a is used to ring the bell\\ is used to print one backslash character\ is used to print a double quote23V2111 Ch 031/3/2012 9:27 AMChapter 3Your First ProgramProgramming in CT H E E N D##V224111 Ch 031/3/2012 9:27 AMEscape

SequenceDescription

\nNewline. Position the screen cursor to the beginning of the next line.

\tHorizontal tab. Move the screen cursor to the next tab stop.

\rCarriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line.

\aAlert. Sound the system bell.

\\Backslash. Used to print a backslash character.

\"Double quote. Used to print a double quote character.