Comp111 Notes

Embed Size (px)

Citation preview

  • 8/3/2019 Comp111 Notes

    1/59

    Comp 111: Introduction to Programming

    Introduction to CC is a programming language which was developed at AT& Ts Bell laboratories in USA in 1972. It wasdesigned and written by Dennis Ritchie. The languages that existed before C are: -

    FORTRAN (FORmula TRANslation)

    ALGOL (ALGOrithmic Language)

    PL/1 (Programming Language 1) BASIC (Beginner's All-purpose Symbolic Instruction Code)

    PascalThe languages that supersede C are C++, C# and Java.

    Why Use C?In today's world of computer programming, there are many high-level languages to choose from, such asPascal, BASIC, and Java. But C stands apart from all these languages. This is due to its many desirablequalities. It is a robust language whose rich set of built-in functions and operators can be used to writeany complex logic program. The C language compiler combines the capabilities of a low level languagewith the features of a high level language. Therefore the language is suitable for writing both systemsoftware as well as business packages & other software. Many compilers available in the market written

    in C. Program written in C are very efficient and fast. This is due to its variety of data types and

    powerful operators. It is many time faster than BASIC. This helps developers in saving theirvaluable time.

    C is a powerful and flexible language which helps system developers to deliver various complextasks with ease. C is used for diverse projects as operating systems, word processors, graphics,spreadsheets, and even compilers for other languages.

    C is popular among professional programmers for programming, as a result, a wide variety of Ccompilers and helpful accessories are available.

    C is highly portable language. This means that a C program written for one computer system (anIBM PC, for example) can be run on another system (a DEC VAX system, perhaps) with little orno modification. Portability is enhanced by the ANSI standard for C, the set of rules for C

    compilers.

    Cs another striking feature is its ability to extend itself. A C program is basically a collection ofvarious function supported by C library (also known as header files). We can also add our ownfunctions to the C library. These functions can be reused in other applications or programs bypassing pieces of information to the functions, you can create useful, reusable code.

    Writing C program with user-defined functions makes program more simple and easy tounderstand. Breaking a problem in terms of functions makes program debugging, maintenanceand testing easier.

    As these features shows that C is an excellent choice for your first programming language. But what is C++? You might have heard this term C++ and the programming technique called Object-OrientedProgramming (OOP). Possibly you're wondering what the differences are between C and C++ andwhether you should learn C or C++.C++ is a superset of C, means that C++ is the new improved version of C for the latest programmingneeds. It contains everything C does, plus new additions for OOP concept. If you will learn C++ later,you will find that almost everything which you learnt in C is applicable in C++ too. In learning C, you arenot only learning one of today's most powerful and popular programming languages, but you are alsopreparing yourself for other similar programming languages.

    1

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    2/59

    Comp 111: Introduction to Programming

    Another language that has gotten lots of attention is Java for its OOP and portability. Java, just like C++,is based on C. If later you decide to learn Java, you will find that almost everything you learned about Capplies here.

    Characteristics of C

    We briefly list some of C's characteristics that define the language and also have lead to its popularity as aprogramming language. Naturally we will be studying many of these aspects throughout the course.

    Small size

    Extensive use of function calls

    Loose typing -- unlike PASCAL

    Structured language

    Low level (Bitwise) programming readily available

    Pointer implementation - extensive use of pointers for memory, array, structures and functions.C has now become a widely used professional language for various reasons.

    It has high-level constructs.

    It can handle low-level activities.

    It produces efficient programs.

    It can be compiled on a variety of computers.Its main drawback is that it has poor error detection which can make it off putting to the beginner.However diligence in this matter can pay off handsomely since having learned the rules of C we canbreak them. Not many languages allow this. This if done properly and carefully leads to the power of Cprogramming.

    C Programming Language

    Communicating with a computer involves speaking a language that is understandable to it. Thereforethere is a close analogy between learning English Language and learning C language. In English we firstlearn the alphabets, and then combine alphabets to form words which in turn are combined to formsentences and sentences are combined to form paragraphs.

    Learning C is similar and easier. Therefore we will learn the several building blocks of a program. Theseare: -

    Character set

    Constants, variables & keywords.

    Instructions

    ProgramCharacter Set

    The character set in C Language can be grouped into the following categories.

    i. Alphabetsii. Digitsiii. Special Characters

    iv. White SpacesWhite Spaces are ignored by the compiler until they are a part of string constant. White Space may beused to separate words, but are strictly prohibited while using between characters of keywords oridentifiers.C Character-Set Table

    Letters Digits

    2

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    3/59

    Comp 111: Introduction to Programming

    Upper Case A to Z 0 to 9

    Lower Case a to z.

    Special Characters

    White Space

    i. Blank Spaceii. Horizontal Tab

    iii. Carriage Return

    iv. New Linev. Form Feed

    The alphabets, numbers and special symbols when properly combined form constants, variables andkeywords.

    CONSTANTS

    3

    Pre

    pared by Z. Mwololo

    , .Comma & .Ampersand

    . .Period ^.Caret

    ; .Semicolon * .Asterisk

    : .Colon - .Minus Sign

    ? .Question Mark + .Plus Sign

    ' .Apostrophe = 60 )

    printf ( "First division ") ;else{

    if ( per >= 50 )printf ( "Second division" ) ;

    else{

    26

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    27/59

    Comp 111: Introduction to Programming

    if ( per >= 40 )printf ( "Third division" ) ;

    elseprintf ( "Fail" ) ;

    }

    }}This is a straight forward program. Observe that the program uses nested if-elses. This leads to threedisadvantages:

    As the number of conditions go on increasing the level of indentation also goes on increasing. Asa result the whole program creeps to the right.

    Care needs to be exercised to match the corresponding ifs and elses.

    Care needs to be exercised to match the corresponding pair of braces.All these three problems can be eliminated by usage of Logical operators. The following programillustrates this.

    /* Method II */

    main( ){

    int m1, m2, m3, m4, m5, per ;printf ("Enter marks in five subjects ");scanf ("%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5);per = (m1 + m2 + m3 + m4 + m5) / 5;if (per >= 60)printf ("First division");if (( per >= 50) && (per < 60))printf ("Second division");if ((per >= 40) && (per < 50))

    printf ("Third division");if(per < 40)printf ("Fail");

    }As can be seen from the second if statement, the && operator is used to combine two conditions. Seconddivision gets printed if both the conditions evaluate to true. If one of the conditions evaluate to false thenthe whole thing is treated as false. Two distinct advantages can be cited in favor of this program:

    The matching (or do I say mismatching) of the ifs with their corresponding elses gets avoided,since there are no elses in this program.

    In spite of using several conditions, the program doesn't creep to the right. In the previousprogram the statements went on creeping to the right. This effect becomes more pronounced asthe number of conditions goes on increasing. This would make the task of matching the ifs with

    their corresponding elses and matching of opening and closing braces that much more difficult.

    The else if ClauseThere is one more way in which we can write the program above. This involves usage ofelse ifblocks asshown below:/* else if ladder demo */main( )

    27

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    28/59

    Comp 111: Introduction to Programming

    {int m1, m2, m3, m4, m5, per;per = ( m1+ m2 + m3 + m4+ m5 ) / per;if (per >= 60)printf ("First division");

    else if (per >= 50)printf ("Second division");else if (per >= 40)printf ("Third division");elseprintf ("fail") ;

    }You can note that this program reduces the indentation of the statements. In this case every else isassociated with its previous if. The last else goes to work only if all the conditions fail. Even in else ifladder the last elseis optional.Note that the else if clause is nothing different. It is just a way of rearranging the else with the if thatfollows it. This would be evident if you look at the following code:

    if( i==2)printf(with you);else{

    If(j==2)printf(All the time);

    }OR

    if( i==2)printf(with you);

    elseif(j==2)

    printf(All the time);

    Another place where logical operators are useful is when we want to write programs for complicatedlogics that ultimately boil down to only two answers. For example, consider the following example:Example:A company insures its drivers in the following cases:

    If the driver is married.

    If the driver is unmarried, male & above 30 years of age.

    If the driver is unmarried, female & above 25 years of age.In all other cases the driver is not insured. If the marital status, sex and age of the driver are the inputs,write a program to determine whether the driver is to be insured or not.

    Here after checking a complicated set of instructions the final output of the program would be one of thetwoEither the driver should be ensured or the driver should not be ensured. As mentioned above, sincethese are the only two outcomes this problem can be solved using logical operators. But before we do thatlet us write a program that does not make use of logical operators.

    /* Insurance of driver - without using logical operators */main( )

    28

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    29/59

    Comp 111: Introduction to Programming

    {char sex, ms ;int age ;printf ( "Enter age, sex, marital status " ) ;scanf ( "%d %c %c", &age, &sex, &ms ) ;

    if ( ms == 'M' )printf ( "Driver is insured" ) ;else{if ( sex == 'M' ){

    if ( age > 30 )printf ( "Driver is insured" ) ;

    elseprintf ( "Driver is not insured" ) ;

    }else{if ( age > 25 )printf ( "Driver is insured" ) ;

    elseprintf ( "Driver is not insured" ) ;

    }}}From the program it is evident that we are required to match several ifs and elses and several pairs ofbraces. In a more real-life situation there would be more conditions to check leading to the programcreeping to the right. Let us now see how to avoid these problems by using logical operators. As

    mentioned above, in this example we expect the answer to be either Driver is insured or Driver is notinsured. If we list down all those cases in which the driver is insured, then they would be:

    Driver is married.

    Driver is an unmarried male above 30 years of age.

    Driver is an unmarried female above 25 years of age.

    Since all these cases lead to the driver being insured, they can be combined together using && and || asshown in the program below:

    /* Insurance of driver - using logical operators */main( ){

    char sex, ms ;int age ;printf ( "Enter age, sex, marital status " ) ;scanf ( "%d %c %c" &age, &sex, &ms ) ;if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age >30)||( ms == 'U' && sex == 'F' && age > 25 ))printf ("Driver is insured");

    29

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    30/59

    Comp 111: Introduction to Programming

    elseprintf ( "Driver is not insured" ) ;

    }In this program it is important to note that:

    The driver will be insured only if one of the conditions enclosed in parentheses evaluates to true.

    For the second pair of parentheses to evaluate to true, each condition in the parentheses separatedby && must evaluate to true.

    Even if one of the conditions in the second parentheses evaluates to false, then the whole of thesecond parentheses evaluates to false.

    The last two of the above arguments apply to third pair of parentheses as well.Thus we can conclude that the && and || are useful in the following programming situations:

    When it is to be tested whether a value falls within a particular range or not.

    When after testing several conditions the outcome is only one of the two answers (This problemis often called yes/no problem).

    The switch Statement

    This is another form of the multi way decision. It is well structured, but can only be used incertain cases where;

    Only one variable is tested, all branches must depend on the value of that variable. Thevariable must be an integral type. (int, long, short or char).

    Each possible value of the variable can control a single branch. A final, catch all, defaultbranch may optionally be used to trap all unspecified cases.

    Hopefully an example will clarify things. This is a function which converts an integer into avague description. It is useful where we are only concerned in measuring a quantity when it is

    quite small.estimate(number)int number;/* Estimate a number as none, one, two, several, many */{ switch(number) {

    case 0 :printf("None\n");break;

    case 1 :printf("One\n");break;

    case 2 :printf("Two\n");

    break;case 3 :case 4 :case 5 :

    printf("Several\n");break;

    default :printf("Many\n");

    30

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    31/59

    Comp 111: Introduction to Programming

    break;}

    }

    Each interesting case is listed with a corresponding action. The break statement prevents anyfurther statements from being executed by leaving the switch. Since case 3 and case 4 have nofollowing break, they continue on allowing the same action for several values of number.

    The other main type of control statement is the loop. Loops allow a statement, or block ofstatements, to be repeated. Computers are very good at repeating simple tasks many times, theloop is C's way of achieving this.

    The Conditional OperatorsThe conditional operators ? and : are sometimes called ternary operators since they take three arguments.In fact, they form a kind of foreshortened if-then-else. Their general form is,expression 1 ? expression 2 : expression 3What this expression says is: if expression 1 is true (that is, if its value is non-zero), then the value

    returned will be expression 2, otherwise the value returned will be expression 3. Let us understand thiswith the help of a few examples:i.

    int x, y ;scanf ( "%d", &x ) ;y = ( x > 5 ? 3 : 4 ) ;

    This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y. The equivalent ifstatement will be,if ( x > 5 )

    y = 3;else

    y = 4 ;

    ii. char a ;

    int y ;scanf ( "%c", &a ) ;y = ( a >= 65 && a =65 && a = 'a' ? a : '!' ) ) ;

    The conditional operators can be nested as shown below.

    31

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    32/59

    Comp 111: Introduction to Programming

    int big, a, b, c ; big = (a > b ? (a > c ? 3: 4) : (b > c? 6: 8));

    Check out the following conditional expression:a > b ? g = a : g = b ;This will give you an error Lvalue Required. The error can be overcome by enclosing the

    statement in the : part within a pair of parenthesis. This is shown below:a > b ? g = a : ( g = b );In absence of parentheses the compiler believes that b is being assigned to the result of the

    expression to the left of second =. Hence it reports an error.The limitation of the conditional operators is that after the ?or after the : only one C statement canoccur. In practice rarely is this the requirement. Therefore, in serious C programming conditionaloperators arent as frequently used as the if-else.

    LoopsThe versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involvesrepeating some portion of the program either a specified number of times or until a particular condition is

    being satisfied. This repetitive operation is done through a loop control instruction. There are threemethods by way of which we can repeat a part of a program. They are:

    Using a for statement

    Using a while statement

    Using a do-while statement

    The While Loop

    It is often used if one wants to do something a fixed number of times. Perhaps you want tocalculate gross salaries of ten different persons, or you want to convert temperatures fromcentigrade to Fahrenheit for 15 different cities. The while loop is, ideally suited for such cases.For example:/* Calculation of simple interest for 3 sets of p, n and r */main( ){

    int p, n, count ;float r, si ;count=1;while ( count

  • 8/3/2019 Comp111 Notes

    33/59

    Comp 111: Introduction to Programming

    This is very similar to the while loop except that the test occurs at the end of the loop body. Thisguarantees that the loop is executed at least once before continuing. Such a setup is frequentlyused where data is to be read. The test then verifies the data, and loops back to read again if itwas unacceptable. The general syntax is: -

    do{Statements;

    } while (condition);

    do{ printf("Enter 1 for yes, 0 for no :");

    scanf("%d", &input_value);} while (input_value != 1 && input_value != 0);

    The for Loop

    The for loop works well where the number of iterations of the loop is known before the loop isentered. The head of the loop consists of three parts separated by semicolons.

    The first is run before the loop is entered. This is usually the initialization of the loopvariable.

    The second is a test, the loop is exited when this returns false. The third is a statement to be run every time the loop body is completed. This is usually an

    increment of the loop counter.The general syntax is : -

    for (initialize; condition; increment/ decrement){

    Statements;

    }The example is a function which calculates the average of the numbers stored in an array. Thefunction takes the array and the number of elements as arguments.

    float average(float array[], int count){ float total = 0.0;

    int i;

    for(i = 0; i < count; i++)total += array[i];

    return(total / count);}

    The for loop ensures that the correct number of array elements are added up before calculatingthe average.

    The three statements at the head of a for loop usually do just one thing each, however any ofthem can be left blank. A blank first or last statement will mean no initialization or runningincrement. A blank comparison statement will always be treated as true. This will cause the loop

    33

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    34/59

    Comp 111: Introduction to Programming

    to run indefinitely unless interrupted by some other means. This might be a return or a breakstatement.

    It is also possible to squeeze several statements into the first or third position, separating themwith commas. This allows a loop with more than one controlling variable. The example below

    illustrates the definition of such a loop, with variables hi and lo starting at 100 and 0 respectivelyand converging.

    for (hi = 100, lo = 0; hi >= lo; hi--, lo++)

    The for loop is extremely flexible and allows many types of program behaviour to be specifiedsimply and quickly.

    The break StatementWe have already met break in the discussion of the switch statement. It is used to exit from aloop or a switch, control passing to the first statement beyond the loop or a switch.With loops, break can be used to force an early exit from the loop, or to implement a loop with a

    test to exit in the middle of the loop body. A break within a loop should always be protectedwithin an if statement which provides the test to control the exit condition.

    The continue StatementThis is similar to break but is encountered less frequently. It only works within loops where its effect is toforce an immediate jump to the loop control statement.

    In a while loop, jump to the test statement. In a do while loop, jump to the test statement. In a for loop, jump to the test, and perform the iteration.

    Like a break, continue should be protected by an if statement. You are unlikely to use it veryoften.

    Functions in C

    A function in C language is a block of code that performs a specific task. It has a name and it isreusable i.e. it can be executed from as many different parts in a C Program as required. It alsooptionally returns a value to the calling program

    So function in a C program has some properties discussed below.

    Every function has a unique name. This name is used to call function from main()function. A function can be called from within another function.

    A function is independent and it can perform its task without intervention from orinterfering with other parts of the program.

    34

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    35/59

    Comp 111: Introduction to Programming

    A function performs a specific task. A task is a distinct job that your program mustperform as a part of its overall operation, such as adding two or more integer, sorting anarray into numerical order, or calculating a cube root etc.

    A function returns a value to the calling program. This is optional and depends upon the

    task your function is going to accomplish. Suppose you want to just show few linesthrough function then it is not necessary to return a value. But if you are calculating areaof rectangle and wanted to use result somewhere in program then you have to send back(return) value to the calling function.

    C language is collection of various inbuilt functions. If you have written a program in C then it isevident that you have used Cs inbuilt functions. Printf, scanf, clrscr etc. all are Cs inbuiltfunctions.

    Structure of a Function

    A general form of a C function looks like this:

    FunctionName (Argument1, Argument2, Argument3)

    {

    Statement1;

    Statement2;

    Statement3;

    }

    An example of function.

    int sum (int x, int y){int result;result = x + y;return (result);}

    Example of a simple function to add two integers.

    1. #include2. #include3. void add(int x, int y)4. {5. int result;6. result = x+y;7. printf("Sum of %d and %d is %d.\n\n",x,y,result);

    35

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    36/59

    Comp 111: Introduction to Programming

    8. }9. void main()10. {11. clrscr();12. add(10,15);

    13. add(55,64);14. add(168,325);15. getch();16. }

    Explanation

    Before I explain, let me give you an overview of above c program code. This is a very simpleprogram which has only function named add() . This add() function takes two values asarguments, adds those two values and prints the result.

    Line 3-8 is a function block of the program. Line no. 3 is the header of function, void is returntype of function, add is function name and (int x, int y) are variable which can hold integervalues to x and y respectively. When we call function, line no. 12, 13, 14, we need to send twointeger values as its argument. Then these two values get stored in variable x and y of line no. 3.Now we have two values to perform addition; in line no. 5 there is an integer declaration namedresult. This integer will store the sum of x and y (please see line no. 6). Line no. 7 simplyprints the result with message.

    Now imagine the same program without using function. We have called add() function threetimes, to get the same output without using function we have to write Line no. 6 & 7 three time.If you want to add more value later in the program then again you have to type those two lines.Above example is a small and simple program so it does not appear great to use function. Butassume a function consist 20 30 or more lines then it would not be wise to write same block ofcode wherever we need them. In such cases functions come handy, declare once, use whereveryou want.

    Advantages of using functions:

    There are many advantages in using functions in a program they are:

    1. It makes possible top down modular programming. In this style of programming, the highlevel logic of the overall problem is solved first while the details of each lower levelfunctions is addressed later.

    2. The length of the source program can be reduced by using functions at appropriateplaces.

    36

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    37/59

    Comp 111: Introduction to Programming

    3. It becomes uncomplicated to locate and separate a faculty function for further study.4. A function may be used later by many other programs this means that a c programmer

    can use function written by others, instead of starting over from scratch.5. A function can be used to keep away from rewriting the same block of codes which we

    are going use two or more locations in a program. This is especially useful if the code

    involved is long or complicated.

    Types of functions:

    A function may belong to any one of the following categories:

    1. Functions with no arguments and no return values.2. Functions with arguments and no return values.3. Functions with arguments and return values.4. Functions that return multiple values.5. Functions with no arguments and return values.

    1. Functions with no arguments and no return value.

    A C function without any arguments means you cannot pass data (values like int, char etc) to thecalled function. Similarly, function with no return type does not pass back data to the callingfunction. It is one of the simplest types of function in C. This type of function which does notreturn any value cannot be used in an expression it can be used only as independent statement.Lets have an example to illustrate this.

    1. #include

    2. #include3. void printline()4. {5. int i;6. printf("\n");7. for(i=0;i

  • 8/3/2019 Comp111 Notes

    38/59

    Comp 111: Introduction to Programming

    20. getch();21. }

    Source Code Explanation:

    The above C program example illustrates that how to declare a function with no argument and noreturn type. I am going to explain only important lines only because this C program example isfor those who are above the beginner level.

    Line 3-12: This C code block is a user defined function (UDF) whose task is to print a horizontalline. This is a simple function and a basic programmer can understand this. As you can see inline no. 7 I have declared a for loop which loops 30 time and prints - symbol continuously.

    Line 13-21: These line are main() function code block. Line no. 16 and 18 simply prints twodifferent messages. And line no. 17 and 18 calls our user defined function printline().

    2. Functions with arguments and no return value.

    In our previous example what we have noticed that main() function has no control over theUDF printfline(), it cannot control its output. Whenever main() calls printline(), it simplyprints line every time. So the result remains the same.

    A C function with arguments can perform much better than previous function type. This type offunction can accept data from calling function. In other words, you send data to the calledfunction from calling function but you cannot send result data back to the calling function.Rather, it displays the result on the terminal. But we can control the output of function by

    providing various values as arguments. Lets have an example to get it better.

    1. #include2. #include3. void add(int x, int y)4. {5. int result;6. result = x+y;7. printf("Sum of %d and %d is %d.\n\n",x,y,result);8. }9. void main()

    10. {11. clrscr();12. add(30,15);13. add(63,49);14. add(952,321);15. getch();16. }

    38

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    39/59

    Comp 111: Introduction to Programming

    Source Code Explanation:

    This program simply sends two integer arguments to the UDF add() which, further, calculatesits sum and stores in another variable and then prints that value. So simple program tounderstand.

    Line 3-8: This C code block is add() which accepts two integer type arguments. This UDFalso has a integer variable result which stores the sum of values passed by calling function (inthis example main()). And line no. 7 simply prints the result along with argument variablevalues.

    Line 9-16: This code block is a main() function but only line no. 12, 13, 14 is important for usnow. In these three lines we have called same function add() three times but with differentvalues and each function call gives different output. So, you can see, we can control functionsoutput by providing different integer parameters which was not possible in function type 1. Thisis the difference between function with no argument and function with argument.

    3. Functions with arguments and return value.

    This type of function can send arguments (data) from the calling function to the called functionand wait for the result to be returned back from the called function back to the calling function.And this type of function is mostly used in programming world because it can do two waycommunications; it can accept data as arguments as well as can send back data as return value.The data returned by the function can be used later in our program for further calculations.

    1. #include

    2. #include3. int add(int x, int y)4. {5. int result;6. result = x+y;7. return(result);8. }9. void main()10. {11. int z;12. clrscr();

    13. z = add(952,321);14. printf("Result %d.\n\n",add(30,55));15. printf("Result %d.\n\n",z);16. getch();17. }

    Source Code Explanation:39

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    40/59

    Comp 111: Introduction to Programming

    This program sends two integer values (x and y) to the UDF add(), add() function adds thesetwo values and sends back the result to the calling function (in this program to main()function). Later result is printed on the terminal.

    Line No. 3-8: Look line no. 3 carefully, it starts with int. This int is the return type of the

    function, means it can only return integer type data to the calling function. If you want anyfunction to return character values then you must change this to char type. On line no. 7 you cansee return statement, return is a keyword and in bracket we can give values which we want toreturn. You can assign any integer value to experiment with this return which ultimately willchange its output. Do experiment with all you program and dont hesitate.

    Line No. 9-17: In this code block only line no. 13, 14 and 15 is important. We have declared aninteger z which we used in line no. 13. Why we are using integer variable z here? You knowthat our UDF add() returns an integer value on calling. To store that value we have declared aninteger value. We have passed 952, 321 to the add() function, which finally return 1273 asresult. This value will be stored in z integer variable. Now we can use z to print its value or

    to other function.

    You will also notice some strange statement in line no. 14. Actually line no. 14 and 15 does thesame job, in line no. 15 we have used an extra variable whereas on line no. 14 we directly printedthe value without using any extra variable. This was simply to show you how we can usefunction in different ways.

    4. Functions with no arguments but returns value.

    We may need a function which does not take any argument but only returns values to the callingfunction then this type of function is useful. The best example of this type of function is

    getchar() library function which is declared in the header file stdio.h. We can declare asimilar library function of own. Take a look.

    1. #include2. #include3. int send()4. {5. int no1;6. printf("Enter a no : ");7. scanf("%d",&no1);8. return(no1);

    9. }10. void main()11. {12. int z;13. clrscr();14. z = send();15. printf("\nYou entered : %d.", z);

    40

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    41/59

    Comp 111: Introduction to Programming

    16. getch();17. }

    Source Code Explanation:

    In this program we have a UDF which takes one integer as input from keyboard and sends backto the calling function. This is a very easy code to understand if you have followed all abovecode explanation. So I am not going to explain this code.

    POINTERS

    What is a Pointer?

    A pointer is a secondary data type (also known as derived data type) in C. It is built from one ofthe primary data types available in C language. Basically pointer contains memory address ofother variable or function as their value. As pointer deals with memory address, it can be used toaccess and manipulate data stored in memory.

    Benefits of using Pointer in C Program

    Pointer is one of the most exciting features of C language and it has added power and flexibilityto the language. Pointer is in C language because it offers following benefits to the programmers:

    1. Pointers can handle arrays and data table efficiently.2. Pointers support dynamic memory management.3. Pointer helps to return multiple values from a function through function argument.4. Pointer increases program execution speed.5. Pointer is an efficient tool for manipulating structures, linked lists, queues stacks etc.

    We can achieve these and much more benefits from pointer only if we can use it properly.

    The * And & Operators

    Take a look on the following declaration,

    int x=10;

    When we make such declaration how C compiler treat this statement:

    1. Reserve memory space for this integer value.

    41

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    42/59

    Comp 111: Introduction to Programming

    2. Name this memory location as x.3. Store the value 10 at this location.

    This can be illustrated by a simple diagram:

    Integer variable location in memory.

    So when we declared an integer variable x and assigned value 10 then compiler occupied a 2byte memory space at memory address 65325 and stored value 10 at that location. Compilernamed this address x so that we can use x instead of 65325 in our program. But we can useaddress or variable in our program and both will point to the same value (example given below).

    The memory address of a variable could differ from PC to PC and entirely depends on availablefree space in memory at time of program execution. As this differs from PC to PC thus wecannot rely on that address (numeric value representing variable address) and we cannot use thisaddress in our program. But have you noticed one thing that address is an integer.

    We can print address of any variable or function, following program shows how we can do that:

    Address of variable example.

    1. #include2. #include3.4. void main()5. {6. int i=9;7. clrscr();8.9. printf("Value of i : %d\n",i);10. printf("Address of i : %u",&i);11.12. getch();13. }

    This is a very simple c program which prints value and address of an integer. But did you noticeline no. 10 in above program? This line output the address of i variable and to get address of ivariable we have used ampersand (&) operator. This operator is known as "Address of" operatorand we already used this operator many times in our program, just recall scanfstatement which

    42

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    43/59

    Comp 111: Introduction to Programming

    is used to accept input from computer keyboard. So when we use ampersand operator (&i) beforeany variable then we are instructing c compiler to return its address instead of value.

    Another operator we going to deal with in this entire pointer tutorial is "*" called "Value ataddress" operator. It is the same operator which we use for multiplication of numbers. As the

    name suggest, "value at address" operator returns value stored at particular address. The "valueat address" operator also called indirection operator. Following example extends above Cprogram and puts "value at address" operator in action.

    Value at address (*) example

    1. #include2. #include3.4. void main()5. {

    6. int i=9;7. clrscr();8.9. printf("Value of i : %d\n",i);10. printf("Address of i : %u\n",&i);11. printf("Value at address of i : %d",*(&i));12.13. getch();14. }

    Now in this program notice line no. 11 and use of & and * operators also see the output of

    program which prints value of variable i and *(&i) same. This is how these two operator works.

    Pointer with an example

    Since this tutorial is already become lengthy so I am going to give a small example on how wecan use pointer in our C program.

    Syntax: datatype *pointer_name;

    Example : int *iPtr;

    float *fPtr;

    Pointer Example

    43

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    44/59

    Comp 111: Introduction to Programming

    1. #include2. #include3.4. void main()5. {

    6. int i=9, *ptr;7. ptr=&i;8. clrscr();9.10. printf("Value of i : %d\n",i);11. printf("Address of i : %u\n",&i);12. printf("Value of ptr : %u\n",ptr);13. printf("Address of ptr : %u\n",&ptr);14. printf("Ptr pointing value : %d", *ptr);15.16. getch();

    17. }

    In the above example in line no. 6 we have declared an integer i and assigned 9 to it. Along withvariable i, we have also declared an integer pointer. To declare a pointer of any data type we justneed to put an * (asterisk) before variable name or identifier. In our example ptr is an integervariable and is capable of holding address of any integer variable.

    Remember one thing integer pointer can hold only integer variable address, you cannot useinteger pointer to hold address of float or char variable. To hold char or float variable address ina pointer you need to declare char or float pointer respectively.

    In line no. 7 we assigned integer variable is address to ptr, now ptr is pointing to i. Line no 10prints value of i and line no. 11 prints address of i. Next line prints value stored in ptr pointervariable, line no. 13 prints address of ptr pointer. As pointer is different entity so it also requiresspace in memory. Memory occupied by a pointer depends on its data type. Integer pointer willoccupy 2 bytes whereas character pointer will occupy 1 byte. Finally line no. 14 prints the valueof address stored in ptr pointer i.e. value of i. And to print value of stored address in a pointer weneed write *pointer variable name (in our example *ptr). A memory map will help you tounderstand this.

    5. Functions that return multiple values.

    So far, we have learned and seen that in a function, return statement was able to return onlysingle value. That is because; a return statement can return only one value. But if we want tosend back more than one value then how we could do this?

    44

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    45/59

    Comp 111: Introduction to Programming

    We have used arguments to send values to the called function, in the same way we can also usearguments to send back information to the calling function. The arguments that are used to sendback data are called Output Parameters.

    It is a bit difficult for novice because this type of function uses pointer. Lets see an example:

    1. #include2. #include3. void calc(int x, int y, int *add, int *sub)4. {5. *add = x+y;6. *sub = x-y;7. }8. void main()9. {10. int a=20, b=11, p,q;

    11. clrscr();12. calc(a,b,&p,&q);13. printf("Sum = %d, Sub = %d",p,q);14. getch();15. }

    Source Code Explanation:

    Logic of this program is that we call UDF calc() and sends argument then it adds and subtractthat two values and store that values in their respective pointers. The * is known as indirectionoperator whereas & known as address operator. We can get memory address of any variable by

    simply placing & before variable name. In the same way we get value stored at specificmemory location by using * just before memory address. These things are a bit confusing butwhen you will understand pointer then these thing will become clearer.

    Line no. 3-7: This UDF function is different from all above UDF because it implements pointer.I know line no. 3 looks something strange, lets have a clear idea of it. Calc() function has fourarguments, first two arguments need no explanation. Last two arguments are integer pointerwhich works as output parameters (arguments). Pointer can only store address of the value ratherthan value but when we add * to pointer variable then we can store value at that address.

    Line no. 8-15: When we call calc() function in the line no. 12 then following assignments

    occurs. Value of variable a is assigned to x, value of variable b is assigned to y, addressof p and q to add and sub respectively. In line no. 5 and 6 we are adding and subtractingvalues and storing the result at their respective memory location. This is how the program works.

    45

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    46/59

    Comp 111: Introduction to Programming

    ARRAYS

    What is an Array?

    An array in C language is a collection of similar data-type, means an array can hold value of aparticular data type for which it has been declared. Arrays can be created from any of the C data-types int, float, and char. So an integer array can only hold integer values and cannot hold valuesother than integer. When we declare array, it allocates contiguous memory location for storingvalues whereas 2 or 3 variables of same data-type can have random locations. So this is the mostimportant difference between a variable and an array.

    Types of Arrays:

    1. One dimension array (Also known as 1-D array).2. Two dimension array (Also known as 2-D array).

    3. Multi-dimension array.

    Declaration of One Dimensional Arrays:

    Syntax: data_type array_name[width];

    Example: int roll[8];

    In our example, int specifies the type if the variable, roll specifies the name of the variable andthe value in bracket [8] is new for newbie. The bracket ([ ]) tells compiler that it is an array andnumber mention in the bracket specifies that how many elements (values in any array is called

    elements) it can store. This number is called dimension of array.So, with respect to our example we have declared an array of integer type and named it rollwhich can store roll numbers of 8 students.

    C Array Assignment and Initialization:

    We can initialize and assign values to the arrays in the same way as we do with variable. We canassign value to an array at the time of declaration or during runtime. Lets look at each approach.

    Syntax: data_type array_name[size]={list of values};

    Example:

    int arr[5]={1,2,3,4,5};int arr[]={1,2,3,4,5};

    In our above array example we have declared an integer array and named it arr which can hold5 elements, we are also initializing arrays in the same time.

    46

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    47/59

    Comp 111: Introduction to Programming

    Both statements in our example are valid method to declare and initialize single dimension array.In our first example we mention the size (5) of an array and assigned it values in curly brace,separating elements value by comma (,). But in second example we left the size field blank butwe provided its elements value. When we only give element values without providing size of an

    array then C compiler automatically assumes its size from given element values.

    There is one more method to initialize array C programming; in this method we can assignvalues to individual element of an array. For this lets look at example:

    Array Initialization Example

    1. #include2. #include3.4. void main()

    5. {6. int arr[5],i;7. clrscr();8. arr[0]=10;9. arr[1]=20;10. arr[2]=30;11. arr[3]=40;12. arr[4]=50;13.14. printf("Value in array arr[0] : %d\n",arr[0]);15. printf("Value in array arr[1] : %d\n",arr[1]);

    16. printf("Value in array arr[2] : %d\n",arr[2]);17. printf("Value in array arr[3] : %d\n",arr[3]);18. printf("Value in array arr[4] : %d\n",arr[4]);19. printf("\n");20.21. for(i=0;i

  • 8/3/2019 Comp111 Notes

    48/59

    Comp 111: Introduction to Programming

    TWO DIMENSIONAL ARRAYS

    We know how to work with an array (1D array) having one dimension. In C language it is

    possible to have more than one dimension in an array. We are going to learn how we can use twodimensional arrays (2D arrays) to store values. Because it is a 2D array so its structure will bedifferent from one dimension array. The 2D array is also known as Matrix or Table, it is an arrayof array.

    Declaration of 2D array:

    Syntax: data_type array_name[row_size][column_size];Example: int arr[3][3];So the above example declares a 2D array of integer type. This integer array has been named arrand it can hold up to 9 elements (3 rows x 3 columns).

    Code for assigning & displaying 2D Array

    1. #include2. #include3.4. void main()5. {6. int i, j;7. int arr[3][3]={

    8. {12, 45, 63},9. {89, 34, 73},10. {19, 76, 49}11. };12. clrscr();13. printf(":::2D Array Elements:::\n\n");14. for(i=0;i

  • 8/3/2019 Comp111 Notes

    49/59

    Comp 111: Introduction to Programming

    So in the above example we have declared a 2D array named arr which can hold 3x3 elements.We have also initialized that array with values, because we told the compiler that this array willcontain 3 rows (0 to 2) so we divided elements accordingly. Elements for column have beendifferentiated by a comma (,). When compiler finds comma in array elements then it assumescomma as beginning of next element value. We can also define the same array in other ways,

    like.int arr[3][3]={12, 45, 63, 89, 34, 73, 19, 76, 49}; or,int arr[ ][3]={12, 45, 63, 89, 34, 73, 19, 76, 49};

    But this kind of declaration is not acceptable in C language programming.

    int arr[2][ ]={12, 45, 63, 89, 34, 73, 19, 76, 49}; or,int arr[ ][ ]={12, 45, 63, 89, 34, 73, 19, 76, 49};

    To display 2D array elements we have to just point out which element value we want to display.In our example we have a arr[3][3], so the array element reference will be from arr[0][0] to arr[2]

    [2]. We can print display any element from this range. But in our example I have used for loopfor my convenience, otherwise I had to write 9 printf statements to display all elements of array.So for loop i handles row of 2D array and for loop j handles column. I have formatted the outputdisplay of array so that we can see the elements in tabular form.

    STRUCTURES

    C Structure Introduction

    We used variable in our C program to store value but one variable can store only single pieceinformation (an integer can hold only one integer value) and to store similar type of values wehad to declare many variables. To overcome this problem we used array which can hold numbersof similar data type. But array too have some limitations, like in our real world application wedeal with set of dissimilar data types and single array cannot store dissimilar data.

    For example think about storing book information or product information, a product can havedifferent information to store like product code (an integer), product name (a char array),product price (a float) etc. And to store 20 products information we can declare integer arrayfor product code, 2D character array for storing product name and float array to store productprice. This approach definitely achieves your goals, but try to consider these things too. What ifyou wanted to add more products than 20, what if you want to add more information on productslike stock, discount, tax etc? It will become difficult to differentiate these variables with othervariables declared for calculation etc.

    To solve this problem C language has a unique data type called Structure. C structure is nothingbut collection of different related data types. If we are using C structure then we are combining

    49

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    50/59

    Comp 111: Introduction to Programming

    different related data types in one group so that we can use and manage those variables easily.Here related data type means, a structure holding information about book will contains variableand array related to book.

    Syntax for C Structure declaration

    struct structure_name{data type member1;data type member2;};

    Example:

    struct products{char name[20];int stock;float price;};

    So structure declaration begins with struct keyword and with a space we need to provide a

    structure name. Within open and closed curly braces we can declare required and relatedvariable, you can see it in our example structure declaration. And most important point toremember in case of C structure is that it ends with semicolon (;).

    Example of C Structure

    1. #include2. #include3.4. struct product5. {

    6. char name[30];7. int stock;8. float price, dis;9. };10.11. void main()12. {

    50

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    51/59

    Comp 111: Introduction to Programming

    13.14. struct product p1 ={"Apple iPod Touch 32GB", 35,298.56, 2.32};15. clrscr();16. printf("Name=%s,\nStock=%d,\nPrice=$%.2f,\nDiscount=%.2f%.", p1.name, p1.stoc

    k, p1.price,p1.dis);

    17. getch();18. }

    Code Explanation

    So line no.4-9 declares a C structure named product, this structure contains four variables tostore different information about product. In the beginning there is a character array (charname[30]) which stores name of the product, next we have integer variable (int stock) to storestock of product and last two variable are float type (float price, discount) to product price &discount on product respectively.

    Guys we just declared product structure and now we have to use it in main(). Line no. 14declares a product type variable p1. Here product type variable means, in our C programproduct is a structure and to use that structure we need to create its variable. Declaring a productstructure variable is simple just use following syntax:

    struct structure_name variable_name;

    Remember struct is a C keyword, structure_name is name of structure you used whiledeclaring a C structure (in above C program its product) and variable_name could be anyname of your choice (in above C program its p1) but standard naming convention applies.

    Along with declaring C structure variable p1 we have also initialized it and to initialize Cstructure you need to assign values in proper order. Proper order means assign value in the orderthey are declared in structure. For example, in ourproduct structure we declare variable infollowing orders:

    char name[30];int stock;float price, discount;

    So for this structure proper order will be:

    char name[30];int stock;float price;float discount;

    51

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    52/59

    Comp 111: Introduction to Programming

    You dont need to rewrite your structure, you just need to keep it in mind that structure variableinitialization should be performed in orderly manner (top bottom and left right manner)otherwise it will show error or you may get strange output.

    So in above program we have initialized p1 variable in following way:

    struct product p1 ={"Apple iPod Touch 32GB", 35, 298.56, 2.32}; means

    struct product p1 ={char name[30], int stock, float price, float discount};//this line of code isonly assumption.

    Next in line no. 16 we just printed the values stores in product structure. You cannot print valuesstored in product structure member variable (like name, stock etc.) directly, you have to linkmember variable with structure variable and you can do this using (.) dot operator. Forexample: character array name is unknown to main() because it is declared in structure product,so to access member variable we will follow the following syntax:

    structure_variable.member_variable;

    Example:

    p1.name;

    We can rewrite printf("Name=%s,\nStock=%d,\nPrice=$%.2f,\nDiscount=%.2f%.",p1.name, p1.stock, p1.price,p1.discount); in the following manner:

    printf(Name = %s,p1.name);

    printf(Stock = %d,p1.stock);printf(Price = $%.2f,p1.price);printf(Stock = %.2f,p1.discount);

    Here is full working code sample of C Structure

    1. #include2. #include3.4. struct product5. {

    6. char name[30];7. int stock;8. float price, discount;9. };10.11. void main()12. {

    52

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    53/59

    Comp 111: Introduction to Programming

    13.14. struct product p1 ={"Apple iPod Touch 32GB", 35,298.56, 2.32};15. clrscr();16. printf("Name = %s\n",p1.name);17. printf("Stock = %d\n",p1.stock);

    18. printf("Price = %.2f\n",p1.price);19. printf("Discount= %.2f\n",p1.discount);20. getch(); }

    THE C STORAGE CLASSES, SCOPE AND MEMORY

    ALLOCATIONINTRODUCTION

    The storage class determines the part of memory where storage is allocated for an object(particularly variables and functions) and how long the storage allocation continues toexist.

    A scope specifies the part of the program which a variable name is visible, that is theaccessibility of the variable by its name. In C program, there are four storage classes:automatic, register, external, and static.

    Keep in mind that in the hardware terms we have primary storage such as registers,cache, memory (Random Access Memory) and secondary storage such as magnetic and

    optical disk.

    1. AUTOMATIC VARIABLE - auto They are declared at the start of a programs block such as in the curly braces ( { } ).

    Memory is allocated automatically upon entry to a block and freed automatically uponexit from the block.

    The scope of automatic variables is local to the block in which they are declared,including any blocks nested within that block. For these reasons, they are also calledlocal variables.

    No block outside the defining block may have direct access to automatic variables (byvariable name) but, they may be accessed indirectly by other blocks and/or functions

    using pointers. Automatic variables may be specified upon declaration to be of storage class auto.

    However, it is not required to use the keyword auto because by default, storage classwithin a block is auto.

    Automatic variables declared with initializers are initialized every time the block inwhich they are declared is entered or accessed.

    53

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    54/59

    Comp 111: Introduction to Programming

    2. REGISTER VARIABLE - register Automatic variables are allocated storage in the main memory of the computer; however,

    for most computers, accessing data in memory is considerably slower than processingdirectly in the CPU.

    Registers are memory located within the CPU itself where data can be stored and

    accessed quickly. Normally, the compiler determines what data is to be stored in theregisters of the CPU at what times. However, the C language provides the storage class registerso that the programmer can

    suggest to the compiler that particular automatic variables should be allocated to CPUregisters, if possible and it is not an obligation for the CPU to do this.

    Thus, register variables provide a certain control over efficiency of program execution. Variables which are used repeatedly or whose access times are critical may be declared to

    be of storage class register. Variables can be declared as a register as follows:

    register int var;

    3. EXTERNAL VARIABLE - extern All variables we have seen so far have had limited scope (the block in which they are

    declared) and limited lifetimes (as for automatic variables). However, in some applications it may be useful to have data which is accessible from

    within any block and/or which remains in existence for the entire execution of theprogram. Such variables are called global variables, and the C language providesstorage classes which can meet these requirements; namely, the external (extern) andstatic (static) classes.

    Declaration for external variable is as follows:extern int var;

    External variables may be declared outside any function block in a source code file the

    same way any other variable is declared; by specifying its type and name (externkeyword may be omitted). Typically if declared and defined at the beginning of a source file, the extern keyword

    can be omitted. If the program is in several source files, and a variable is defined in letsay file1.c and used in file2.c and file3.c then the extern keyword must be used in file2.cand file3.c.

    But, usual practice is to collect extern declarations of variables and functions in aseparate header file (.h file) then included by using #include directive.

    Memory for such variables is allocated when the program begins execution, and remainsallocated until the program terminates. For most C implementations, every byte ofmemory allocated for an external variable is initialized to zero.

    The scope of external variables is global, i.e. the entire source code in the file followingthe declarations. All functions following the declaration may access the external variableby using its name. However, if a local variable having the same name is declared withina function, references to the name will access the local variable cell.

    The following program example demonstrates storage classes and scope./* storage class and scope */#include

    54

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    55/59

    Comp 111: Introduction to Programming

    void funct1(void);void funct2(void);/* external variable, scope is global to main(), funct1() and funct2(), extern

    keyword is omitted here, coz just one file */int globvar = 10;int main(){

    printf("\n****storage classes and scope****\n");/* external variable */globvar = 20;

    printf("\nVariable globvar, in main() = %d\n", globvar);funct1();

    printf("\nVariable globvar, in main() = %d\n", globvar);funct2();printf("\nVariable globvar, in main() = %d\n", globvar);return 0;

    }/* external variable, scope is global to funct1() and funct2() */int globvar2 = 30;void funct1(void){

    /* auto variable, scope local to funct1() and funct1() cannot access the externalglobvar */charglobvar;

    /* local variable to funct1() */globvar = 'A';/* external variable */globvar2 = 40;

    printf("\nIn funct1(), globvar = %c and globvar2 = %d\n", globvar, globvar2);

    }void funct2(void){

    /* auto variable, scope local to funct2(), and funct2() cannot access theexternal globvar2 */

    double globvar2;/* external variable */

    55

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    56/59

    Comp 111: Introduction to Programming

    globvar = 50;/* auto local variable to funct2() */globvar2 = 1.234;printf("\nIn funct2(), globvar = %d and globvar2 = %.4f\n", globvar, globvar2);

    }

    Output:

    External variables may be initialized in declarations just as automatic variables; however,

    the initializers must be constant expressions. The initialization is done only once atcompile time, i.e. when memory is allocated for the variables. In general, it is a good programming practice to avoid using external variables as they

    destroy the concept of a function as a 'black box' or independent module. The black box concept is essential to the development of a modular program with

    modules. With an external variable, any function in the program can access and alter thevariable, thus making debugging more difficult as well. This is not to say that externalvariables should never be used.

    There may be occasions when the use of an external variable significantly simplifies theimplementation of an algorithm. Suffice it to say that external variables should be usedrarely and with caution.

    4. STATIC VARIABLE - static As we have seen, external variables have global scope across the entire program

    (provided extern declarations are used in files other than where the variable is defined),and have a lifetime over the entire program run.

    56

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    57/59

    Comp 111: Introduction to Programming

    Similarly, static storage class provides a lifetime over the entire program, however; itprovides a way to limit the scope of such variables, and static storage class is declaredwith the keyword static as the class specifier when the variable is defined.

    These variables are automatically initialized to zero upon memory allocation just asexternal variables are. Static storage class can be specified for automatic as well as

    external variables such as:static extern varx; Static automatic variables continue to exist even after the block in which they are defined

    terminates. Thus, the value of a static variable in a function is retained between repeatedfunction calls to the same function.

    The scope of static automatic variables is identical to that of automatic variables, i.e. it islocal to the block in which it is defined; however, the storage allocated becomespermanent for the duration of the program.

    Static variables may be initialized in their declarations; however, the initializers must beconstant expressions, and initialization is done only once at compile time when memoryis allocated for the static variable.

    /* static storage class program example */#include #define MAXNUM 3void sum_up(void);int main(){

    int count;

    printf("\n*****static storage*****\n");printf("Key in 3 numbers to be summed ");for(count = 0; count < MAXNUM; count++)

    sum_up();printf("\n*****COMPLETED*****\n");return 0;

    }void sum_up(void){

    /* at compile time, sum is initialized to 0 */staticint sum = 0;int num;

    printf("\nEnter a number: ");scanf("%d", &num);sum += num;printf("\nThe current total is: %d\n", sum);

    }

    57

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    58/59

    Comp 111: Introduction to Programming

    Output:

    While the static variable, sum, would be automatically initialized to zero, it is better to doso explicitly.

    In any case, the initialization is performed only once at the time of memory allocation bythe compiler. The variable sum retains its value during program execution.

    Each time the sum_up() function is called, sum is incremented by the next integer read.To see the different you can remove the static keyword, re-compile and re-run theprogram.

    DYNAMIC MEMORY ALLOCATION In the previous section we have described the storage classes which determined how

    memory for variables is allocated by the compiler. When a variable is defined in the source program, the type of the variable determines

    how much memory the compiler allocates. When the program executes, the variable consumes this amount of memory regardless of

    whether the program actually uses the memory allocated. This is particularly true forarrays.

    However, in many situations, it is not clear how much memory the program will actuallyneed. For example, we may have declared arrays to be large enough to hold themaximum number of elements we expect our application to handle.

    If too much memory is allocated and then not used, there is a waste of memory. If notenough memory is allocated, the program is not able to fully handle the input data.

    We can make our program more flexible if, during execution, it could allocate initial and

    additional memory when needed and free up the memory when it is no more needed. Allocation of memory during execution is called dynamic memory allocation. C

    provides library functions to allocate and free up memory dynamically during programexecution. Dynamic memory is allocated on the heap by the system.

    It is important to realize that dynamic memory allocation also has limits. If memory isrepeatedly allocated, eventually the system will run out of memory.

    58

    Pre

    pared by Z. Mwololo

  • 8/3/2019 Comp111 Notes

    59/59

    Comp 111: Introduction to Programming