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

Similar documents
University of Northumbria - School of CEIS A quick guide to C MJB September 2016

CSE 303 Lecture 8. Intro to C programming

Compiling and Running a C Program in Unix

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

8. Characters, Strings and Files

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

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

PRINCIPLES OF OPERATING SYSTEMS

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Topic 6: A Quick Intro To C

ONE DIMENSIONAL ARRAYS

Programming refresher and intro to C programming

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

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

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Intermediate Programming, Spring 2017*

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

Arrays, Strings, & Pointers

A Quick guide to C. Dr Alun Moon September 16, Contents. Introduction 2 Unix 2 On Program design 4. C programming Good practice 4

Lectures 5-6: Introduction to C

Kurt Schmidt. October 30, 2018

Should you know scanf and printf?

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

An overview of Java, Data types and variables

Chapter 11 Introduction to Programming in C

Lectures 5-6: Introduction to C

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

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Chapter 11 Introduction to Programming in C

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

CS 231 Data Structures and Algorithms, Fall 2016

CSC231 C Tutorial Fall 2018 Introduction to C


Program Organization and Comments

C Introduction. Comparison w/ Java, Memory Model, and Pointers

C programming basics T3-1 -

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Array Initialization

A Fast Review of C Essentials Part I

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

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

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

Chapter 11 Introduction to Programming in C

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

A brief introduction to C programming for Java programmers

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

today cs3157-fall2002-sklar-lect05 1

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

CSE 374 Programming Concepts & Tools

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Variables and literals

Computer Science & Engineering 150A Problem Solving Using Computers

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

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Chapter IV Introduction to C for Java programmers

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

COMP s1 Lecture 1

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

CSE 303: Concepts and Tools for Software Development

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Chapter 11 Introduction to Programming in C

ARRAYS(II Unit Part II)

Tutorial 1 C Tutorial: Pointers, Strings, Exec

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1

CS 61C: Great Ideas in Computer Architecture Introduction to C

Work relative to other classes

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

just a ((somewhat) safer) dialect.

Warm-up sheet: Programming in C

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Chapter 8 Character Arrays and Strings

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Introduction to C Language

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Programming in C. What is C?... What is C?

C, C++, Fortran: Basics

C mini reference. 5 Binary numbers 12

EECS2031 Software Tools

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

Procedures, Parameters, Values and Variables. Steven R. Bagley

Computers Programming Course 11. Iulian Năstac

Lecture 2, September 4

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

QUIZ. Can you find 5 errors in this code?

C for C++ Programmers

EL2310 Scientific Programming

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Introduction to string

Transcription:

alun@debian:~$ gcc hello.c alun@debian:~$ a.out Hello, world alun@debian:~$ gcc -o hello hello.c alun@debian:~$ hello Hello, world alun@debian:~$ 1

A Quick guide to C for Networks and Operating Systems School of Informatcs, Univeirsity of Northumbria September 17, 2013 import java.lang.*; /** * Some comments */ public class Table static public void main ( String[] args ) import java.lang.*; /** * Some comments */ public class Table static public void main ( String[] args ) int main ( int argc, char **argv ) printf("hello, world\n"); int main ( int argc, char **argv ) printf("hello, world\n"); Abstract These notes are intended as an introduction to the C programming language. They are written for students who have previous experience with Java and are taking the Networks and Operating Systems module. 2

Contents 1 Introduction 3 2 Program structure 4 3 Variables, and Types 5 3.1 Operations.............................. 5 3.2 Arrays................................. 5 3.3 Strings................................. 5 4 Control structures 6 5 Functions 6 6 Pointers 7 6.1 Warning!............................... 7 6.2 Parameters for functions....................... 8 6.3 Safe use of strings.......................... 9 7 IO made easy 9 7.1 Fields................................. 9 7.2 Input.................................. 11 7.2.1 Command line........................ 11 7.2.2 Stdio scanf.......................... 11 1 Introduction C or C++ are the languages most commonly used for systems programming. These languages allow the programmer to have direct access to the operating system and, potentially, the real hardware. Java, by contrast, achieves its portability by running on a virtual machine that deliberately isolates the Java programmer from the underlying physical machine. The C language is about 30 years old, and was the language used to write Unix. C++ was originally written as an extension of C, to introduce object oriented ideas such as a class, and inheritance. Java uses many of the same ideas, and has a similar syntax to C++, but since it was devised as a complete new language some of the less attractive aspects of C, that C++ inherited, are not present in Java. For this module you will need to understand some simple programs, and write some pieces of code to extend or modify these programs. The programs don t use object orientation, but do make use of relatively low level operating systems interfaces, so Java is not appropriate, so C is used. Only a subset of C is needed, and those students who have previously used Java should find many similarities between the languages. These notes are intended to help a Java programmer understand how to read or write programs for this module. They should not be regarded as a definitive description of C. For more information on C programming, novice programmers could look at A First Course in Computer Programming Using C by King, 3

Pardoe, and Vickers (McGraw Hill, 1995). Experienced programmers are recommended to look at Kernighan & Richie s definitive book The C Programming Language (Prentice Hall). 2 Program structure C programs are a collection of functions, which may be written in one or more source code files. Unlike Java, the filename does not need to correspond to the function or program name,but the compiler does require that the filenames end with.c All the functions in C programs are public throughout the program, there is no need to distinguish between public and private functions in C. (This simplifies easy programs, but can be a weakness if misused.) Each program must have one function called main. When the program is executed, the execution starts with the first instruction of main. A simple C program is /* a simple C program */ void main() printf("hello world\n"); This program consists of a single function, called main, which does not return any value, so like its Java equivalent, is of type void. The first line of the program specifies a header file, stdio the compiler will read this file before dealing with the rest of the program. There are two types of header file local files, which need their filename in double quote marks system files,which need their filename in angle brackets < > In this example stdio.h is the file that contains the definition of printf used inside main. As with Java, C statements end with a semi-colon. Comments begin with /* and end with */ they can extend over several lines. Take care to make sure you use */, or the compiler will ignore most of your program To run a C program you need to first compile it. If the program is called prog.c, then it can be compiled with gcc myprog.c. By default the program gcc creates is called a.out. To give the executable file another name use the -o compiler option gcc -o prog prog.c, this writes to a file called prog. The program can be run by typing its name at the shell prompt (assuming PATH is set to contain the current directory). 4

3 Variables, and Types C has a number of intrinsic or built in data types. The only ones we will need are int, long, char and float. These more-or-less correspond to the Java types with the same names (though Java defines them more carefully than C). C doesn t have a boolean type with values true and false. C programmers have to use an int variable, where 0 represents true and any other value represents false. Variables are declared in the same way in C and Java: int length, height; long largenumber; float area; Generally, the best place to declare variables is in the statements at the beginning of a function, and these variables are then in scope for the whole of the function. Sometimes variables are declared at the beginning of a file, outside of any functions. These variables are global to all the functions in the file. Variable names in C (like Java) are case sensitive, so largenumber and largenumber are two different variables. 3.1 Operations The symbols =, +, -, *, /, <, >, == all have same meaning in numeric expressions for both Java and C. Generally, identical operations in each language will result in identical values, but errors are dealt with differently in the two languages and division by zero will crash one of our C programs, whereas in Java it produces NaN. When these operators are used solely with operands of type int, the result is an int. Care should be taken with the division operator, since the result of 5/2 is 2 but the result of 5.0/2 is 2.5 3.2 Arrays In C arrays are declared and instantiated in a single statement eg char buffer[1024]; declares an array to hold 1024 characters, in locations numbered from 0 to 1023. In C, unlike Java, arrays aren t objects with methods, so you can t ask an array what size it is. The size can t change after it has been declared and the programmer is expected to know the size. 3.3 Strings Strings of characters, such as hello world can be dealt with in a variety of ways. In our programs we use the original approach to strings, which is to store the string as a sequence of characters ending with a special character called null - this is the character which has ASCII code zero. So the string hello world consists of 12 characters! A variable to store a student identifier (which has 7 characters) could be declared with char id[8]; 5

These null terminated strings are the way Unix (and many other systems) internally deals with strings. They can t be manipulated using =, ==, or + in the way that Java (or even C++ with a suitable string class) allows. To test if two strings are equal the function strcmp is used, and strcpy or strcat can be used to copy or concatenate strings. Example programs using these functions will be available. (When using these functions, the system header string.h should be included in your program - see examplestring) values can be set in a program using double quote marks. Single quotes are reserved just for single character values. So m is a single character value, but "m" is a string containing two characters m and the null character. char ch; char s; char str[50]; ch= m ; /*legal */ s="m"; /* error */ strcpy(str,"m"); /* legal */ strcpy(ch, "m"); /* error */ strcpy(str, m ); /* error */ 4 Control structures If statements and loops can be programmed the same way in both Java and C. Some C examples are: if ( age < 18) strwrite("too young to buy alcohol"); else strwrite("too old to get a child fare"); int i; for (i=0;i<11;i++) printf("%i times 7 = %i\n", i, i*7); 5 Functions A function in C looks like a Java function (method), except that it doesn t belong to a class (C doesn t have classes and objects) and you don t have to worry about qualifiers such as public, private or static. If the function generates a value, that value can be passed back using the return statement. Parameters can be used to pass values into a function. Each parameter has to have its type declared, and the type should match the type used when the function is called. int twomore(int n) return(n+2); 6

void main() int p; int q; p=4; printf("%i\n", twomore(p)); /* OK */ q=twomore(467); /* OK */ r=twomore(45.67); /* the parameter will be converted to an integer before the function executes */ 6 Pointers The declaration int x; Declares an integer variable, called x. The declaration int *y; Or int* y; Declares a pointer to an integer. This means that the variable y can contain an address, at which an integer can be stored. Initially y doesn t contain a suitable address, but it can be given one with an instruction such as y = &x; The ampersand means the address of. In this example the address of x is stored in y. Pointers are often used with arrays of characters, for example char* message; message="hello World"; Here a pointer variable is declared and then in the next instruction the compiler will store the null terminated string Hello world somewhere in memory, and then put the address where the string starts into message. The string could be printed using printf(message) or printf("%s\n", message) 6.1 Warning! Technically, an array name is a pointer to the memory locations used by the array. One of the most common C programming errors is to confuse pointers and arrays when inputting a string. For scanf("%s", name); 7

This will work if name has been declared as an array (it needs to be big enough to hold the whole string, including the null terminator). If name has been declared as a pointer and the pointer has not been made to point to a suitable area of memory then the program will usually crash with a message such as memory fault. This does not mean the computer s memory is faulty, it means that the programmer has, in effect, tried to store the input string in an area of memory that has not been allocated for this purpose. All C or C++ programmers probably make this mistake at least once. But good programmers learn from their mistakes! 6.2 Parameters for functions One of the main uses for pointers (and/or & operators) is when using a function to change the values in one or more variables. In C, parameters are always called by value the function uses a copy of the parameter, and any changes to the parameter within the function are lost when the function has finished. eg void addtwo(int x)/* this function doesn t do anything useful */ x=x+2; will do nothing useful try it with void addtwo(int x)/* this function doesn t do anything useful */ x=x+2; main() int n; n=56; addtwo(n); printf("%i\n", n); If you want a function to change the value of a variable, then the function must be given the address of the variable and for the function, the parameter is a pointer to the variable. void addtwo(int* x)/* this functions adds two to *x */ *x=*x+2; main() int n; n=56; addtwo(&n); printf("%i\n", n); 8

When using an array as a parameter, remember that the array name is really just a pointer, so there is no need to use the & operator. eg char name[100]; strlen(name); 6.3 Safe use of strings Strings are stored in arrays of char. The array must be declared, with a fixed size and this gives the maximum size of string that can be stored in the array. Functions such as strcpy or strcat which copy strings can try and store a string larger than the array. When the program executes this will lead to other data in the program s memory being overwritten, or the program crashing. Safer versions of these functions, that allow the programmer to specify the maximum size of the string to be copied, are strncpy and strncat. main() char firstname[20]; char secondname[20]; char fullname[30]; int len; scanf("%s",firstname); scanf("%s",secondname); strcpy (fullname,firstname); len = strlen(firstname); strncat(fullname,secondname,30-len-1); /* Length of fullname: less the number of characters in firstname, less 1 for the terminating null character */ printf(fullname); 7 IO made easy The IO library in C is stdio, to use it include the system header file. The basic output function is printf. It prints the string supplied to the function on stdout, note that the newline has to be given explicitly in the string using the \n sequence. 7.1 Fields printf can format and print numbers and text. The place for the value is introduced by a % sign, the type of the variable to be printed is given by a letter as follows 9

i integer f floating point s string (char array) The general format of the placeholder is %width.precision type where the width is the minimum number of characters to use, precision is the number of decimal places to use, and type is a letter as above. For example the program, int main() int n=5; printf(" %d \n",n); printf(" %5d \n",n); printf(" %05d \n",n); printf(" %-5d \n",n); float p= 1.0/6.0; printf(" %f \n",p); printf(" %6f \n",p); printf(" %6.2f \n",p); printf(" %-6.2f \n",p); produces 5 5 00005 5 0.166667 0.166667 0.17 0.17 for strings the precision is the maximum number of characters to use from the string. main() char *sample = "This is a bit of sample text!"; printf(" %s \n",sample); printf(" %10s \n",sample); printf(" %40s \n",sample); printf(" %-40s \n",sample); printf(" %20.10s \n",sample); printf(" %.10s \n",sample); 10

This is a bit of sample text! This is a bit of sample text! This is a bit of sample text! This is a bit of sample text! This is a This is a 7.2 Input There are two ways of getting input into your program, command-line arguments, and the stdio library. The command line arguments are quick and easy, useful for giving initial data to the program. The stdio functions are more flexible. 7.2.1 Command line The command line is passed into the program via arguments to main, an example program and its output are shown below. /* A program to print out the arguments to main. It illustrates how the command line input is split into words, and assigned to the argc and argv prameters to main. */ int main (int argc, char **argv) int i; for (i = 0; i <= argc; ++i) printf ("argument %i=%s\n", i, argv[i]); alun@debian:~/nos/examples$ cmd this is a sample line argument 0=cmd argument 1=this argument 2=is argument 3=a argument 4=sample argument 5=line argument 6=(null) alun@debian:~/nos/examples$ The first parameter to main receives the number of words in the command-line. The input is split into words using spaces as seperators. The second parameter is an array of strings (pointers to characters). The first element is the name of the program, the array has a null pointer after the last commnand-line argument. 7.2.2 Stdio scanf The basic input function in stdio is scanf. It uses the same strings to indicate data to be read. 11

alun@debian:~$ gcc hello.c alun@debian:~$ a.out Hello, world alun@debian:~$ gcc -o hello hello.c alun@debian:~$ hello Hello, world alun@debian:~$ Or alun@debian:~$ javac Hello.java alun@debian:~$ java Hello Hello, world alun@debian:~$ 12