C++ Laboratory Instructor: Andrey Dolgin

Slides:



Advertisements
Similar presentations
For loops For loops are controlled by a counter variable. for( c =init_value;c
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
C Programming for engineers Teaching assistant: Ben Sandbank Home page:
Functions a group of declarations and statements that is assigned a name effectively, a named statement block usually has a value a sub-program when we.
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
Structure of a C program
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
Programming Functions. A group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a value A sub-program.
לולאות 02 יולי יולי יולי 1502 יולי יולי יולי 1502 יולי יולי יולי 15 1 Department of Computer Science-BGU.
Introduction to C Programming
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Programming Variables. Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.) They.
1 Agenda Administration Background Our first C program Working environment Exercise Memory and Variables.
C programming for Engineers Lcc compiler – a free C compiler available on the web. Some instructions.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Incremental operators Used as a short-hand i++ or ++i  ==  i = i + 1 i-- or --i  ==  i = i – 1 i += a  ==  i = i + a i -= a  ==  i = i - a i *=
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
CISC105 – General Computer Science Class 4 – 06/14/2006.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Numbers in ‘C’ Two general categories: Integers Floats
Chapter 4 C Program Control Part I
Chapter 2 - Introduction to C Programming
ICS103 Programming in C Lecture 3: Introduction to C (2)
Intro to C Tutorial 4: Arithmetic and Logical expressions
Functions Department of Computer Science-BGU יום רביעי 12 ספטמבר 2018.
Introduction to C Programming Language
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Control Structures Lecture 7.
Looping.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Introduction to CS Your First C Programs
פרטים נוספים בסילבוס של הקורס
C Programming Variables.
CS1100 Computational Engineering
Chapter 2 - Introduction to C Programming
פרטים נוספים בסילבוס של הקורס
Introduction to C Programming
Introduction to C Topics Compilation Using the gcc Compiler
Program Breakdown, Variables, Types, Control Flow, and Input/Output
Chapter 2 - Introduction to C Programming
Incremental operators
Lecture3.
Week 2 Variables, flow control and the Debugger
C Programming Getting started Variables Basic C operators Conditionals
WEEK-2.
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Chapter 2 - Introduction to C Programming
Functions Department of Computer Science-BGU יום שישי 26 אפריל 2019.
Variables in C Topics Naming Variables Declaring Variables
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

C++ Laboratory Instructor: Andrey Dolgin e-mail: phd_ie@yahoo.com Home page: http://www.cse.bgu.ac.il 20% exam, 80% assignments 3 assignments Don’t copy assignments Obligatory attendance on all labs

Computer Structure (inspired by the Matrix) Is computer clever? What about man? Memory 0100110 devices bus Processor 01+10

Language types Computers understand only machine language. Basically looks like a sequence of 1’s and 0’s. The computer does not understand C. Assembly – machine language with some text codes (still inconvenient). Interpreted languages – Java, Perl. The program is translated into machine language line by line during execution. Compiled languages – C, Pascal, Fortran. The program is translated into machine language before execution

High level languages vs. machine languages. Actually, binary instructions.

Why teach C? C is small (only 32 keywords). lots of C code are available (OS, editors, DB). C doesn’t change much. C is quick (nearly as fast as assembly). C is the basis for many languages (Java, C++). C is one of the easiest languages to learn.

Software Development Process Understand Problem Definition Generalize & Decompose the problem definition Develop Solution Algorithm Write the Code Test and Debug

Programming Process Use any text editor to write a program a.cpp Compile the program a.cpp->a.o C compiler will print error messages and abort Or produce an object file Link the program a.o+b.o+c.o->prog.exe linker will print error messages and abort Or produce an executable program Run the program prog

Our first C program Comments are good /* HelloWorld – An example program */ #include <stdio.h> int main(void) { printf(“Hello, world!\n”); return 0; } Preprocessor directive Includes C standard library main() means “start here” This is an instruction to the compiler to insert the contents of the file stdio.h to the program prior to compilation. This file contains information about the printf fuction. This tells the compiler we are about to define a function named main. main is a special function – it is where the program starts running. Note that all C statements end with a semicolon (;). This is a C statement. This statement calls a function called printf, which causes text to be printed on the screen. Yet another C statement. This one terminates the program and informs the operating system that it has ended successfully. Return 0 from main means our program finished without errors This is a comment – starts with a /* and ends with a */. Comments are used to explain the program to a human reader, and are ignored by the compiler. Curly braces indicate the beginning and end of a block of instructions. Specifically in this case – a function. Brackets define code blocks

Keywords of C we need Flow (6) – if, else, return, switch, case,default Loops (5) – for, do, while, break, continue Types (5) – int, float, double, char, void Structures (3) – struct, typedef, union Counting and sizing (2) – enum, sizeof Useful types (3) – unsigned, static, const “Don’t use me” keywords (1) – goto

Variables

Declaring variables in C Before using a variable, one must declare it. The declaration first introduces the variable type, then its name. When a variable is declared, its value is undefined.

Example Variable Declarations int i; char c; float f1, f2; float f1=7.0, f2 = 5.2; unsigned int ui = 0;

Variable naming rules Letters, digits, underscores CSE_8a a_very_long_name_that_isnt_very_useful fahrenheit First character cannot be a digit 8a_CSE is not valid! Case sensitive CSE_8a is different from cse_58

Data types in C char – a single byte character ‘A’. short int (or just short) – an integer number, usually 2 bytes (rarely used) 15 . int - an integer number – usually 4 bytes 12345. long int (or just long) – an integer number, 4 or 8 bytes (rarely used) 123456. float – a single precision real number – usually 4 bytes 0.0012. double – a double precision real number – usually 8 bytes 0.00000012. long double - a double precision real number – usually 8 bytes (rarely used) 0.00000000012. Signed vs. unsigned

Memory types Heap .&x .&y Stack x y Loads program in Code memory Loader start Loads program in Code memory CPU execute Takes each instruction and executes it storing new data values in Stack or Heap Code memory Heap .&x .&y Stack x y

printf and scanf printf – prints to the standard output (for example screen). Can also accept variables and print their values. scanf – gets values from the standard input (for example keyboard), and assigns them to variables.

printf can print variable values printf ("z=%d\n", z ); The sequence %d is a special sequence and is not printed! It indicates to printf to print the value of an integer variable written after the printed string.

scanf gets input from the user scanf("%lf", &var); This statement waits for the user to type in a double value, and stores it in the variable named ‘var’. The meaning of ‘&var’ is the address of the variable var in stack. To get 2 doubles from the user, use – scanf("%lf%lf", &var1, &var2);

prinft/scanf conversion codes A %<conversion code> in the printf/scanf string is replaced by a respective variable. %c – a character %d – an integer, %u – an unsigned integer. %f – a float %lf – a double %g – a nicer way to show a double (in printf) %% - the ‘%’ character (in printf)

Example /* Get a length in cm and convert to inches */ #include <stdio.h> int main(void) { double cm, inches; printf("Please enter length in centimeters: "); scanf("%lf",&cm); inches = cm / 2.54; printf("This is equal to %g inches\n", inches); return 0; }

Exercise Write a program that accepts as input - and outputs - The Dollar-Shekel exchange rate An integer amount of dollars and outputs - The equivalent amount in Shekels

Solution #include <stdio.h> int main(void) { double shekels, xchange; int dollars; printf("Enter the US$-NIS exchange rate: "); scanf("%lf", &xchange); printf("Enter the amount of dollars: "); scanf("%d", &dollars); shekels = dollars * xchange; printf("%d dollars = %g shekels\n", dollars, shekels); return 0; }

Char is also a number! A char variable is used to store a text character: Letters. Digits. Keyboard signs. Non-printable characters. But also small numbers (0 to 255).

ASCII (American Standard Code for Information Interchange) Every character is assigned a numeric code. ‘’ operator in C returns this code, ‘A’=65 ASCII code 0 (NULL character) is important. Note continuous sets of numbers, upper case and lower case characters. Generally, you don't care about the numbers. The ASCII table.

Example of char as both a character and a small number #include <stdio.h> int main(void) { char i = 'b'; printf("i as a character is %c\n", i); printf("i as an integer is %d\n", i); printf("The character after %c is %c\n", i, i + 1); return 0; }

Another example /* Get the position of a letter in the abc */ #include <stdio.h> int main(void) { char letter; printf("Please enter a lowercase letter\n"); scanf("%c", &letter); printf("The position of this letter in the abc is %d\n", letter-'a'+1); return 0; }

Exercise Write a program that accepts as input – and outputs – A lowercase letter and outputs – The same letter in uppercase (e.g., if the input is ‘g’, the output should be ‘G’)

Solution /* Convert a letter to uppercase */ #include <stdio.h> int main(void) { char letter; printf("Please enter a lowercase letter\n"); scanf("%c", &letter); printf("This letter in uppercase is %c\n", letter-'a'+’A’); return 0; }

Arithmetic operators An operator is an action (in our case, usually a mathematical one) performed on something (e.g. constants, variables). That “something” is called an operand. Common operators: Braces () Assignment = Addition + Subtraction - Multiplication * Division / Modulo %

Operations with different types For example - 3 + 4 = 7 3.0 + 4 = 7.0 3 / 4 = 3.0 / 4 = 0.75

Casting variables Sometimes it is desirable for a variable of one type to be considered as belonging to another in an operation We say the variable is cast to the new type. The casting operator is of the form – (type) For example, (float)i casts the variable i to a float.

Casting variables #include <stdio.h> int main(void) { int a=1, b=2; printf("%d / %d = %d\n", a, b, a/b); printf("%d / %d = %g\n", a, b, (float)a / b); return 0; }

Example – find what’s wrong #include <stdio.h> int main(void) { int a = 10; int b = 20; printf("The average of %d and %d is %d\n", a, b, (a + b) * (1 / 2)); return 0; }

Will this work? #include <stdio.h> int main(void) { int a = 10; int b = 20; printf ("The average of %d and %d is %d\n", a,b, (a + b)*(1.0 / 2)); return 0; }

Selection statements

Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection statements: if statement switch statement

Selection statements: if used to execute conditionally a statement or block of code. if (expression) statement If expression is true, statement is executed (what is true?). statement can be replaced by a block of statements, enclosed in curly braces.

An example /* This program displays the absolute value of a number given by the user */ #include <stdio.h> int main(void) { double num; printf("Please enter a real number: "); scanf("%lf", &num); if (num<0) num = -num; printf("The absolute value is %g\n", num); return 0; }

If-else statement if (expression) statement1 else statement2 if expression is true, statement1 is executed. if expression is false, statement2 is executed both statements can be (and very often are) replaced by blocks of statements (“compound statements”)

An example (fragment) int first, second, min; /* … */ if (first < second) { min = first; printf ("The first number is smaller than the second.\n"); } else min = second; printf ("The second number is smaller than the first\n"); printf("The smaller number is equal to %d\n", min);

True or false In C, every expression has a numeric value An expression is ‘true’ when its non-zero If it is zero, it is false Therefore, in the following – if (expression) statement statement is executed if expression is non zero.

Relational operators They are – A == B (Note the difference from A = B) A != B A < B A > B A <= B A >= B The value of logical expression is non-zero if it’s true, zero if it’s false

An example int a, b; printf("Enter two Numbers\n"); scanf("%d%d", &a, &b); if (a == b) { printf("The numbers equal %d\n", a); printf("The expression a == b is %d\n", a == b); } else printf("The numbers are not equal\n");

The assignment operator = The assignment operator is also an operator. Hence, expressions involving it have a numeric value This value equals to whatever appears on the right of the assignment operator For example – (x = 4) equals 4 (y = 0) equals 0

A very common mistake Very often a programmer might confuse between the equality operator and the assignment operator - if (x==4) … if (x=4) … The second is usually a mistake, but legal in C so the compiler doesn’t call it!

Logical operators Allows to evaluate two or more expressions - !A – ‘not’ - True when A is not, and vice versa. A && B – ‘and’ - True when both A and B are true A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true

Else-if if statements distinguish between exactly 2 cases and execute different code in each case The else-if construction allows for a multi-way decision

Else-if if (expression) statement else if (expression) else

An example if (grade >= 90) printf ("A\n"); else if (grade >= 80) printf ("B\n"); else if (grade >= 70) printf ("C\n"); else if (grade >= 60) printf ("D\n"); else printf ("F\n");

The ?: operator expr1 ? expr2 : expr3 If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated

The ?: operator #include <stdio.h> int main(void) { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); min = i<j ? i : j; printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }

The switch statement a multiway conditional statement similar to the if-else if-else "statement" allows the selection of an arbitrary number of choices based on an integer value switch (expression) {   case const-expr: statements   case const-expr: statements   …   default: statements }

That grade example again switch (grade/10) { case 10: case 9: printf ("A\n"); break; case 8: printf ("B\n"); case 7: printf ("C\n"); case 6: printf ("D\n"); default: printf ("F\n"); }

Give me a break when the switch transfers to the chosen case, it starts executing statements at that point it will “fall through” to the next case unless you “break” out it causes the program to immediately jump to the next statement after the switch statement

Riddle me this Suppose a program’s execution reaches the following line – scanf(“%d%c”, &i, &ch); And suppose the user input is – 100 b What will be the contents of i and ch? Answer i == 100 ch == ‘ ‘ (there’s a space in there)

Spaces in scanf One way to overcome this problem is to introduce a space before the %c – scanf(“%d %c”, &i, &ch); The space tells scanf to ignore all whitespace characters that come after the %d is read

Loops

Loops Used to repeat the same instruction(s) over and over again. C provides some flexible ways of deciding how many times to loop, or when to exit a loop. for, while, do-while loops.

While loops while (condition) { statement(s); } The statements are executed as long as condition is true When the condition is no longer true, the loop is exited.

Example - factorial #include <stdio.h> int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); i=1; while (i<=n) fact = fact*i; i++; } printf("the factorial is %d\n", fact); return 0; This is a counter Every iteration i is incremented by 1. Equivalent to i=i+1.

getchar getchar() gets a single character from the user. Requires including stdio.h Returns a non-positive number on failure. Similar to scanf. char c; c = getchar(); char c; scanf(“%c”, &c); ====

putchar putchar(‘char’) prints out the character inside the brackets. Requires including stdio.h Similar to printf. char c; putchar(c); char c; printf(“%c”, c); ====

Exercise Input – Output – Note – Two integers – A and B How many times A contains B This is the result of the integer division A/B Note – Do not use the division operator!

Solution #include <stdio.h> int main(void) { int a, b, res; printf("Please enter two numbers.\n"); scanf("%d%d", &a, &b); res = 0; while ( (res+1) * b <= a) res = res + 1; printf("%d / %d = %d", a, b, res); return 0; }

Break in a loop When break is encountered, the loop is exited regardless of whether the condition is still true. The program then continues to run from the first line after the while loop. If called within a nested loop, break breaks out of the inner loop only.

Continue When continue is encountered, the rest of the loop is ignored. The program then continues to run from the beginning of the loop. Rarely used. Can usually be replaced by an appropriate if-else statement.

For loops For loops are controlled by a counter variable. for( c =init_value;c<=fin_value;c+=increment_value) { loop body; } c is a incremented after every iteration (can also be decreased!) c is a counter.

For loops (cont.) Equivalent to while… Any for loop can be converted to while loop and vice versa But some applications are more natural to for, and others to while. If we want to perform something for a predefined number of times, better use for. If we just wait for something to happen (not after a certain number or iterations), better use while.

Incremental operators Used as a short-hand for incrementing (or decrementing) variables. i++ or ++i == i = i + 1 i-- or --i == i = i – 1 i += a == i = i + a i -= a == i = i - a i *= a == i = i * a i /= a == i = i / a

Prefix ++i and postfix i++ #include <stdio.h> int main(void) { int i=5; printf("i++=%d\n",i++); //i++=5 printf(“++i=%d\n",++i); //++i=7 return 0; }

Exercise Write a program that accepts a number from the user, and checks whether it is prime.

Solution (isprime.c) #include <stdio.h> int main(void) { int i, num; printf("enter a number\n"); scanf("%d", &num); for(i = 2 ; i < num; i++) if (num % i == 0) /* Then we know it's not a prime */ break; if (i < num) printf("%d is not a prime number!\n", num); else printf("%d is indeed a prime number!\n", num); return 0; }

Exercise Extend the former program so it accepts a number from the user, and prints out all of the prime numbers up to that number (Hint – gotta use nested loops here...)

Solution (listprimes.c) #include <stdio.h> int main(void) { int i, j, last; printf("enter a number\n"); scanf("%d", &last); for(i = 2; i <= last; i++) for(j = 2 ; j < i; j++) if (i % j == 0) break; if (j == i) printf("the number %d is prime\n", i); } return 0;

Exercise Write a program that prints an upside-down half triangle of *. The height of the pyramid is the input. ***** **** *** ** *

Solution #include<stdio.h> int main(void) { int i, j, size; printf(“Please enter a size:\n”); scanf(“%d”,&size); for (i = 1; i <= size; i++) for(j = i; j <= size; j++) printf("*"); printf("\n"); } return 0;

Exercise Change the former prime-listing program, so that is displays only the largest prime number which is smaller than or equal to the user’s input.

Solution 1 #include <stdio.h> int main(void) { int i, j, last; int found = 0; /* This indicates whether we found the largest prime */ printf("enter a number\n"); scanf("%d", &last); i = last; while (!found) /* Loop until we find our guy */ for(j = 2 ; j < i; j++) if (i % j == 0) break; if (j == i) /* If this is true then i is prime */ found = 1; else i--; } printf("The largest prime not larger than %d is %d.\n", last, i); return 0;

Solution 2 (with break) #include <stdio.h> int main(void) { int i, j, last; printf("enter a number\n"); scanf("%d", &last); for(i=last;i>1;i--) for(j = 2 ; j < i; j++) if (i % j == 0) break; if (j == i) /* i is prime. We found our guy */ } printf("The largest prime not larger than %d is %d.\n", last, i); return 0;

Do while loops do { statement(s) } while (expression); Similar to while loops Except the condition is evaluated after the loop body The loop body is always executed at least once, even if the expression is never true (equals zero)

Example – waiting for legal input #include <stdio.h> int main(void) { int i; printf("Please enter a positive number.\n"); do { scanf("%d", &i); if (i<=0) printf("That's not a positive number! Try again.\n"); } while (i<=0); /* The program continues.... */ return 0; }

Functions

Functions a group of declarations and statements that is assigned a name effectively, a named statement block usually has a value a sub-program when we write our program we always define a function named main inside main we can call other functions which can themselves use other functions, and so on…

Example - Square This is a function defined outside main #include <stdio.h> double square(double a) { return a*a; } int main(void) double num; printf("enter a number\n"); scanf("%lf",&num); printf("square of %g is %g\n",num,square(num)); return 0; This is a function defined outside main Here is where we call the function square

Why use functions? they can break your problem down into smaller sub-tasks easier to solve complex problems they make a program much easier to read and maintain abstraction – we don’t have to know how a function is implemented to use it generalize a repeated set of instructions we don’t have to keep writing the same thing over and over

Characteristics of Functions return-type name(arg_type1 arg_name1, arg_type2 arg_name2, …) { function body; return value; } int main(void) { … } double square(double a) { return a*a; }

Return Statement Return causes the execution of the function to terminate and usually returns a value to the calling function The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type) If no value is to be returned, the return-type of the function should be set to ‘void’

Factorial calculation example int main(void) { int num; printf("enter a number\n"); scanf("%d",&num); printf("%d!=%d\n",num,factorial(num)); return 0; } #include <stdio.h> int factorial(int n) { int i, fact = 1; for (i=2; i<=n; i++) fact *= i; return fact; }

A Detailed Example Write a program that receives a nominator and a denominator from the user, and displays the reduced form of the number. For example, if the input is 6 and 9, the program should display 2/3.

Example – solution (step I) #include <stdio.h> int main(void) { int n, d; printf("Please enter nominator and denominator: "); scanf("%d%d", &n, &d); Calculate n’s and d’s Greatest Common Divisor printf("The reduced form of %d/%d is %d/%d", n, d, n/gcd, d/gcd); return 0; }

Example – solution (step II) #include <stdio.h> int main(void) { int n, d, g; printf("Please enter nominator and denominator: "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form of %d/%d is %d/%d", n, d, n/g, d/g); return 0; }

Example – solution (step III) /* Returns the greatest common divisor of its two parameters. Assumes both are positive. The function uses the fact that the if r = mod(y, x) then the gcd of y and x equals the gcd of x and r. */ int gcd(int x, int y) { int tmp; while(x > 0) tmp = x; x = y % x; y = tmp; } return y;

The Great Void Sometimes there’s no reason for a function to return a value In these cases, the function return type should be ‘void’ If the ‘return’ keyword is used within such a function it exits the function immediately. No value needs be specified If the function receives no parameters, the parameter list should be replaced by ‘void’

Pass-by-value Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables A change to the value of an argument in a function body will not change the value of variables in the calling function

Scope of variables The scope of a variable is the boundaries within which it can be used in a program. Normally variables are local in scope - this means they can only be used in the function where they are declared. A variable declared within a function is unrelated to variables declared elsewhere, even if they have the same name Global variables can be declared , which can be used in any function. Global variables are a BAD PRACTICE.

Wrong way to do it int add_one(int b) { a=b+1; } int main(void) int a=34,b=1; add_one(b); printf("a = %d, b = %d\n", a, b); return 0;

Bad global variable use example #include<stdio.h> void printRow(int); int i, size; int main(void) { printf(“Please enter a size:\n”); scanf(“%d”,&size); for (i = 1; i <= size; i++) printRow(i); return 0; } void printRow(int length) for(i = length; i <= size; i++) printf("*"); printf("\n"); Variables here are global This program only prints ONE row of stars

Function Declaration Most software projects in C are composed of more than one file We want to be able to define the function in one file, and to use it in all files For this reason, the function must be declared in every file in which it’s called, before it’s called for the first time the declaration contains: the function name the data types of the arguments (their names are optional) the data type of the return value

Function Declaration #include <stdio.h> int factorial(int a); /* Function Declaration! */ int main(void){ int num; printf("enter a number\n"); scanf("%d",&num); printf("%d!=%d\n",num,factorial(num)); return 0; } int factorial(int a){ int i,b=1; for(i=1; i<=a; i++) b=b*i; return b;

Function Declaration stdio.h actually contains a large set of function declarations The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called

The math library A collection of mathematical functions Need to include the header file math.h (#include <math.h>) Use functions of the library, e.g. double s,p; s=sqrt(p); Declared in math.h : double sqrt ( double x );

The math library sin(x), cos(x), tan(x) asin(x), acos(x), atan(x) x is given in radians asin(x), acos(x), atan(x) log(x) sqrt(x) pow(x,y) – raise x to the yth power. ceil(x), floor(x) …and more