C-Programming. Claude Fuhrer 5 août 2017

Similar documents
C: How to Program. Week /Mar/05

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

Chapter 2 - Introduction to C Programming

DEPARTMENT OF MATHS, MJ COLLEGE

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

A Fast Review of C Essentials Part I

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

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

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

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Chapter 1 & 2 Introduction to C Language

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

Data Types and Variables in C language

Syntax and Variables

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Fundamental of Programming (C)

ANSI C Programming Simple Programs

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

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

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

Programming and Data Structures

EL2310 Scientific Programming

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Computers Programming Course 7. Iulian Năstac

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Programming. C++ Basics

C Functions. 5.2 Program Modules in C

Introduction to C Final Review Chapters 1-6 & 13

BLM2031 Structured Programming. Zeyneb KURT

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Informática Ingeniería en Electrónica y Automática Industrial

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Presented By : Gaurav Juneja

Variables. Data Types.

ET156 Introduction to C Programming

Fundamentals of Programming

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Lecture 04 FUNCTIONS AND ARRAYS

BCA-105 C Language What is C? History of C

ET156 Introduction to C Programming

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

BASIC ELEMENTS OF A COMPUTER PROGRAM

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

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

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

Computer Programming : C++

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

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

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

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

UEE1302 (1102) F10: Introduction to Computers and Programming

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Chapter 2: Overview of C. Problem Solving & Program Design in C

Introduction to Computing Lecture 01: Introduction to C

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

C Language, Token, Keywords, Constant, variable

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

Informatica e Sistemi in Tempo Reale

VARIABLES AND CONSTANTS

Fundamentals of Programming

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

INTRODUCTION 1 AND REVIEW

CMPE-013/L. Introduction to C Programming

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

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

Creating a C++ Program

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Computer Programming

The C Programming Language Guide for the Robot Course work Module

Programming in C++ 4. The lexical basis of C++

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

CS102: Variables and Expressions

VALLIAMMAI ENGINEERING COLLEGE SRM NAGAR, KATTANGULATHUR

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

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

2. Numbers In, Numbers Out

DETAILED SYLLABUS INTRODUCTION TO C LANGUAGE

Getting started with C++ (Part 2)

Computer System and programming in C

UIC. C Programming Primer. Bharathidasan University

Maciej Sobieraj. Lecture 1

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Computers Programming Course 6. Iulian Năstac

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

6.096 Introduction to C++ January (IAP) 2009

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

Chapter 2: Introduction to C++

Transcription:

C-Programming Claude Fuhrer (claude.fuhrer@bfh.ch) 5 août 2017

1 Pseudocode The most important step in writing a program, is to understand the problem which should be solved and then establish a strategy to solve it. These two steps are normally independant of the programming language that should be used to write the program. 1.1 A stupid game: guess a number Consider a simple two player game. One player choose a number and keep secret. The second player must guess this number by asking questions to which the first player responds "too big", "too small" or "you found it" We will write two version of this games. In one version, the computer choose the secret number and answer to the questions. In the other version, it must guess the number choosen by its opponent. * 1.2 Version one: computer choose a secret number For this version, to choose the number, the computer use a kind of "virtual dice" called random number generator. Then the computer ask its opponent to guess (that is the opponent enter a value in a given predefined domain, for example between 1 and 100). The computer compare the number entered by the user with the secret number and print the answer. This solution must be a little more formalized to be able to program it. Therefore, one should rewrite it in a slightly modified form: Declare two variables secret and guess Declare a variable found an initalise it to false secret random number between 1 and 100 while found = false do ask the user to enter a guess guess entered number if guess > secret then display text too big end if if guess < secret then display text too small end if if guess = secret then display text You found it found true end if end while 2

This pseudocode may now be implemented. For a first introduction one would not use the C programming language, but a visual programming environment where one can draw the program structure. This environment is called blockly 1 Implementing this code into blocky gives something like: 1. Version two: the computer guess the number For the second version of the game, the computer should guess the number choosed by its opponent. For that, one should first understand what could be the strategy to minimise the number of tries. A naive strategy would be enumerates all number in the search domain, one after another. With this strategy, the computer may try up to 100 values before it find the right answer. But it should be possible to reduce this number. Let us show this on a concrete example. If the initial domain is 1 to 100, the computer may gives at first guess the value 50. The opponent answer that this guess is either to big or to small. Imagine that the opponent is too small. The computer has now reduced the search domain between 51 and 100. Applying the same strategy (bissecting the search domain again and again), ensure that, in the general case, the number of tries would be minimal. Let us write this in pseudocode. To simplify the program, one would let the human player answer -1 if the guess is too small, +1 if the guess is too big and 0 if the computer found the right number. 1 https://developers.google.com/blockly/

Define two variables low and high Define a variable guess Define a variable answer Set low 1 Set high 100 repeat guess (high + low) / 2 display guess answer read user answer if answer = -1 low guess end if if answer = 1 high guess end if until answer = 0 2 A very simple program The most simple program used to test almost every programming environment is the famous Hello world. This program just shows the two words hello world on the screen. It would help to understand the basic structure of a C program. The two first lines declare a set of standard function allowing the program to communicates with the user and the operating system. Theses two lines would be used in all of our programs. 1 #include <stdlib.h> 2 #include <stdio.h> Then, a C program has at least one function called main(). The definition of this function may vary with the programming environment and the operating system. The simplest is: 1 int main() 2 { // Some code here 4 return 0; 5 } For C, a pair of curly braces ({}) delimit a block, that is a set of instruction which can be considered as a single complex instruction. 4

The sentence (the instruction) return 0; says to the operating system that the program exited without any error. One can see that, in C, every instructions ends with a semicolon! For our Hello world program, the body of the function main() contains a single line to display a message on screen. This would say that the complete program would be: 1 #include <stdlib.h> 2 #include <stdio.h> 6 printf ("Hello world!! \n"); 7 return 0; 8 } The function printf() is used to display a text on screen of your computer (this program does not display windows). A text is delimited with double quotes (") at the beginning and at the end. The character \n says that a new line is appended to the text. At the end of the instruction one can see that it ends with a semicolon. Instruction within a block are always shifted to the right from a fixed quantity of spaces (for example 4 spaces). The would help to enhance the readibility of the program and simplify the search of errors 2.1 Comments To enhance the readbility of a program, one can use comments. Comments are text ignored by the compiler but of a great help for the human programmer. In there is two types of comments, the block comments and the line comment. 1 / * A block comment starts with the two characters slash-star and 2 ends with the tow characted star-slash. It may span over many lines and allows to add useful information to your program. 4 5 Within comments one can write in the language of your choice: 6 auf deutsch, en francais o in italiano. 5

7 * / 8 9 // A line comment start with two slashes and end at the end 10 // of the line. If one need a comment over many lines, it 11 // should be repeated 6

Variables, base types and operations.1 Variables To store values of computations, one should use variables. The notion of variables within a C program is very similar to the variables used for mathematics. A variable has a name and a type. The name consist of a suite of letters and decimal digits with the following rules: 1. One can use lower cases letters ( a to z ) without accented character or umlaute. 2. One can use upper cases letters ( A to Z ) without accented characters or umlaute. One can use decimal digits ( 0 to 9 ), but not at the beginning of the variable name. That is, the variable name vectord is legal while the name 2nd_value is not. 4. One can use the underscore character ( _ ) to simulates a space between words No other character are allowed. In particular spaces, punctuation and special symbols are not accepted. Moreover, one cannot use as identifier one of the reserved words of C. C is case sensitive, that is, it makes a difference between lower cases and upper cases. For example, the two variables =radius= and =Radius= represent different variables. Normally variables and function names are always written with lower cases. If a variable name consist of two words, one can use either the camel notation meanvalue where the second word is capitalised or the underscore mean_value. The second scheme is recommended for C. Do not be afraid to use long and descriptive variable names. Except where the usage shows immediately the meaning of variable (for example x for the parameter of function), short names are mostly an annoing source of errors. For example 1 area = radius * radius * M_PI; // easy to read and verify 2 k = p * p * K; // what does it mean? Functions names follow the same rules as used for the variables names..2 Signed and unsigned integers The C programming language provides many types for integer and floating points calculations. For signed integers one can use: 7

int (2 bits) long int (64 bits) char (8 bits). Signed integers are coded using the two-complement previously seen, that is the range of values represented is always symmetric to zero. For example for the type enumerated above one has: char store values between -128 and + 127 int store values between -2 147 48 648 and 2 147 48 647 (that is values between 2 1 and 2 1 1) long int store values between -9 22 72 06 854 775 808 and 9 22 72 06 854 775 807 (that is values between 2 6 and 2 6 1) Moreover, to have unsigned integer, one need to add the reserved word unsigned before. For example: unsigned char store values between 0 and 255 unsigned int store values between 0 and 4294967295.. Operators for integer arithmetic. For integer arithmetic, the C programming language provides only the fives operators: + for the addition - for the substraction * for the multiplication / for the integer division (i.e. integer part) % for the modulo, that is the rest of the division...1 Computations with integers All theses operators are infixed that is, they should be used as usual arithmetic operator. One should should be attentive that the result of these standard operation is not always the "expected" result that you learned in math course, due to the domain of definition of the types given above. For example 8

1 #include <stdlib.h> 2 #include <stdio.h> 6 char a = 100, b = 6, c; 7 c = a + b; 8 printf ("the sum of a and b is %i\n", c); 9 return 0; 10 } For this example, the program should display: The sum of a and b is 120 Why 120? the sum of these two values should be 16, but, one have seen that the biggest signed integer that one may store on 8 bits (char is stored on 8 bits) is 127. Then (remember the number circle), adding 1 to 127 gives -128, and adding 9 to 127 gives -120. This feature may be disappointing for beginner and also the source of many bugs and error if one do not consider the way computers are "thinking". 1. Exercise Do the same exercise with unsigned char. What is the result of this computation? Where is the limit? What happens if we exceed the limit?.4 Example of calculation using integers: 1 #include <stdio.h> 6 int a, b, c; 7 a = 12; 8 b = 5; 9 c = a + b; 10 printf ("a + b = %i\n", c); 11 12 c = a - b; 1 printf ("a - b = %i\n", c); 14 15 c = a * b; 16 printf ("a * b = %i\n", c); 17 18 c = a / b; 9

19 printf ("a / b = %i\n", c); 20 21 c = a % b; / * % == modulo, i.e. rest of the division * / 22 printf ("a %% b = %i\n", c); 2 24 return 0; 25 }.5 Maximum and minimum value of integers types. The coding used for integers types is the "two-complement", that is, for int the value should be comprised between 2 2 1 and +2 2 1 1. This can be easily shown with the following program: 1 #include <stdio.h> 6 int a = 1000; 7 int b = a; 8 printf ("The value of b is %i\n", b); 9 10 b = b * a; 11 printf ("The value of b is %i\n", b); 12 1 b = b * a; 14 printf ("The value of b is %i\n", b); 15 16 b = b * a; 17 printf ("The value of b is %i\n", b); 18 19 return 0; 20 } For variables of type unsigned int, the definition domain is 0 to 2 2 1. 1 #include <stdio.h> 6 unsigned int a = 1000; 7 unsigned int b = a; 8 printf ("The value of b is %u\n", b); 10

9 10 b = b * a; 11 printf ("The value of b is %u\n", b); 12 1 b = b * a; 14 printf ("The value of b is %u\n", b); 15 16 b = b * a; 17 printf ("The value of b is %u\n", b); 18 19 return 0; 20 }.6 Floating points The C programming language provides 2 types of floating points numbers. They a both based on the norm IEEE-754. Theses types are: float for floating points simple precision, that is numbers coded onto 2 bits. The definition domain of these numbers is approximately ±10 7 and they provides 6 significant digits. double for floating point double precision, that is numbers coded onto 64 bits..6.1 A simple example of use of floating points numbers 1 #include <stdio.h> 6 float a = 2.5; 7 float b = 0.1; 8 10 9 printf ("The value of a is %f and the value of b is %f\n", a, b); 11 printf("the sum a + b is %f\n", a + b); 12 printf("the difference a - b is %f\n", a - b); 1 printf("the product a * b is %f\n", a * b); 14 printf("the quotient a / b is %f\n", a / b); 15 return 0; 16 } To illustrate the limited precision of theses numbers, one can show the following program: 11

1 #include <stdio.h> 6 float a = 7542421.0; 7 float b =.0; 8 float c = a / b; 9 10 printf ("The quotient is : %f\n", c); 11 12 c = c + 2.0; 1 printf("the new value of c is : %f\n", c); 14 return 0; 15 } If, for the same computing one use variable of type double instead variable of type float, the program gives: 1 #include <stdio.h> 6 double a = 7542421.0; 7 double b =.0; 8 double c = a / b; 9 10 printf ("The quotient is : %f\n", c); 11 12 c = c + 0.1; 1 printf("the new value of c is : %f\n", c); 14 return 0; 15 }.6.2 Exercise Compute the perimeter and the area of a circle which radius is given. 1 #include <stdio.h> 12

6 float radius, perimeter, area; 7 8 radius = 12.; 9 perimeter = 2.0 *.1415 * radius; 10 area =.1415 * radius * radius; 11 12 printf ("The perimeter of a circle with radius %f is %f\n", 1 radius, perimeter); 14 printf ("The area of a circle with radius %f is %f\n", 15 radius, area); 16 17 return 0; 18 }.7 Exercise Write a program to compute the sum of all odd numbers between 1 and 19. 1 #include <stdio.h> 6 int sum; 7 8 sum = 1 + + 5 + 7 + 9 + 11 + 1 + 15 + 17 + 19; 9 printf ("The searched sum is : %i\n", sum); 10 return 0; 11 } 1

4 Comparisons and boolean operators 4.1 Comparisons operators The C programming language provides boolean and comparisons operators. To compare two numerical values, one can use: < smaller than <= smaller or equal to == equals to >= greater or equal to > greater than These operators may be used to compare numerical values and receive a boolean answer. 4.2 Boolean operators Boolean operators combine boolean values to receive a boolean answer. The boolean operators provided by the C programming language are:! logical not && logical and logical or 14

5 Decision and branch 1 #include <stdio.h> 6 int value = 2; 7 8 if (value >= 0) 9 { 10 printf ("value is positive\n"); 11 } 12 else 1 { 14 printf ("value is negative \n"); 15 } 16 return 0; 17 } The use of boolean operators may be: 1 #include <stdio.h> 6 int value = 12; 7 if ( (value >= 0) && (value < 10) ) { 8 printf ("One can write value with only one symbol\n"); 9 } else { 10 printf ("One need at least two symbols to write value\n"); 11 } 12 return 0; 1 } 5.1 Exercise Write a program called stupidgame.c to guess a secret value between 1 and 100. For the first version of this program, the user has only one try before the program quit. 15

6 Loops If there is a need to execute an instruction (or a block of consecutive instructions) many times, the program need to to a loop. The C programming language provides many structures for loops. For the beginning, one should only study the while loop. The while loop is defined as follow: while ( <condition> ) { <while block> } The <condition> is a boolean expression which is evaluated either to true of false. If it is evaluated to true, the instructions contained into the <while block> are executed once. Then the program skip to the while condition and evaluate it again. As long as the condition returns true, the loop content is repeated. 6.1 Exercise Write a program to compute the sum of all odd numbers between 1 and 9999. 1 #include <stdio.h> 6 int n = 1; 7 int sum =0; 8 9 while (n <= 9999) { 10 sum = sum + n; 11 n = n + 2; 12 } 1 printf ("The searched sum is : %i\n", sum); 14 return 0; 15 } 6.2 Exercise : Collatz conjecture The Collatz conjecture is a problem studied by the mathematician since more than 50 years. The formulation of this conjecture is simple. One choose a natural number n N. Then iteratively, one can compute new value of n using the following rules: if n is even, n n/2 if n is odd, then n n + 1. 16

#include <stdio.h> #include <stdlib.h> int main() { int n = 7; printf ("n = %i\n", n); while (n > 1) { if ( (n % 2) == 0) { n = n / 2; } else { n = * n + 1; } printf ("n = %i\n", n); } } / * end while * / return 0; One can slightly modify the program, allowing the user to enter the number to be tested at runtime. For that goal, one should use the function scanf() which allows to read a number from the keyboard. The function scanf() need of format string to define what should be read and the address of a variable to define where the information should be stored. That is, the program modification shoud be: int n; / * Initialisation is no more needed * / printf ("Enter the number to be tested:"); scanf ("%i", &n); printf ("n = %i\n", n); / * already in the previous version * / The format string used here ("%i") says to the system that one should read a value of type int, that is an integer. 6. Exercise : stupid game One should write a two-user game. The first user enter a "secret" number between 1 and 100. The second number should guess this number. If the number entered by the second player is greater than the secret number, the program writes "Too big". If the number entered is smaller than the secret number, the program displays "Too small". The program loops until the second player has found the secret number. 17

6.4 Exercise: Von Neumann random number generator The idea of the Von Neumann random generator is very simple. One first choose a four digit number (that is between 1000 and 9999). The this number is squared. The "middle number" of this number is extracted as result of the random number generator and also used for the next step. Let us see that on an example: One choose as first number 124 The square of 124 is 1522756 The "middle number" can be either 5227 or 2275. Let us choose the first version. 5227 is squared, this gives 2721529 The "middle number" is 215 This algorithm is very simple to implement but does not provides a "good" list of random number. It is heavingly dependant of the seed (the first number choosed) and has a short sequence. Now you can implement this algorithm as exercise. 1 #include <stdio.h> 6 int number, counter=0; 7 8 printf ("Enter the seed of the sequence (four digit number): "); 9 scanf ("%i", &number); 10 11 if ( (number < 1000) (number > 9999) ) { 12 printf ("Number outside limit!!\n"); 1 return 0; 14 } 15 16 while (counter < 10) { 17 / * The number if first squared * / 18 number = number * number; 19 20 number = number / 100; 21 number = number % 10000; 22 printf ("Next number = %i\n", number); 2 counter++; 24 } 18

25 26 return 0; 27 } Try to use this program with the following seeds: 124, 1245, 2, 1111. 6.4.1 The standard unix random generator The standard unix library (used for C) use a different algorithm, which seems to be better (altough not perfect). 1 static unsigned long next = 1; 2 / * RAND_MAX assumed to be 2767 * / 4 int myrand(void) { 5 next = next * 110515245 + 1245; 6 return((unsigned)(next/6556) % 2768); 7 } 6.4.2 Mersenne Twister A new standard algorithm, called "Mersenne Twister" was developped by Makoto Matsumoto and Takuji Nishimura en 1997. This algorithm has a very long period (2 1997 1). The numbers produced as uniformely distributed on many dimension. If you need more information, you can read the article on wikipedia (Mersenne Twister). 6.4. Using the standard random generator for your program. To be able to use the standard random generator into your program, you shoud copy the file diva.h into your computer and modify the search path from Code::blocks. A simple program showing the use of this standard random generator can be: 1 #include <stdio.h> 4 #include "diva.h" 5 6 int main() 7 { 8 int value, counter=0; 9 10 init_random_generator(); 11 12 while (counter < 10) { 1 value = random_int(121); // 0 <= value < 121 19

14 15 printf("value is %i\n", value); 16 counter++; 17 } 18 } 20

7 Bitwise operations As previously seen, the operators & and allows respectively bitwise and and bitwise or. Theses operations are used to manipulates bits in a word (e.g. an integer value). 7.1 Exercise: Test bits Display all numbers between 1 and 127 where the bit b 4 is set. 7.2 Shift left and shift right To generate mask, one also need the two shift operator: >> shift right << shift left 7.2.1 Example of use 1 int x = 0x01 ; / * the value 1 in hexadecimal * / 2 int y = x << ; / * y contains 0x80 * / 4 int z = y >> 1; / * z contains 0x40 * / 7. Exercise: decimal to binary Write a program which ask the user to enter an integer value and then display the binary form of this number. 7.4 The for loop The most used loop in C is the for loop. This loop provides exactly the same functionality as the while, but in a more compact form. For the while loop one has 4 distinct operation to do: 1. declaration of the loop variable 2. initialisation of the loop variable. boolean expression (comparison) to define if the loop should be repeated once again 4. modification of the loop variable. For example: 21

1 int i; // Declaration of the loop variable 2... 4 i = 0; // Initialisation 5 while (i < END_VALUE) { // Boolean expression 6... // loop code here 7 8 i= i + 1; // Modification of the loop variable 9 } The for loop writes the last three steps (or all four steps if you a using a compiler implementing the C99 norm) like: 1 int i; 2 for (i = 0; i < END_VALUE; i=i+1) { 4... // loop code here 5 } If your compiler implement the C99 norm, you can even write: 1 for (int i = 0; i < END_VALUE; i=i+1) { 2... // loop code here } The standard configuration of Code::Blocks does not support the C99 norm. It must be added if needed. 7.4.1 Application of the for loop : trigo functions Let us show a little example of the use of the for loop with the programming of trigo functions. 1. Example 1 : the sine function The sine function of an angle x (given in radians) may be computed using the Taylor serie: sin(x) = x1 1! x! + x5 5! x7 x2n+1 +... + ( 1)n 7! (2n + 1)! +... Unfortunately, using this formulation, the computing of the sine may be difficult to implement in C. Therefore, before one can start to write the program, one first should modify slightly the formula. One can see that the Taylor serie of the sine function is an alternate sum of terms with the form x 2n+1 /(2n + 1)!. Thus, one can write: 22

t 1 = x1 1! t = x! = ( 1) t 1 t 5 = x5 5! = ( 1) t t 7 = x7 7! = ( 1) t 5... This array shows us a reccurence relation: x 2 2 x 2 4 5 x 2 6 7 t 1 = x1 1! = x (1) x 2 t i = ( 1) t i 2 (i 1) i for i and odd (2) sin(x) = t i () i One can then program this schema, using a for loop. Moreover, the number of term that should be computed depends on the desired precision, but also on the type of floating points used. Remember that the type float provide only 6 significant digits. If one need more precision, one can use the type double. 2. Exercise : the arcsin() function The arcsin function is the inverse of the sine function. The Taylor serie defining this function is: arcsin(x) = x + 1 2 x + 1 2 4 x5 5 + 1 5 2 4 6 x7 +... (4) 7 Question 1 : How can you rewrite the terms of this serie in a recurrent relationship? Question 2: write a C function that implement your algorithm and test it. What did you remark? 2

8 Arrays The notion of array has already be studied within the Matlab course. The idea behind array in C is very similar. Unfortunately, the syntax is different. One can enumerate theses diffences: 1. In C an array must be declared before it can be used. 2. The base type of the array (the type of the cells content) must be defined and cannot be changed.. The size must be defined when array is declared. Once the size is set, it cannot be changed (arrays are not dynamic) 4. The first element of a C array is indexed with value 0 5. The last element has index "size - 1" 6. To access array elements one should use brackets ("[]") and not parenthesis. The following example demonstrate the use of an array in a C program: 1 #include <stdio.h> 6 float array1[5]; // Five cells, base type = float 7 int array2[10]; // Ten cells, base type = int 8 int i; 9 10 array1[0] = 12.2; 11 array1[1] =.1415; 12 array1[2] = 42.12; 1 array1[] = 1.2e7; 14 array1[4] = 12; // Last cell has index size-1 = 4 15 16 for (i = 0; i < 10; i=i+1) { // i takes value 0 to 9 17 array2[i] = i * i * i; 18 } 19 20 for (i = 0; i < 10; i++) { 21 printf ("value of cell %i is %i\n", i, array2[i]); 22 } 2 return 0; 24 } 24

8.1 Bubble sort algorithm There is a lot a different sorting algorithms. Here one will study one of the simplest. It is called bubble sort. Let us define a random filled array of integer. For example: 0 1 2 4 12 2 7 42 24 The algorithm say that one should compare content of cell of index i with content of cell of index i+1. If the first is smaller than the second, one should swap the content of the two cells. In the example above, the first swap occurs between cell 1 and 2. Which will give: 0 1 2 4 12 7 2 42 24 The next swap would be between cells and 4. Afte one pass, one has: 0 1 2 4 12 7 2 24 42 The array is not sorted, but, one can see that the biggest value (42) is already at the right place. Moreover, the lightest element has moved for one position left. 25

9 Appendix 9.1 C reserved words 9.2 References auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while 1. The Rosetta code, a web site showing an 26