BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$617$
|
|
- Cody Robinson
- 5 years ago
- Views:
Transcription
1 BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$617$ Instructors:AykutErdem,ErkutErdem,FuatAkal TAs:YasinSahin,AhmetSelmanBozkir,GultekinIsik, OguzhanGuclu Today# Func/ons# ParameterLists ReturnValues Prototypes Variable#Scopes# BlockStructure GlobalandLocalVariables Recursion# 1 2 Today# Func/ons# Defini@ons Invoca@on ParameterLists ReturnValues Prototypes Variable#Scopes# BlockStructure GlobalandLocalVariables Sta@cVariables Recursion# Introduc/on# Structured$ProgrammingisaproblemHsolvingstrategyanda programmingmethodologythatincludesthefollowingtwo guidelines: Theflowofcontrolinaprogramshouldbeassimpleas possible. Theconstruc@onofaprogramshouldembodytop1down$design. 3 4
2 TopBdown#Design# Top1down$design(stepwise$refinement,ordivide$and$conquer) consistsofrepeatedlydecomposingaproblemintosmaller problems. Aprogramisconstructedfromsmallerpieces(components, modules) Eachpieceismoremanageablethantheoriginalprogram Func/ons# Bossasksworkertocompletetask 5 6 Math#Library#Func/ons# Math#Library#Func/ons# Mathlibraryfunc@ons performcommonmathema@calcalcula@ons #include#<math.h># # Formatforcallingfunc@ons Func/onName(argument);# Ifmul@plearguments,usecommaHseparatedlist y = sqrt( ); Callsfunc@onsqrt,whichreturnsthesquarerootofitsargument ArgumentsmaybeanyrHvalue(constants,variables,or expressions) Func/on#Header# intabs(intnum) doublefabs(doublenum) doublepow(doublex,doubley) intrand(void) doublesin(doubleangle) doublecos(doubleangle) doublesqrt(doublenum) Descrip/on# Returnstheabsolutevalueofaninteger element Returnstheabsolutevalueofadoubleprecision element. Returnsxraisedtothepowerofy. Returnsarandomnumber Returnsthesineofanangle;theangleshouldbe inradius. Returnsthecosineofanangle;theangleshould beinradius. Returnsthethesquarerootofadouble 7 8
3 Math#Library#Func/ons#(Example)# Howtocodesquarerootof(x1#B#x2) 2 #+#(y1#b#y2) 2# byusing math.hlibraryfunc@ons? a = x1 x2; b = y1 y2; c = pow(a, 2) + pow(b, 2); d = sqrt(c); Func/ons# WehavealreadywriYen/calledsomefunc@onsbefore. /* Welcome to BBM 101 */ int main(void) { printf( Hello world\n ); mainisafunc@onthatmustexistineverycprogram. prinuisalibraryfunc@onwhichwehavealreadyusedinourprogram. Let s create and call our own functions now 9 10 Func/on#Defini/on# Syntax type name (parameters){ variables; statements; nameisthenameofthefunc@on typeisthetypeofthereturnedvaluebythefunc@on voidmeansthefunc@onreturnsnothing Func@onsreturnintvalueifnothingisspecified parametersspecifythetypesandnamesoftheparameters separatedbycomma Func/on#Returning#a#Value#(Example)# Let sdefineafunc@ontocomputethecubeofanumber: int cube ( int num ) { int result; result = num * num * num; return result; Thisfunc@oncanbecalledas: n = cube(5); 11 12
4 void#func/on#(example)# Func/on#Invoca/on# /* function definition */ void print_message(void){ printf( A message for you: ); printf( Have a nice day\n ); int main(void){ /* function invocation */ print_message(); Aprogramismadeupofoneor morefunc@ons,oneofthembeing main(). Whenaprogramencountersa func@on,thefunc@oniscalledor invoked. A\erthefunc@ondoesitswork, programcontrolispassedbackto thecallingenvironment,where programexecu@oncon@nues. Function1(){ return; Function2(){ return; int main(){ Function1(); Function2(); return; The#return#Statement# Whenareturnstatementisexecuted,theexecu@onofthe func@onisterminatedandtheprogramcontrolisimmediately passedbacktothecallingenvironment. Ifanexpressionfollowsthekeywordreturn,thevalueofthe expressionisreturnedtothecallingenvironmentaswell. Areturnstatementcanbeoneofthefollowingtwoforms: return; return expression; Examples:# # return; return 1.5; return result; return a+b*c; return x < y? x : y; The#return#Statement#(Example)# Defineafunc@ontocheckifaskedyearisaleapyear int IsLeapYear(int year){ return ( ((year % 4 == 0) && (year % 100 = 0)) Thisfunc@onmaybecalledas: if (IsLeapYear(2005)) else (year % 400 == 0) ); printf( 29 days in February.\n ); printf( 28 days in February.\n ); 15 16
5 Example:#Find#minimum#of#two#integers# Func/on#Parameters# int min(int a, int b){ if (a < b) return a; else return b; int main (void){ int j, k, m; printf( Input two integers: ); scanf( %d %d, &j, &k); m = min(j, k); Input two integers: 11 3 The mininum is 3. Afunc@oncanhavezeroormoreparameters. Theformal$parameter$list$indeclara@onheader int f (int x, double y, char c); Theactual$parameter$list$infunc@oncalling: value = f(age, 100*score, initial); Parameter variables and their types are declared here. Cannot be told what their types are from here. printf( \nthe minimum is %d.\n, m); Rules#for#Parameter#Lists# Thenumberofparametersintheactualandformalparameter listsmustbeconsistent. Parameterassocia@onisposiGonal:$thefirstactual$parameter matchesthefirstformal$parameter,thesecondmatchesthe second,andsoon. CallBbyBValue#Invoca/on# Eachargumentisevaluated,anditsvalueisusedlocallyinplace ofthecorrespondingformalparameter. Ifavariableispassedtoafunc@on,thestoredvalueofthat variableinthecallingenvironmentwillnotbechanged. InC,allcallsarecallHbyHvalue. Actual$parametersandformal$parametersmustbeof compa@ble$data$types. Actual$parametersmaybeavariable,constant,anyexpression matchingthetypeofthecorrespondingformalparameter
6 Func/on#Call# Func/on#Call#(Example)# # t = cubesum(i); j = cubesum(t); isequivalentto j = cubesum(cubesum(i)); int compute_sum (int n){ int sum = 0; for ( ; n > 0; --n) sum += n; printf( %d, n); return sum; int main (void){ int n = 3, sum; printf( %d, n); sum = compute_sum(n); printf( %d, n); printf( %d, sum); Example:#Find#maximum#of#three#integers# int maximum(int a, int b, int c){ int max = a; if (b > max) max = b; if (c > max) max = c; return max; int main (void){ int j, k, l, m; printf( Input three integers: ); scanf( %d %d %d, &j, &k, &l); Input three integers: The maxinum is 11. Func/on#Prototypes# Generalformforafunc@onprototypedeclara@on: return_type function_name (parameter-type-list) Usedtovalidatefunc@ons Prototypeonlyneedediffunc@ondefini@oncomesa\eruseinprogram Thefunc@onwiththeprototype int maximum( int, int, int ); #(Takesin3ints,returnsanint) printf( \nthe maximum is %d.\n, maximum(j, k, l)); 23 24
7 Using#Func/on#Prototypes# Today# int max (int a, int b){... int min (int a, int b){... int main(void){... min(x,y); max(u,v);... = int max(int,int); int min(int,int); int main(void){ min(x,y); max(u,v);... int max (int a, int b){... int min (int a, int b){... Func/ons# Defini@ons Invoca@on ParameterLists ReturnValues Prototypes Variable#Scopes# BlockStructure GlobalandLocalVariables Sta@cVariables Recursion# Block#Structure#and#Variable#Scope# int total, count; int main(int argc, const char * argv[]){ total = count = 0; { int count = 0; while (1) { if (count > 10) break; total += count; count++; printf("%d\n", count); count++; printf("%d\n", count); Global$countvariableis validinthewholeprogram. Local$countvariableis onlyvalidinthered blockhere External#Variables# Localvariablescanonlybeaccessedinthefunc@oninwhich theyaredefined. Ifavariableisdefinedoutsideanyfunc@onatthesamelevelas func@ondefini@ons,itisavailabletoallthefunc@onsdefined belowinthesamesourcefile "externalvariable Global#variablesareexternalvariablesdefinedbeforeany func@ondefini@on Theirscopewillbethewholeprogram 28
8 Local#Variables# void func1 (void){ int i = 5; printf( %d\n, i); i++; printf( %d\n, i); int main (void){ int i = 5; printf( %d \n, i); func1(); printf( %d \n,i); Sta/c#Variables# Avariableissaidtobesta/cifitisallocatedstorageatthe beginningoftheprogramexecu@onandthestorageremains allocatedun@ltheprogramexecu@onterminates. Externalvariablesarealwayssta@c. Withinablock,avariablecanbespecifiedtobesta@cbyusing thekeywordsta@cbeforeitstypedeclara@on: static type variable-name; Variabledeclaredsta@ccanbeini@alizedonlywithconstant expressions(if#not,#its#default#value#is#zero) Sta/c#Variables#(Example)# Sta/c#Variables#(ExampleBIni/al#Value)# void incr(void); int main(void){ int i; void incr(void); for (i=0; i<3; i++) incr(); void incr(void){ static int static_i = 0; printf( static_i = %d\n, static_i++); A#sta/c#variable#inside#a# func/on#keeps#its#value# between#invoca/ons.# Output: static_i = 0 static_i = 1 static_i = 2 31 void put_stars(int n){ static int static_n; int i; for (i=0; i<static_n; i++) printf( ); for (i=0; i<n; i++) printf( * ); printf( \n ); static_n+= n; int main(void){ put_stars(3); put_stars(2); put_stars(3); Output: *** ** *** 32
9 Today# Func/ons# ParameterLists ReturnValues Prototypes Variable#Scopes# BlockStructure GlobalandLocalVariables Recursion# Recursion# Recursionistheprocesswherebyaconstructoperatesonitself. thefirstone Recursionisaprogrammingtechniquethatnaturally implementsthedividehandhconquerproblemsolving methodology Recursive#Func/on# #How1does1it1Look1like?1 Computes#the#factorial#of#a#nonnega/ve#integer.# int fact(int n) { if (n == 0) return (1); else return (n * fact(n-1)); The#func/on#fact#calls#itself.# We#will#see#how#it#really#works#soon# # The#Nature#of#(direct)#Recursion# One or more simple cases of the problem(called the stopping$ cases$or$base$case)haveasimplenonhrecursivesolu@on. Theothercasesoftheproblemcanbereduced(using$recursion) toproblemsthatareclosertostoppingcases. Eventually the problem can be reduced to stopping cases only, whicharerela@velyeasytosolve. 1In1general:1 if(stopping$case) $$$$$$solve$it else$ $$$$$$reduce$the$problem$using$recursion 35 36
10 Recursive#Example#B#Palindrome# Apalindrome#isaword,phrase,numberorothersequenceof e.g.,radar,$level,$rotator,$ Steponnopets, EyEdipAdanadapideye, ,etc. Recursive#Defini/on: Ifthestringhasnoelements,thenit'sapalindrome. Ifthestringhasonlyoneelement,thenit'sapalindrome. Iftheelementsintheendpoints(thefirstandlastelements)arethesame, andtheinternalleyersareapalindrome,#thenit'sapalindrome. Four#Criteria#of#a#Recursive#Solu/on# Atestforthebasecaseenablestherecursivecallstostop. Theremustbeacaseoftheproblem(knownasbase$caseorstopping$case)that ishandleddifferentlyfromtheothercases(withoutrecursivelycallingitself.) Inthebasecase,therecursivecallsstopandtheproblemissolveddirectly. Eventually,oneofthesmallerproblemsmustbethebasecase. Themannerinwhichthesizeoftheproblemdiminishesensuresthatthebase caseiseventuallyisreached Factorial#Func/on# #Itera:ve1Defini:on1 Factorial#Func/on# #Recursive1Defini:on1 n=n*(nh1)*(nh2)* *2*1 0=1 Itera/ve#Defini/on#in#C: fval = 1; for (i = n; i >= 1; i--) fval = fval * i; for$any$integer$n$>$0$ Todefinenrecursively,nmustbedefinedintermsofthe factorialofasmallernumber. Observa@on(problemsizeisreduced): n=n*(nh1) Basecase"0#=#1# # Wecanreachthebasecase,bysubtrac@ng1fromnifnisa posi@veinteger. 1Recursive1Defini:on:1 $$$$n$=$1$ $ $if$n$=$0$ $$$$n$=$n*(n11)$ $if$n$>$0$ 39 40
11 Revisi/ng#the#Recursive#Factorial#Func/on# Defini/on#in#C1 /* Computes the factorial of a nonnegative integer. Precondition: n must be greater than or equal to 0. Postcondition: Returns the factorial of n; n is unchanged.*/ int fact(int n) { if (n == 0) return (1); else return (n * fact(n-1)); How#does#it#Compute?# printf( %d, fact (3)); 6# return#3#*#fact(2)# ###3#*#2## return#2#*#fact(1)# ###2#*#1## return#1#*#fact(0)# ###1#*#1# # return#1# Thisfactfunc@onsa@sfiesthefourcriteriaofarecursivesolu@on.# Tracing#a#Recursive#Func/on# Astackisusedtokeeptrackoffunc@oncalls. Wheneveranewfunc@oniscalled Foreachfunc@oncall,anac:va:on1record1(AR)iscreatedonthestack. ARconsistsofthefunc@on sparametersandlocalvariablesarepushed ontothestackalongwiththememoryaddressofthecallingstatement (returnpoint). Totracearecursivefunc@on,thebox1methodcanbeused. Theboxmethodisasystema@cwaytotracetheac@onsofarecursive func@on. Theboxmethodillustrateshowcompilersimplementrecursion. Eachboxintheboxmethodroughlycorrespondstoanac@va@onrecord. The#Box#Method# Labeleachrecursivecallinthebodyoftherecursivefunc@on. Theselabelshelpustokeeptrackofthecorrectplacetowhichwe mustreturna\erafunc@oncallcompletes. A\ereachrecursivecall,wereturntothelabeledloca@on,and subs@tutethatrecursivecallwithreturnedvalue. if (n ==0) else return (1); return (n * fact(n-1) ) A 43 44
12 The#Box#Method#(cont d.)# itslocalenvironment. Eachboxcontains: Thevaluesofthearguments slocalvariables Aplaceholderforthevaluereturnedfromeachrecursivecallfromthe currentbox(labelinthepreviousstep). The#Box#Method#(cont d.)# processtothefirstbox. Thendrawanarrowtoanewboxcreateda\erarecursivecall,puta labelonthatarrow. printf( %d, fact (3)); A The#Box#Method#(cont d.)# A\eranewboxiscreated,westarttoexecutethebodyofthe func@on. Onexi@ngafunc@on,crossoffthecurrentboxanfollowits arrowbacktotheboxthatcalledthefunc@on. Thisboxbecomesthecurrentbox. Subs@tutethevaluereturnedbythejustHterminatedfunc@oncallinto theappropriateiteminthecurrentbox. Con@nuetheexecu@onfromthereturnedpoint. Box#Trace#of#fact(3)1 Theini@alcallismade,andthefunc@onfactbeginsexecu@on. AtpointA,arecursivecallismade,andthenewinvoca@onoffactbeginsexecu@on. A AtpointA,arecursivecallismade,andthenewinvoca@onoffactbeginsexecu@on. A A 47 48
13 Box#Trace#of#fact(3)#(cont d.)# Box#Trace#of#fact(3)#(cont d.)# A A A Thisisthebasecase,sothisinvoca@onoffactcompletes. A A Thefunc@onvalueisreturnedtothecallingbox,whichcon@nuestheexecu@on. A A A Thecurrentinvoca@onoffactcompletes. A A A A 49 Thefunc@onvalueisreturnedtothecallingbox,whichcon@nuestheexecu@on. A Thecurrentinvoca@onoffactcompletes. A Thefunc@onvalueisreturnedtothecallingbox,whichcon@nuestheexecu@on. Thecurrentinvoca@onoffactcompletes. Thevalue6isreturnedtotheini@alcall. 50 Example:#Find#the#reverse#of#an#input#string# Trace#of#reverse(3)1 /* reads n characters and prints them in reverse order. */ void reverse(int n){ char next; if (n == 1) { /* stopping case */ scanf("%c", &next); printf("%c", next); else { scanf("%c", &next); reverse(n-1); printf("%c", next); return; int main(){ printf("enter a string: "); reverse(3); printf("\n"); reverse(3); /* Assume input is abc */ n=3 3 <= 1? false read next : a reverse(2) write a return n=2 2 <= 1? false read next : b reverse(1) write b return n=1 1 <= 1? true read next : c write c return 51 52
14 Example:#Fibonacci#Sequence# Itisthesequenceofintegers: t 0 t 1 t 2 t 3 t 4 t 5 t Eachelementinthissequenceisthesumofthetwopreceding elements. Thespecifica@onofthetermsintheFibonaccisequence: $ $$ $n $ $ifn$is$0or1 $ $t n $=$ $ $ $ $t n11$ +$t n12 otherwise$ Example:#Fibonacci#Sequence# int fib(int n){ if (n < 2) return n; else return(fib(n-2) + fib(n-1)); Thisisanexampleofnon1linear$recursion.Becausetotalnumberofrecursive callsgrowsexponen@ally. fib(n11)expressionmustbeevaluatedcompletelybeforeitsvaluecanbe addedtotheexpressionfib(n12)whichmustalsobeevaluatedcompletely RecursiontreeisusefulintracingthevaluesofvariablesduringnonHlinear recursion Recursion#Tree#for#Fibonacci#Sequence# =>7thFibonacci fib(6) number fib(5)+fib(4) fib(4)+fib(3) fib(3)+fib(2) fib(3)+fib(2) fib(2)+fib(1) fib(2)+fib(1) fib(2)+fib(1) # fib(1)+fib(0) Example:#Fibonacci#Sequence#(Itera/ve# Version)# int Fib(int n) { int Prev1, Prev2, Temp, j; if (n==0 n== 1) return n; else { Prev1=0; Prev2 = 1; for (j=1; j <= n; j++){ Temp = Prev1 + Prev2; Prev2 = Prev1; Prev1 = Temp; return Prev1; 55 56
15 Recursion#vs.#Itera/on# naturalandlogicalwayofsolvingaproblem. Conflict:machineefficiencyversusprogrammerefficiency. andastack(andviceversa). 57
BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$7$
BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$7$ ykuterdem,erkuterdem,fuatkal Today#! Func/ons#! Defini4ons! Invoca4on! ParameterLists! ReturnValues! Prototypes! Variable#Scopes#! BlockStructure!
More informationBBM 101 Introduc/on to Programming I Fall 2013, Lecture 6-7
BBM 101 Introduc/on to Programming I Fall 2013, Lecture 6-7 Instructors: Aykut Erdem, Erkut Erdem, Fuat Akal TAs: Yasin Sahin, Ahmet Selman Bozkir, Gultekin Isik, Oguzhan Guclu 1 Today Func/ons Defini@ons
More informationBBM 101 Introduc/on to Programming I Fall 2014, Lecture 7. Aykut Erdem, Erkut Erdem, Fuat Akal
BBM 101 Introduc/on to Programming I Fall 2014, Lecture 7 Aykut Erdem, Erkut Erdem, Fuat Akal 1 Today Func/ons Defini4ons Invoca4on Parameter Lists Return Values Prototypes Recursion Recursion Induc4ve
More informationDetail from C Propaganda Poster // Reddit user TheBall BBM 101. Introduction to Programming I. Lecture #11 C Iterations, Functions, Multi-D Arrays
Detail from C Propaganda Poster // Reddit user TheBall BBM 101 Introduction to Programming I Lecture #11 C Iterations, Functions, Multi-D Arrays Erkut Erdem, Aykut Erdem & Aydın Kaya // Fall 2017 Last
More informationProgramming & Data Structure Laboratory. Arrays, pointers and recursion Day 5, August 5, 2014
Programming & Data Structure Laboratory rrays, pointers and recursion Day 5, ugust 5, 2014 Pointers and Multidimensional rray Function and Recursion Counting function calls in Fibonacci #include
More informationProgramming & Data Structure Laboratory. Day 2, July 24, 2014
Programming & Data Structure Laboratory Day 2, July 24, 2014 Loops Pre and post test loops for while do-while switch-case Pre-test loop and post-test loop Condition checking True Loop Body False Loop Body
More informationChapter 4 Functions By C.K. Liang
1 Chapter 4 Functions By C.K. Liang What you should learn? 2 To construct programs modularly from small pieces called functions Math functions in C standard library Create new functions Pass information
More informationHomework 2 Answers. Due Date: Monday, April 29, 2002, at 11:59PM Points: 100
Homework 2 Answers Due Date: Monday, April 29, 2002, at 11:59PM Points: 100 UNIX System 1. (10 points) What program is running as process #1? Type ps ax and look for the process with a PID of 1. Then look
More informationUNIT III (PART-II) & UNIT IV(PART-I)
UNIT III (PART-II) & UNIT IV(PART-I) Function: it is defined as self contained block of code to perform a task. Functions can be categorized to system-defined functions and user-defined functions. System
More informationAN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University
AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:
More informationFunctions. Arash Rafiey. September 26, 2017
September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic
More informationDynamic memory allocation
Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes
More informationC Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function
More informationArray Initialization
Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]
More informationFunctions. Chapter 5
Functions Chapter 5 Function Definition type function_name ( parameter list ) declarations statements For example int factorial(int n) int i, product = 1; for (i = 2; I
More informationSubject: Fundamental of Computer Programming 2068
Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find
More informationPointers and scanf() Steven R. Bagley
Pointers and scanf() Steven R. Bagley Recap Programs are a series of statements Defined in functions Can call functions to alter program flow if statement can determine whether code gets run Loops can
More informationC programming basics T3-1 -
C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of
More informationA PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions.
FUNCTIONS IN C A PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions. Big problems require big programs too big to be written
More informationFUNCTIONS OMPAL SINGH
FUNCTIONS 1 INTRODUCTION C enables its programmers to break up a program into segments commonly known as functions, each of which can be written more or less independently of the others. Every function
More informationControl Structure: Loop
Control Structure: Loop Knowledge: Understand the various concepts of loop control structure Skill: Be able to develop a program involving loop control structure 1 Loop Structure Condition is tested first
More informationUnit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.
1 What is user defined function? Explain with example. Define the syntax of function in C. A function is a block of code that performs a specific task. The functions which are created by programmer are
More informationCOMP s1 Lecture 1
COMP1511 18s1 Lecture 1 1 Numbers In, Numbers Out Andrew Bennett more printf variables scanf 2 Before we begin introduce yourself to the person sitting next to you why did
More informationb. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.
UNIT IV 1. Appropriately comment on the following declaration int a[20]; a. Array declaration b. array initialization c. pointer array declaration d. integer array of size 20 2. Appropriately comment on
More informationLecture 9 - C Functions
ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin
More informationStructures in C. C allows you to declare a struct. Once you do so, you can create variables of this type. Here is the general syntax:
Structures in C An array allows you to store related variables of the same type in the same essential structure. But what if you wanted to store related information in the same structure that was NOT of
More informationStructured Programming. Functions and Structured Programming. Functions. Variables
Structured Programming Functions and Structured Programming Structured programming is a problem-solving strategy and a programming methodology. The construction of a program should embody topdown design
More informationSOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques
SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques 1 Principles of Programming and Software Engineering 1 const CENTS_PER_DOLLAR = 100; void computechange(int dollarcost, int centscost, int& d,
More informationC/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)
C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 By the end of this lecture, you will be able to identify the
More informationC/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for
C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 1 By the end of this lecture, you will be able to identify
More informationChapter 5 C Functions
Chapter 5 C Functions Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt(
More informationPointers, command line arguments, Process control, and functions
Pointers, command line arguments, Process control, and functions Prof. (Dr.) K.R. Chowdhary, Director SETG Email: kr.chowdhary@jietjodhpur.ac.in webpage: http://www.krchowdhary.com Jodhpur Institute of
More informationC Overview Fall 2015 Jinkyu Jeong
C Overview Fall 2015 Jinkyu Jeong (jinkyu@skku.edu) 1 # for preprocessor Indicates where to look for printf() function.h file is a header file #include int main(void) printf("hello, world!\n");
More informationCS111: PROGRAMMING LANGUAGE II
CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A
More informationBBM 102 Introduction to Programming II
BBM 102 Introduction to Programming II Spring 2018 C Review Instructors: Dr. Cumhur Yiğit Özcan, Dr. Ali Seydi Keçeli, Dr. Aydın Kaya TAs: Selim Yılmaz, Bahar Gezici, Cemil Zalluhoğlu Today Introduction
More informationLecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions
Lecture 02 Summary C/Java Syntax Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 1 2 By the end of this lecture, you will be able to identify the
More informationCS101 Introduction to computing Function, Scope Rules and Storage class
CS101 Introduction to computing Function, Scope Rules and Storage class A. Sahu and S. V.Rao Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati Outline Functions Modular d l Program Inbuilt
More information& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.
Computer Programming and Utilization (CPU) 110003 G) Functions 1 What is user defined function? Explain with example. Define the syntax of function in C. A function is a block of code that performs a specific
More informationBBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal
BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3 Aykut Erdem, Erkut Erdem, Fuat Akal 1 Today Introduc/on to Programming Basic Concepts Developing Algorithms Crea
More informationChapter 8: Function. In this chapter, you will learn about
Principles of Programming Chapter 8: Function In this chapter, you will learn about Introduction to function User-defined function Formal and Actual Parameters Parameter passing by value Parameter passing
More informationLecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?
Lecture 16 Functions II they re back and they re not happy Daily Puzzle If it is raining at midnight - will we have sunny weather in 72 hours? function prototypes For the sake of logical clarity, the main()
More informationCS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) Class Teacher: Pralay Mitra Department of Computer Science and Engineering Indian Institute of Technology Kharagpur An Example: Random
More informationAnswer all questions. Write your answers only in the space provided. Full marks = 50
Answer all questions. Write your answers only in the space provided. Full marks = 50 1. Answer the following: [2+3+2+1=8 marks] a) What are the minimum and maximum numbers that can be represented in 10-bit
More informationFunctions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself
More informationFUNCTIONS. Without return With return Without return With return. Example: function with arguments and with return value
FUNCTIONS Definition: A is a set of instructions under a name that carries out a specific task, assigned to it. CLASSIFICATION of s: 1. User defined s (UDF) 2. Library s USER DEFINED FUNCTIONS Without
More informationn Group of statements that are executed repeatedly while some condition remains true
Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,
More informationTutorial 1: Introduction to C Computer Architecture and Systems Programming ( )
Systems Group Department of Computer Science ETH Zürich Tutorial 1: Introduction to C Computer Architecture and Systems Programming (252-0061-00) Herbstsemester 2012 Goal Quick introduction to C Enough
More informationBBM 101 Introduc/on to Programming I Fall 2014, Lecture 5. Aykut Erdem, Erkut Erdem, Fuat Akal
BBM 101 Introduc/on to Programming I Fall 2014, Lecture 5 Aykut Erdem, Erkut Erdem, Fuat Akal 1 Today Itera/on Control Loop Statements for, while, do- while structures break and con/nue Some simple numerical
More informationRecap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam
Multimedia Programming 2004 Lecture 2 Erwin M. Bakker Joachim Rijsdam Recap Learning C++ by example No groups: everybody should experience developing and programming in C++! Assignments will determine
More informationCS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015
CS 141 - Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015 You may take this test with you after the test, but you must turn in your answer sheet. This test has the following sections:
More informationME 172. C Programming Language Sessional Lecture 8
ME 172 C Programming Language Sessional Lecture 8 Functions Functions are passages of code that have been given a name. C functions can be classified into two categories Library functions User-defined
More informationFunctions. (transfer of parameters, returned values, recursion, function pointers).
Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value
More informationIt is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.
Functions A number of statements grouped into a single logical unit are called a function. The use of function makes programming easier since repeated statements can be grouped into functions. Splitting
More informationIPC144 - Introduction to Strings. array of characters is an array, each element of which has a character data type.
IPC144 - Introduction to Strings Agenda: 1 Review/Questions 2 Array of characters 3 Character Strings 4 Try it! 5 Homework Array of Characters array of characters is an array, each element of which has
More informationSOLUTION FOR FUNCTION. 1) Write a program to display Hello 10 times. Create user-defined function message().
SOLUTION FOR FUNCTION 1) Write a program to display Hello 10 times. Create user-defined function message(). #include #include void message(int); int i; for (i=1;i
More informationPointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables
Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable
More informationDepartment of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #06
Department of Computer Science & Engineering Indian Institute of Technology Kharagpur Practice Sheet #06 Topic: Recursion in C 1. What string does the following program print? #include #include
More informationEC 413 Computer Organization
EC 413 Computer Organization C/C++ Language Review Prof. Michel A. Kinsy Programming Languages There are many programming languages available: Pascal, C, C++, Java, Ada, Perl and Python All of these languages
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers
More informationCOP 3223 Introduction to Programming with C - Study Union - Fall 2017
COP 3223 Introduction to Programming with C - Study Union - Fall 2017 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................
More informationCHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.
More informationUnit III Functions. C functions can be classified into two categories, namely, library functions and user defined functions.
Unit III Functions Functions: Function Definition, Function prototype, types of User Defined Functions, Function calling mechanisms, Built-in string handling and character handling functions, recursion,
More informationTEST BDA24202 / BTI10202 COMPUTER PROGRAMMING May 2013
DEPARTMENT OF MATERIAL AND ENGINEERING DESIGN FACULTY OF MECHANICAL AND MANUFACTURING ENGINEERING UNIVERSITI TUN HUSSEIN ONN MALAYSIA (UTHM), JOHOR TEST BDA24202 / BTI10202 COMPUTER PROGRAMMING May 2013
More informationDecision Making and Loops
Decision Making and Loops Goals of this section Continue looking at decision structures - switch control structures -if-else-if control structures Introduce looping -while loop -do-while loop -simple for
More informationFunction. Mathematical function and C+ + function. Input: arguments. Output: return value
Lecture 9 Function Mathematical function and C+ + function Input: arguments Output: return value Sqrt() Square root function finds the square root for you It is defined in the cmath library, #include
More information'C' Programming Language
F.Y. Diploma : Sem. II [DE/EJ/ET/EN/EX] 'C' Programming Language Time: 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1(a) Define pointer. Write syntax
More informationECE264 Fall 2013 Exam 1, September 24, 2013
ECE264 Fall 2013 Exam 1, September 24, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.
More informationC: How to Program. Week /Mar/05
1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers
More informationScheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C
Sample Test Paper-I Marks : 25 Time:1 Hrs. Q1. Attempt any THREE 09 Marks a) State four relational operators with meaning. b) State the use of break statement. c) What is constant? Give any two examples.
More informationDecision Making -Branching. Class Incharge: S. Sasirekha
Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the
More information{C} Programming. Part 1/2 Basics Variables, Conditions, Loops, Arrays, Pointer basics
{C Programming Part 1/2 Basics Variables, Conditions, Loops, Arrays, Pointer basics Variables A variable is a container (storage area) to hold data. Eg. Variable name int potionstrength = 95; Variable
More informationCS-211 Fall 2017 Test 1 Version Practice For Test on Oct. 2, Name:
CS-211 Fall 2017 Test 1 Version Practice For Test on Oct. 2, 2017 True/False Questions... Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a)
More informationCharacters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,
Strings Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters, decimal digits, special characters and escape
More informationBBM 201 DATA STRUCTURES
BBM 201 DATA STRUCTURES Lecture 2: Recursion & Performance analysis 2018-2019 Fall System Life Cycle Programs pass through a period called system life cycle, which is defined by the following steps: 1.
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationProcedures, Parameters, Values and Variables. Steven R. Bagley
Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.
More informationSUHAIL T A
SUHAIL T A Functions A number of statements grouped into a single logical unit C pgm is a collection of functions Self contained pgm segment that carries out a specific task main is a special recognized
More informationToday s Learning Objectives
Today s Learning Objectives 15-123 Systems Skills in C and Unix We will Review ints and modular arithmetic Learn basic Data types and Formats How Conditionals and loops work How Arrays are defined, accessed,
More informationRecursion. So, just as you are allowed to call function B from within function A, you are ALSO allowed to call function A from within function A!
Recursion Definition: Any time the body of a function contains a call to the function itself. So, just as you are allowed to call function B from within function A, you are ALSO allowed to call function
More informationProgramming and Data Structures Mid-Semester - Solutions to Sample Questions Dept. of Computer Science and Engg. IIT Kharagpur Spring
Programming and Data Structures Mid-Semester - s to Sample Questions Dept. of Computer Science and Engg. IIT Kharagpur Spring 2015-16 February 15, 2016 1. Tick the correct options. (a) Consider the following
More informationWorksheet 4 Basic Input functions and Mathematical Operators
Name: Student ID: Date: Worksheet 4 Basic Input functions and Mathematical Operators Objectives After completing this worksheet, you should be able to Use an input function in C Declare variables with
More informationGovernment Polytechnic Muzaffarpur.
Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking
More informationC Overview Fall 2014 Jinkyu Jeong
C Overview Fall 2014 Jinkyu Jeong (jinkyu@skku.edu) 1 # for preprocessor Indicates where to look for printf() function.h file is a header file #include int main(void) { printf("hello, world!\n");
More information1. Basics 1. Write a program to add any two-given integer. Algorithm Code 2. Write a program to calculate the volume of a given sphere Formula Code
1. Basics 1. Write a program to add any two-given integer. Algorithm - 1. Start 2. Prompt user for two integer values 3. Accept the two values a & b 4. Calculate c = a + b 5. Display c 6. Stop int a, b,
More informationCSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion
CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion Consider the following recursive function: int what ( int x, int y) if (x > y) return what (x-y, y); else if (y > x) return what (x, y-x);
More informationFunctions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.
Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create
More informationFunction a block of statements grouped together, to perform some specific task
Function a block of statements grouped together, to perform some specific task Each program written in C / C++ includes at least one function with pre-defined name: main( ). In our previous programs, we
More informationThe detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.
Chapter 1. An Overview 1.1 Programming and Preparation Operating systems : A collection of special programs Management of machine resources Text editor and C compiler C codes in text file. Source code
More informationSOFTWARE Ph.D. Qualifying Exam Fall 2017
(i) (4 pts.) SOFTWARE Ph.D. Qualifying Exam Fall 2017 Consider the following C program. #include #define START 2 #define LIMIT 60 #define STEP 7 #define SIZE 3 int main(void) { int i = START,
More informationProgramming. Functions and File I/O
Programming Functions and File I/O Summary Functions Definition Declaration Invocation Pass by value vs. pass by reference File I/O Reading Writing Static keyword Global vs. local variables 2 Functions
More informationChapter 7 Functions. Now consider a more advanced example:
Chapter 7 Functions 7.1 Chapter Overview Functions are logical groupings of code, a series of steps, that are given a name. Functions are especially useful when these series of steps will need to be done
More informationCS113: Lecture 4. Topics: Functions. Function Activation Records
CS113: Lecture 4 Topics: Functions Function Activation Records 1 Why functions? Functions add no expressive power to the C language in a formal sense. Why have them? Breaking tasks into smaller ones make
More informationLecture 10: Recursive Functions. Computer System and programming in C 1
Lecture 10: Recursive Functions Computer System and programming in C 1 Outline Introducing Recursive Functions Format of recursive Functions Tracing Recursive Functions Examples Tracing using Recursive
More informationTutorial 6. Memory Addresses and Pointers. scanf() function. Perils of Pointers. Function Pointers. Declarations vs. Definitions
Tutorial 6 Memory Addresses and Pointers scanf() function Perils of Pointers Function Pointers Declarations vs. Definitions CS 136 Spring 2018 Tutorial 6 1 Memory Addresses and Pointers A pointer can be
More informationFundamentals of Programming Session 14
Fundamentals of Programming Session 14 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationStandard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing
Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion Copyright 2003 Scott/Jones Publishing Topics 19.1 Introduction to Recursion 19.2 The Recursive Factorial Function 19.3 The Recursive
More informationData Structures And Algorithms
Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:
More information1. The keyword main in C language is used for
1. The keyword main in C language is used for a. an user defined function *b. the first function to be executed in the program c. an user defined variable 2. The role of a C compiler is to translate a.
More informationECE264 Summer 2013 Exam 1, June 20, 2013
ECE26 Summer 2013 Exam 1, June 20, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it. I
More informationC-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga
C-Programming CSC209: Software Tools and Systems Programming Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Adapted from Dan Zingaro s 2015 slides. Week 2.0 1 / 19 What
More information