C Programming lecture 2 Beautiful programs Greek algorithms

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Introduction to C Programming
Chapter 7: Arrays In this chapter, you will learn about
Programming in C Chapter 10 Structures and Unions
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
C Language.
IT 325 OPERATING SYSTEM C programming language. Why use C instead of Java Intermediate-level language:  Low-level features like bit operations  High-level.
ARDUINO CLUB Session 1: C & An Introduction to Linux.
An introduction to pointers in c
1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Computer Programming w/ Eng. Applications
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
C Programming - Lecture 5
Kernighan/Ritchie: Kelley/Pohl:
Lecture 2 Introduction to C Programming
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
Chapter 10.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
PHYS 2020 Making Choices; Arrays. Arrays  An array is very much like a matrix.  In the C language, an array is a collection of variables, all of the.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a ‘wrappered function’? –What is a clean interface? –How to earn your.
IT253: Computer Organization Lecture 4: Instruction Set Architecture Tonga Institute of Higher Education.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
CSC 107 – Programming For Science. Announcements  Textbook available from library’s closed reserve.
“In mathematics and computer programming, Index notation is used to specify the elements of an array of numbers”
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
1 CS161 Introduction to Computer Science Topic #9.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
1 Homework HW4 due today HW5 is on-line Starting K&R Chapter 5 –Skipping sections for now –Not covering section 5.12.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS 31 Discussion, Week 5 Faisal Alquaddoomi, Office Hours: BH 2432, MW 4:30-6:30pm, F 12:00-1:00pm (today)
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
A bit of C programming Lecture 3 Uli Raich.
© 2016 Pearson Education, Ltd. All rights reserved.
Quiz 11/15/16 – C functions, arrays and strings
Arrays in C.
Object Oriented Programming COP3330 / CGS5409
C Arrays.
7 Arrays.
Arrays Arrays A few types Structures of related data items
The C Language: Intro.
Variables in C Topics Naming Variables Declaring Variables
C Programming - Lecture 3
Presentation transcript:

C Programming lecture 2 Beautiful programs Greek algorithms Arrays of numbers Strings of characters Pointers (the really difficult bit of C)

Beauty is truth and truth beauty A program which is neatly formatted is easier to understand If you're staring in confusion at a load of {s and }s and don't know whether you need another } your program is probably UGLY Indenting consistently is especially important. (in functions, for, while if and else). One of our most important goals as a programmer is to write something that other people can read.

Layout of a program (brace style) int main() { int i,x,y; float z; . if (x < 7) { y= 3; z= 4.2; } else if (x > 23) { y= 5; z= 7.2 } for (i= 1; i < 200; i++) { for (j= 1; j < 200; j++ { /* Inside both loops */ /* Inside only the first loop */ return 0; Always indent after a left bracket Right bracket level with statement which started it Start a left bracket after a statement NOTE: Not all code on these overheads follows this style for space reasons

MAGIC numbers in programs A lot of programs contain what programmers sometimes call MAGIC nos g= 43.2 * a + 7.1; for (i= 7; i < 103; i+=2) { printf ("%d\n",i*7); } This makes code look UGLY and it is confusing to the reader. It is better to give some idea of what these numbers mean in the program.

Enum We can use the enum command to define int s and chars. It looks like this: enum { MAX_LEN= 100, LETTERX= 'x', NEWLINE= '\n' }; By convention we use all capitals for enum constants. That way we can tell them from variables. We can now use the enum constant wherever we could use an int or char for (i= 0; i < MAX_LEN; i++) printf (“%c”,LETTERX);

#define This preprocessor command replaces one thing with another before compilation NOTE – NO semi colon here! #define PI 3.14 #define GRAV_CONST 9.807 #define HELLO_WORLD "Hello World!\n" Now, anywhere in the program we use PI or GRAV_CONST it will be replaced with the replacement string BEFORE the real compiler starts (that's why we call it pre-processing) c= 2.0 * PI * r; a= GRAV_CONST * (m1*m2)/ (r * r); printf (HELLO_WORLD);

Const Another solution is to use the const keyword. This is perhaps the best solution but it sometimes causes problems on older compilers. /* Approximate value of PI */ const double PI=3.14; /* Maximum iterations to be performed before exiting */ const int MAX_ITER=1000;

This lecture's program The sieve of Eratosthenes is an algorithm of greek origin. It is a relatively efficient way of constructing a list of small prime numbers It is defined in your notes in the section "going from algorithm to program". It is also going to be used in the next worksheet.

The sieve 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 After appropriate crossing out we have prime numbers But how can we represent the sieve in C? The goal of this is to find another way to write our is_prime function.

Choosing a data representation When going from an algorithm to a program, one of the first questions is "How can I represent my data?". If the program has to store anything then what is the best way to store it? In the case of the sieve of Eratosthenes, we need to store a table of numbers. In this case, a good storage mechanism is an array – a list of numbers.

The ARRAY An array in C is a group of similar variables. For example 200 ints or 45 chars Arrays use square brackets like so: int some_nums[200]; char bunch_o_chars[45]; some_numbers[3]= 5; printf ("Element 3 is %d\n",some_nums[3]); bunch_o_chars[0]= 'a'; Unfortunately, in C, we must give the length when we declare the array (see lecture notes). ARRAYS CAN BE MODIFIED BY FUNCTIONS! For the reason see later in the lecture

Great C muck-ups: #5 in a series of 100 If we declare an array in C to be 100 elements the array is numbered from 0 to 99. EVERYBODY at some point makes this mistake: int a[100]; /*Declare 100 ints */ a[0]= 52; a[1]= 3; a[100]= 5; /* This is a common error There is NO element 100 but your program will compile and run*/

Passing arrays to functions We prototype a function which accepts an array like this: And write the function like this: And call the function like this: Note that we CAN’T return an array from a function (but see later). void process_array (int []); int calc_array (char[]); void process_array (int all_nums[]) { all_nums[1]= 3; . } int some_numbers [100]; process_array(some_numbers);

So what does this mean for our sieve? We could use an enum to define how many primes we want our array to be. We can use an array to store whether or not it has been crossed (it only needs to be a 1D array - think about this) We can have an enum to say whether it is crossed or not crossed (instead of storing the number) Write something to uncross all the array

Look for some obvious sub-tasks which might be functions What bits of our algorithm are obvious candidates for becoming functions? What data do we need to pass to and from each function? Write the bits that call the function and the prototype Then write the function

Look for some obvious LOOPS Two of the most used workhorses in C are the for and while loops. Which is clearer in this case? A for or while loop? What indeed is the difference? for (initialiser ; condition ; increment) { code; } initialiser; while (condition) { increment; } Generally we use for when the initialiser, condition and increment are all on the same variable. There is ONE difference – can you work out what?

Checking the sieve works Don't just TRUST your program - check it. In a big program it is good to check functions as they are written - not the whole program. Check as you write. The best way to check something is working is to get some print out from it. So add something to the sieve to print all the primes which have been found so far.

Strings in C When we want to store and print text in C we use a string A string is an array of type char which has '\0' as the last character. '\0' is a special character (like '\n') which means "stop now". We can initialise a string using = but we can't set a string using this at other times (use sprintf)! We can print a string with %s: char hi_there[]= "Hello World!\n"; printf ("%s", hi_there);

Useful functions with strings We can find a lot of useful functions in the library string.h #include <string.h> int main() { char test[100]; char test2[]= "World!\n"; strcpy(test,"Hello"); strcat(test,test2); if (strcmp(test,"dave") == 0) printf ("Test is same as Dave\n"); printf ("Length of test is %d\n", strlen (test)); }

Great C muck-ups: #91 in a series of 100 Remember, our string must be big enough to HOLD what we put in it. char small_string[]= "Hey there"; sprintf (small_string,"Hello World!\n"); This will almost certainly cause problems. The first statement sets up a string which is only big enough to hold 10 characters [Why 10? Think about it.] The second statement tries to put 14 characters into it. Disaster!

The scanf statement Scanf can be used like printf but to read instead of write. It is a confusing way to read data from the user (we will see why in later lectures) But look – number CHANGED – we said that didn’t happen! int number, check; check= scanf ("%d",&number); if (check != 1) { printf ("Error!\n"); return –1; }

Pass by reference/Pass by value Normally when we send a variable to a function we make a COPY of the variable. This is called pass by value. A value is passed and this copy of the variable arrives at the function. Sometimes, like in scanf we want to change the variable inside the function. In this case we need to do something different: pass by reference. This is what the & character is for.

What are pointers? Pointers are one of the most difficult topics to understand in C. Pointers "point at" areas of your computer's memory. Imagine your computer's memory as a series of boxes which all hold ints says p is a pointer to an int int *p; 56 71 12 3 21 7 p points at one of the ints

& means "address of" or "point at me" & means "address of" or "point at me" * means value or "what am I pointing at?" int *p; int q= 5; p= &q; printf ("p is %d\n",*p); *p= 5; p is a pointer to an int q is an int p now points at q Therefore p has the same value of 5 We use *p to mean "the value p is pointing at"

What's the point of pointers? When we use & to pass a pointer to a variable into a function we CAN change the value of the variable within the function. This is called pass by reference. This is what was going on when we use & in scanf. In the next lecture we will hear more about pointers and how to use them. We will also learn that arrays are nearly the same thing as pointers.

How we can change an argument within a function void square_num (int *); int main() { int p= 5; square_num (&p); printf ("P is now %d\n",p); return 0; } void square_num (int *num) (*num)= (*num) * (*num); Prototype a function taking a POINTER Pass the address of p to our function Now the function has changed p to 25 Remember * gives the value the pointer points at

Pointers! Pointers are confusing But they are also very useful With pointers we can effectively return more than one thing from a function Arrays are a form of pointer really We will (unfortunately) be hearing a lot more about them in subsequent lectures