Functions in C. Consider #include main() { int i; for(i=1; i <= 5; i++) { printf("%d ", i*i); } for(i=1; i <= 5; i++) { printf("%d ", i*i); } return 0;

Slides:



Advertisements
Similar presentations
Intermediate Code Generation
Advertisements

Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Lecture 1 The Basics (Review of Familiar Topics).
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
CPS120: Introduction to Computer Science Lecture 8.
CSC 107 – Programming For Science. Announcements  Textbook available from library’s closed reserve.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
The Java Programming Language
Computer Science Department Relational Operators And Decisions.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
What does a computer program look like: a general overview.
Lecture #5 Introduction to C++
PHY 107 – Programming For Science. Announcements  Slides, activities, & solutions always posted to D2L  Note-taking versions before class, for those.
Fundamental Programming: Fundamental Programming Introduction to C++
CPS120: Introduction to Computer Science Decision Making in Programs.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
These notes were originally developed for CpSc 210 (C version) by Dr. Mike Westall in the Department of Computer Science at Clemson.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Introduction to Java Java Translation Program Structure
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Boolean Data Lesson CS1313 Fall Boolean Data Outline 1.Boolean Data Outline 2.Data Types 3.C Boolean Data Type: char or int 4.C Built-In Boolean.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CSI 3125, Preliminaries, page 1 Data Type, Variables.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
CPS120: Introduction to Computer Science Variables and Constants.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Fundamental Programming Fundamental Programming More Expressions and Data Types.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
A Sample Program #include using namespace std; int main(void) { cout
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
Week 4 – Functions Coding Functions. Purpose of Coding Functions A function is written to perform a well-defined task; rather than having all logic in.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
C++ Lesson 1.
Control Structures I Chapter 3
The Machine Model Memory
Types CSCE 314 Spring 2016.
Selection (also known as Branching) Jumail Bin Taliba by
EGR 2261 Unit 4 Control Structures I: Selection
Multiple variables can be created in one declaration
Variables A piece of memory set aside to store data
Haskell.
Pre-processor Directives
Control Statement Examples
Lecture 8.
Introduction to C Programming
C++ Data Types Data Type
CPS120: Introduction to Computer Science
Chapter 2: Introduction to C++.
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Understand the interaction between computer hardware and software
Primitive Types and Expressions
C Language B. DHIVYA 17PCA140 II MCA.
Presentation transcript:

Functions in C

Consider #include main() { int i; for(i=1; i <= 5; i++) { printf("%d ", i*i); } for(i=1; i <= 5; i++) { printf("%d ", i*i); } return 0; }

Life would be easier If we could call a function to do the same Consider the following

void Print_Squares(void) { int i; for(i=1; i <=5; i++) { printf("%d ", i*i); }

Our program now is #include void Print_Squares(); main() {Print_Squares(); Print_Squares(); return(0); } void Print_Squares(void) { int i; for(i=1; i <=5; i++) { printf("%d ", i*i); }

The syntax of a function is

type name(type1 arg1, type2 arg2,...) { /* code */ }

Example functions int square(int x) { int square_of_x; square_of_x = x * x; return square_of_x; } Returns the square of an integer

Another float doubleit(float x) { return x*2.0; }

Program syntax Header files e.g. #include Function declaration i.e. a function header Syntax type function name( Argument list); Sometimes argument list is omitted, sometimes not main() Function call i.e. function name followed by legitimate arguments in parentheses e.g. sin(30); After program body full function definition

Example //Header files and function declaration #include float doubleit(float x) // or float doubleit() //Next program body

Program Body main() { float y; y= doubleit(2.0); printf(“value of y is now %f”,y); } //This is followed by function definition

float doubleit(float x) { return x*2.0; }

Note Result of function is attached by return to function type indicated by type name(type1 arg1, type2 arg2,...) { /* code */ }

Functions and Truth Values

Boolean Types In computer science, the Boolean or logical data type is a data type, having two values (usually denoted true and false), intended to represent the truth values of logic and Boolean algebra. It is named after George Boole, who first defined an algebraic system of logic in the mid 19th century.

Boolean types in programming languages In programming languages that have a built-in Boolean data type, such as Pascal and Java, the comparison operators such as '>' and '≠' are usually defined to return a Boolean value. Also, conditional and iterative commands may be defined to test Boolean-valued expressions.programming languagesPascalJavacomparison operatorsconditionaliterative commands

C and Boolean Data Types Languages without an explicit Boolean data type, like C90 and Lisp, may still represent truth values by some other data type. C uses an integer type, where relational expressions like i > j and logical expressions connected by && and || are defined to have value 1 if true and 0 if false, whereas the test parts of if, while, for, etc., treat any non-zero value as true. Indeed, a Boolean variable may be regarded (and be implemented) as a numerical variable with a single binary digit (bit), which can store only two values.

Boolean Types in C after 1999 i.e. Version C99 The initial standards for the C language (1972) provided no Boolean type; and, to this day, Boolean values are commonly represented by integers (ints) in C programs.C Some of its dialects, like C99 and Objective-C, provide standard definitions of a Boolean type as an integer type and macros for "false" and "true" as 0 and 1, respectively.C99Objective-C

NOTE: There is NO Boolean type in C -- you should use char, int or (better) unsigned char. Unsigned can be used with all char and int types.

Boolean Functions Boolean functions are functions that return either TRUE or FALSE. Until recently, since the C-language did not contain any data types to represent a Boolean value., programmers resorted to defining TRUE and FALSE as preprocessing declarations of one and zero.

Integers and Bools The integer one was used to represent a Boolean value of TRUE, while an integer value of zero was used to represent a FALSE.

typedef enum { false = 0, true = 1 } bool ; The Box 1 program demonstrates a simple example of using a boolean return value from a function to test the passed argument is odd. The BOOL declaration is used to represent a boolean datatype - really an integer datatype.

Box1 Box 1 // Header Files usually come first #include // Preprocessing statements are // usually written after Header Files #define TRUE 1 #define FALSE 0 #define BOOL int // Function returns TRUE, if arg is odd BOOL IsOdd(int arg);

Main ///////////////////////////////////////////// // main function int main() { int num; printf("Enter a Number: "); scanf("%d",&num); // use Boolean Function if ( IdOdd(num) == TRUE) { printf("%d is Odd\n",num); } else { printf("%d is Even\n",num); } return 0; } /////////////////////////////////////////////

// IsOdd Function BOOL IsOdd(int arg) { if(arg%2==0) { return FALSE; } else { return TRUE; } }

Note If you noticed the program, the preprocessing define statements have symbols all of uppercase (ie TRUE, FALSE, BOOL). Preprocessing define statements make programs more readable. But, they can create subtle errors in the compile phase. For instance, suppose that the first define statement in the above program was changed to #define TRUE 0;. Now, the symbol TRUE would be always translated into 0; everywhere where the symbol is used. This leads to many compiler errors where ever the symol TRUE is in your code..

Most C/C++ programmers always used uppercase letters for all symbols that are in #define statements. If a code gets compiler errors on statements containing uppercase symbols, then it may be due to preprocessing #define statement errors. Notice, that the if-else statement in the main function of the Box 1 program has a conditional test of IsOdd(num)==TRUE. This seems to a be a waste, as the condition can be written simply as IsOdd(num).

Since the function IsOdd returns a non zero value, the condition is effectively true. There seems to be no need to perform a second equality test. But, by introducing the test, the code is more easily read, and errors are cought more easily. Some programmers often do not put this equality test into Boolean functions.

Note BOOL IsOdd(int arg) { if(arg%2==0) { return FALSE; } else { return TRUE; } }

Is the same as int IsOdd(int arg) { if(arg%2==0) { return 0; } else { return 1; } }