Fundamental of C in Brief.pdf

download Fundamental of C in Brief.pdf

of 85

Transcript of Fundamental of C in Brief.pdf

  • 8/9/2019 Fundamental of C in Brief.pdf

    1/85

    Sandip MalCentre for Computer Science1

    OVERVIEW OF C

    The C programming language is a computer programming language developed inthe early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operatingsystem. It has since spread to many other operating systems, and is one of the most

    widely used programming languages. C is prized for its efficiency, and is the mostpopular programming language for writing system software, though it is also used forwriting applications. It is also commonly used in computer science education, despitenot being designed for novices.

    Characteristics of C

    1. C is a simple programming language for procedure oriented programmingapproach.

    2. C programs are free format programs.

    3. C programming language support pre-processor feature.4. C programs use of function calls.5. C programming can be used for low level programming.6. C programming support memory access via the use of pointers.7. C programming support use of pointers in functions also.

    Why use C ?Industry Presence:Over the last decade C has become one of the most widely useddevelopment languages in the software industry. Its importance is not entirely derivedfrom its use as a primary development language but also because of its use as aninterface language to some of the newer visual languages and of course because of

    its relationship with C++.Middle Level: Being a Middle level language it combines elements of high levellanguages with the functionality of assembly language. C supports data types andoperations on data types in much the same way as higher level languages as well asallowing direct manipulation of bits, bytes, words and addresses as is possible withlow level languages.Portability:With the availability of compilers for almost all operating systems andhardware platforms it is easy to write code on one system which can be easily portedto another as long as a few simple guidelines are followed.Flexibility: Supporting its position as the mainstream development language C can beinterfaced readily to other programming languages.

    Malleable:C, unlike some other languages, offers little restriction to the programmerwith regard to data types -- one type may be coerced to another type as the situationdictates. However this feature can lead to sloppy coding unless the programmer isfully aware of what rules are being bent and why.Speed: The availability of various optimising compilers allow extremely efficientcode to be generated automatically.

    ---Importance of C

    The language is relatively little changed; one of his goals of thestandard was to make sure that most existing programs wouldremain valid, or, failing that, that compilers could produce warningsof new behaviour.

    For most programmers, the most important change is the new syntaxfor declaring and defining functions. A function declaration can now

  • 8/9/2019 Fundamental of C in Brief.pdf

    2/85

    Sandip MalCentre for Computer Science2

    include a description of the arguments of the function; it is a veryuseful addition to the language.

    There are other small-scale language changes. Structure assignmentand enumerations, which had been widely available, are nowofficially part of the language.

    Floating-point computations may now be done in single precision. The pre-processor is more elaborate. Most of these changes will

    have only minor effects on most programmers.

    A significant contribution of the standard is the definition of alibrary to accompany C.

    A collection of standard headers introduction provides uniformaccess to declarations of functions in data types.

    Because the data types and control structures provided by C aresupported directly by most computers, the run-time library requiredto implement self-contained programs is tiny.

    It is independent of any particular machine architecture. With a littlecare it is easy to write portable programs, that is, programs that canbe run without change on a variety of hardware.

    C is not a strongly-typed language, but as it has evolved, its type-checking has been strengthened.

    Some reasons of popularity of C language:

    C has now become a widely used professional language for various reasons.

    1. It support procedure oriented programming.

    2. It supports low level programming.3. It support pre-processor feature.4. It makes program portable.

    Source Code: program is written by the user is called a source code.

    Compiler: A compiler is a program that can convert source code in a machinereadable form.

    Compilation:The process done by the compiler is known as compilation. Normallywe do compilation by using keys Alt + F9.

    Execution: The running process of a compiled program is known as execution.Normally we do execution by using keys Clt + F9 (control + f9).

    Output:The result produced by the execution process is known as output. Normallywe can see the output of a program by using keys Alt + F5.

    Preprocessor: The preprocessor is a program that runs before the compilation andpotentially modifies a source code file. It may add some code.

  • 8/9/2019 Fundamental of C in Brief.pdf

    3/85

    Sandip MalCentre for Computer Science3

    ---Structure of C-ProgramC programs are essentially constructed in the following manner, as a number of welldefined sections.

    /* HEADER SECTION */

    /* Contains name, author, revision number*/

    /* INCLUDE SECTION */

    /* contains #include statements */

    /* CONSTANTS AND TYPES SECTION */

    /* contains types and #defines */

    /* GLOBAL VARIABLES SECTION */

    /* any global variables declared here */

    /* FUNCTIONS SECTION */

    /* user defined functions */

    /* main() SECTION */

    int main() // C-Program Execution starts here.

    {

    Declaration Part; // variables declared before used in an

    Executable part

    Executable Part; // Perform manipulation based on above

    variables declared in Declaration

    part;

    producing output based on

    manipulations.

    }

    Adhering to a well defined structured layout will make your programs

    easy to read easy to modify consistent in format self documenting

    -----Constants, Variables and Data types------Declaration:A declaration is used to specify the name and type of a variable to thecompiler.

    Constants:They refer to fixed values that do not change during the execution of a program.

    Constants

    Numeric Constants Character Constants

    Integer

    Constants Real ConstantsSingle Character

    ConstantsString Constants

    Integer constants:It refers to a sequence of digits. There are three types of integers, namely decimalinteger, octal integer and hexadecimal integer.

    Decimal integers consist of a set of digits 0 through 9, preceded by optional or +sign.

  • 8/9/2019 Fundamental of C in Brief.pdf

    4/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    5/85

    Sandip MalCentre for Computer Science5

    '\r' carriage return

    '\t' horizontal tab

    '\'' single quote

    '\"' double quote

    '\?' question mark

    '\\' backslash'\0' null

    Variable: A variable is used to store a data value. A variable may take differentvalues at different times during execution.Rules for writing the variable name:

    1. They must begin with a letter. Numeric value should not be at first position.2. Uppercase and lowercase are significant. That is variable Total is not the

    same as total or TOTAL.3. It should not be a keyword4. White space is not allowed.

    Example:

    Valid variable names: x1, T_ raise, distance, A, B, a, bInvalid variable names: 123 %, (area), 3an, _man

    ----Data Types in C-----There are three classes of data types

    1. Primary data types2. Derived data types3. User defined data types

    Primary data type:C compiler support five fundamental data types

    1. integer - int2. character - char3. floating point - float4. double5. void

    Integer Types: There are three classes of integer storage namely short int, int andlong int in both signed and unsigned forms Unsigned integer use all the bits for themagnitude of the number and are always positive.

    char 1 byte

    short int or signed short int 1byte

    unsigned short int 1 byteint or signed int 2 bytes(1 byte is 8 bits)

    unsigned int 2 bytes

    long int or signed long int 4 bytes

    unsigned long int 4 bytes

    float 4 bytes

    double 8 bytes

    long double 10 bytes

    Floating point types:

    It is stored in 32 bits with 6 digits of precision. Floating point numbers are defined bythe keyword float. The data type double can be used to define the number with 8

  • 8/9/2019 Fundamental of C in Brief.pdf

    6/85

    Sandip MalCentre for Computer Science6

    bytes giving a precision of 14 digits.. These are known as double precision number.The precision can be increased by using long double which uses 10 bytes.

    Void types:The void type has no values. The type of a function is said to be void when it does

    not return any value to the calling function.

    Character types:A single character can be defined as a character (char) type data. Characters areusually stored in 8 bits of internal storage.

    Modifying Basic Types

    Except for type voidthe meaning of the above basic types may be altered whencombined with the following keywords.

    signed

    unsignedlongshort

    Thesignedand unsignedmodifiers may be applied to types char and int and willsimply change the range of possible values. For example an unsigned charhas arange of 0 to 255, all positive, as opposed to a signed char which has a range of -128to 127. An unsigned integeron a 16-bit system has a range of 0 to 65535 as opposedto asigned int which has a range of -32768 to 32767.

    Note however that the default for type int or char is signed so that the typesigned charis always equivalent to typecharand the typesigned int is always

    equivalent to int.

    The longmodifier may be applied to type int and double only. A long intwill require4 bytes of storage no matter what operating system is in use and has a range of -2,147,483,648 to 2,147,483,647. A long doublewill require 10 bytes of storage andwill be able to maintain up to 19 digits of precision.Theshort modifier may be applied only to type intand will give a 2 byte integerindependent of the operating system in use.NB :Note that the keyword intmay be omitted without error so that the type unsignedis the same as typeunsigned int, the typelongis equivalent to the type long int, andthe typeshortis equivalent to the typeshort int.

    ------Declaration of variable---Declaration of variables two things----:

    1. It tells the compiler what the variable name is.2. It specifies what type of data that the variable will hold.

    General form-----:Data-type v1,v2,.., vn;

    Where v1, v2,.., vn are the name of variables of any basic data types.

    Example----Case 1. int x;

    x=5;Case 2. int x=5;

  • 8/9/2019 Fundamental of C in Brief.pdf

    7/85

    Sandip MalCentre for Computer Science7

    In the Case 1x is variable which is created of type integer and ready to hold thevalue of type integer (Declaration). And after that integer constant 5 is assigned tointeger variable x (Definition).In the Case2 5 is assigned to variable x during declaration (Declaration anddefinition done in the same step reducing computer memory space)

    User-Defined Type DeclarationIt allows user to define an identifier that would represent an existing data type. Thegeneral form istypedef type identifier;

    Where type refers to an existing data type and identifier refers to the new name givento the data type.Example:

    typedef int units;typedef float marks;

    Here units symbolizes int and marks symbolizes float. They can be later used todeclare variables as

    units batch1,batch2;marks x, y;

    where batch1 and batch2 are declared as int variable and x and y are declared as floatvariable.

    Defining symbolic constantsThere are some constants that appear repeatedly in a number of places in the program.One example is the value of "pi" which is 3.142. Instead of using the constant valuein the program we can define the value of the pi using#define symbolic-name value of the constant#define PI 3.142

    SUMMARY OF #define

    allow the use of symbolic constants in programs in general, symbols are written in uppercase are not terminated with a semi-colon generally occur at the beginning of the file each occurrence of the symbol is replaced by its value makes programs readable and easy to maintain

    Console Input / OutputThe printf() function is used for formatted output and uses a control string which ismade up of a series of format specifiers to govern how it prints out the values of thevariables or constants required. The more common format specifiers are given below

    %c character %f floating point%d signed integer %lf double floating point%i signed integer %e exponential notation%u unsigned integer %s string%ld signed long %x unsigned

    hexadecimal

    %lu unsigned long %o unsigned octal%% prints a % sign

  • 8/9/2019 Fundamental of C in Brief.pdf

    8/85

    Sandip MalCentre for Computer Science8

    The printf() function takes a variable number of arguments. In the above example twoarguments are required, the format string and the variablei. The value of iissubstituted for the format specifier %d which simply specifies how the value is to bedisplayed, in this case as a signed integer.

    Field Width Specifiers

    Field width specifiers are used in the control string to format the numbers orcharacters output appropriately .

    Syntax :- %[total width printed][.decimal places printed]format specifier

    where square braces indicate optional arguments.

    For Example :-int i = 15 ;float f = 13.3576 ;

    printf( "%3d", i ) ; /* prints "_15 " where _ indicates a space

    character */printf( "%6.2f", f ) ; /* prints "_13.36" which has a total width of 6

    and displays 2 decimal places*/

    printf( %*.*f, 6,2,f ) ; /* prints "_13.36" as above. Here * is usedas

    replacement character for field widths*/

    There are also a number of flags that can be used in conjunction with field widthspecifiers to modify the output format. These are placed directly after the % sign. A -(minus sign) causes the output to be left-justified within the specified field, a + (plussign) displays a plus sign preceding positive values and a minus preceding negativevalues, and a 0 (zero) causes a field to be padded using zeros rather than spacecharacters.

    scanf()

    This function is similar to the printf function except that it is used for formattedinput. The format specifiers have the same meaning as for printf() and the spacecharacter or the newline character are normally used as delimiters between differentinputs.

    For Example :-int i, d ;char c ;float f ;

    scanf( "%d", &i ) ;

    scanf( "%d %c %f", &d, &c, &f ) ; /* e.g. type "10_x_1.234RET" */

    scanf( "%d:%c", &i, &c ) ; /* e.g. type "10:xRET" */

  • 8/9/2019 Fundamental of C in Brief.pdf

    9/85

    Sandip MalCentre for Computer Science9

    The & character is the address of operator in C, it returns the address in memory ofthe variable it acts on.The scanf function has a return value which represents the number of fields it wasable to convert successfully.For Example :-

    num = scanf( %c %d, &ch, &i );

    This scanf call requires two fields, a character and an integer, to be read in so thevalue placed in numafter the call should be 2 if this was successful. However if theinput was a bc then the first character field will be read correctly as a but the

    integer field will not be converted correctly as the function cannot reconcile bc asan integer. Thus the function will return 1 indicating that one field was successfullyconverted. Thus to be safe the return value of the scanf function should be checkedalways and some appropriate action taken if the value is incorrect.

    getchar() and putchar()

    These functions are used to input and output single characters. Thegetchar()functionreads the ASCII value of a character input at the keyboard and displays the characterwhileputchar()displays a character on the standard output device i.e. the screen.

    For Example :-char ch1, ch2 ;

    ch1 = getchar() ;

    ch2 = 'a' ;putchar( ch2 ) ;

    NB : The input functions described above, scanf() and getchar() are termed bufferedinput functions. This means that whatever the user types at the keyboard is first storedin a data buffer and is not actually read into the program until either the buffer fills upand has to be flushed or until the user flushes the buffer by hitting RETwhereupon therequired data is read into the program. The important thing to remember with bufferedinput is that no matter how much data is taken into the buffer when it is flushed the

    program just reads as much data as it needs from the start of the buffer allowingwhatever else that may be in the buffer to be discarded.

    For Example :-char ch1, ch2;

    printf( "Enter two characters : " ) ;ch1 = getchar() ;ch2 = getchar() ;

    printf( "\n The characters are %c and %c\n", ch1, ch2 ) ;

    Example---- Program for interchanging two numbers without using third variable;

    #include

  • 8/9/2019 Fundamental of C in Brief.pdf

    10/85

    Sandip MalCentre for Computer Science10

    void main(){

    int a, b;printf(Enter two numbers\n\n);

    scanf(%d%d, &a, &b);a=a+b;b=a-b;a=a-b;

    printf(A=%d B=%d, a, b);}

    Question---1. Write a C program to calculate the Area of Circle.2. Write a C program to perform Addition of three numbers. Take three numbers

    through the keyboard.

  • 8/9/2019 Fundamental of C in Brief.pdf

    11/85

    Sandip MalCentre for Computer Science11

    OPERATORS AND EXPRESSIONSAn operator is a symbol that tells the computer to perform certain mathematical orlogical manipulations. Operators are used in programs to manipulate data andvariables.C operators can be classified into a number of categories. They include:

    1. Assignment Operators2. Arithmetic operators3. Relational operators4. Logical operators5. Special Assignment operators6. Increment & decrement operators7. Conditional operators8. Bitwise operators

    Assignment Operator

    int x ;x = 20 ;

    Some common notation :- lvalue -- left hand side of an assignment operationrvalue -- right hand side of an assignment operation

    Type Conversions :- the value of the right hand side of an assignment is converted tothe type of the lvalue. This may sometimes yield compiler warnings if information islost in the conversion.

    For Example :-int x ;char ch ;float f ;

    ch = x ; /* ch is assigned lower 8 bits of x, the remainingbits are

    discarded so we have a possible information loss*/

    x = f ; /* x is assigned non fractional part of f only within intrange, information loss possible */

    f = x ; /* value of x is converted to floating point */

    Multiple assignments are possible to any degree in C, the assignment operator hasright to left associativity which means that the rightmost expression is evaluated first.

    For Example :-x = y = z = 100 ;

    In this case the expression z = 100 is carried out first. This causes the value 100 to beplaced in z with the value of the whole expression being 100 also. This expressionvalue is then taken and assigned by the next assignment operator on the left i.e. x = y

    = ( z = 100 ) ;

  • 8/9/2019 Fundamental of C in Brief.pdf

    12/85

    Sandip MalCentre for Computer Science12

    Ar ithmetic Operators

    + - * / --- same rules as mathematics with * and / being evaluated before + and -.% -- modulus / remainder operator

    For Example :-

    int a = 5, b = 2, x ;float c = 5.0, d = 2.0, f ;

    x = a / b ; // integer division, x = 2.f = c / d ; // floating point division, f = 2.5.x = 5 % 2 ; // remainder operator, x = 1.

    x = 7 + 3 * 6 / 2 - 1 ; // x = 15, * and / evaluated ahead of + and -.

    Note that parentheses may be used to clarify or modify the evaluation of expressionsof any type in C in the same way as in normal arithmetic.

    x = 7 + ( 3 * 6 / 2 ) - 1 ; // clarifies order of evaluationwithout penalty

    x = ( 7 + 3 ) * 6 / ( 2 - 1 ) ; // changes order of evaluation, x = 60now.

    Precedence of Arithmetic OperatorsExpressions are evaluated using an assignment statement of the form

    variable = expression;An arithmetic expression without parentheses will be evaluated from left to rightusing the rules of the precedence of operators.

    Priority Operators Description

    1st

    2nd

    3rd

    * / %

    + -

    =

    multiplication, division, modular division

    addition, subtraction

    assignment

    Example---Determine the hierarchy of operations and evaluate the followingexpression:

    i=2*3/4+4/4+8-2+5/8

    Stepwise evaluation of this expression is shown below:

    i=2*3/4+4/4+8-2+5/8

    i=6/4+4/4+8-2+5/8 operation:*i=1+4/4+8-2+5/8 operation:/i=1+1+82+5/8 operation:/i=1+1+8-2+0 operation:/i=2+8-2+0 operation:+i=10-2+0 operation:+

  • 8/9/2019 Fundamental of C in Brief.pdf

    13/85

    Sandip MalCentre for Computer Science13

    I ncrement and Decrement Operators

    There are two special unary operators in C, Increment ++, and Decrement -- , whichcause the variable they act on to be incremented or decremented by 1 respectively.

    For Example :-x++ ; /* equivalent to x = x + 1 ; */

    ++ and -- can be used in prefix or postfix notation. In prefix notation the value of thevariable is either incremented or decremented and is then read while in postfixnotation the value of the variable is read first and is then incremented ordecremented.

    Example----#include

    #include

    void mian(){

    clrscr();int c=5;

    printf(c=%d, c);printf(c=%d, c++);printf(c=%d, ++c);printf(c=%d, c);printf(c=%d, c--);

    printf(c=%d, --c);printf(c=%d, c);

    }

    Special Assignment Operators

    Many C operators can be combined with the assignment operator as shorthandnotation

    For Example :-x = x + 10 ;

    can be replaced by

    x += 10 ;Similarly for -=, *=, /=, %=, etc.These shorthand operators improve the speed of execution as they require theexpression, the variable x in the above example, to be evaluated once rather thantwice.

    Example---#include#include

    void mian(){

    int x=20;

    i=8+0 operation:-i=8 operation:+

  • 8/9/2019 Fundamental of C in Brief.pdf

    14/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    15/85

    Sandip MalCentre for Computer Science15

    Conditional operator:A operator "?" is available in C to construct conditional expressions of the form

    exp1? exp2:exp3Where exp1, exp2 and exp3 are expressions.

    The operator ? : works as follows : exp1 is evaluated first. If it is true then theexpression exp2 is evaluated and becomes the value of the expression. If exp1 isfalse, exp3 is evaluated and its value becomes the value of the expression.For example a = 10;

    b = 15;x = (a > b) ? a:b;

    This can be achieved using the ifelse statement

    if (a > b)x = a;

    else

    x = b;Limitations:After the ?one C statement and after the : one C statement.

    ExampleWAP to find the largest of three numbers using conditional operator.#include#include

    void mian(){

    clrscr();int a, b, c;int lar;

    printf(Enter three numbers\n);scanf(%d%d%d, &a, &b, &c);lar=(a > b ? (a > c ? a: c) : (b>c ? b : c));

    printf(Largest=%d, lar);}

    Bitwise operators:These are used for manipulation of data at bit level. These operators are used fortesting the bits, or shifting them right or left. Bitwise operator may not be applied tofloat and double.

    Bitwise Operators Meaning

    & bitwise AND| bitwise OR^ bitwise exclusive OR

    > shift right.~ ones Complement

  • 8/9/2019 Fundamental of C in Brief.pdf

    16/85

    Sandip MalCentre for Computer Science16

    Type conversions in expressions:Implicit conversion:During the evaluation of the expression, if the operands are of different types, thelower type is automatically converted to the higher type before the operation

    proceeds. The result is of the higher type.There is a sequence of rules that are applied while evaluating expressions

    1. If one of the operands is long double, the other will be converted to longdouble and the result will be long double.

    2. If one of the operands is double, the other will be converted to float and theresult will be float.

    3. If one of the operands is unsigned long int, the other will be converted tounsigned long int and the result will be unsigned long int.

    4. If one of the operands is long int and the other is unsigned int, then theunsigned int operand will be converted long int.

    Conversion Hierarchy

    long double

    double

    float

    unsigned long int

    long int

    unsigned int

    int

    Short char

    Explicit conversion:C performs type conversion automatically. However, some time we want a type

    conversion in a way that is different from the automatic conversion.Explicit casting coerces the expression to be of specific type and is carried out bymeans of the cast operatorwhich has the following syntax.

    Syntax : ( type ) expression

    For Example if we have an integer x, and we wish to use floating point division in theexpression x/2 we might do the following

    ( float ) x / 2

    which causes x to be temporarily cast to a floating point value and then implicitcasting causes the whole operation to be floating point division.

    The same results could be achieved by stating the operation as

    x / 2.0

    which essentially does the same thing but the former is more obvious and descriptiveof what is happening.

  • 8/9/2019 Fundamental of C in Brief.pdf

    17/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    18/85

    Sandip MalCentre for Computer Science18

    DECISION MAKING AND BRANCHING

    Sometimes we required to execute the C program statements in a particular order. For this we need to use some decisionmaking statements.C language contains following decision making statements:

    1. ifstatement2. switchstatement3. conditional operatorstatement4. gotostatement

    Since these statements 'control' the flow of execution, they are also known as control statements. These statements arepopularly known as decision making statements.Relational operators:

    Relational operators are used to compare two operands. Expressions containing relational operatorsevaluate to true or false in C. In C, they evaluate to either 0 or 1.

    Summary of Relational Operators

    Operator Description Example Evaluation

    == Equal 5 == 4 FALSE

    5 == 5 TRUE

    != not equal 5 != 4 TRUE

    5 != 5 FALSE

    > greater than 5 > 4 TRUE

    5 > 5 FALSE

    >= greater than or equal 5 >= 4 TRUE

    5 >= 5 TRUE

    < less than 5 < 4 FALSE

    5 < 5 FALSE

    3) AND (5 > 4) TRUE

    || OR (5 > 3) OR (5 > 6) TRUE

    || OR (5 > 3) OR (5 > 4) TRUE

    ! NOT !(5 > 3) FALSE

    ! NOT !(5 > 6) TRUE

  • 8/9/2019 Fundamental of C in Brief.pdf

    19/85

    Sandip MalCentre for Computer Science19

    1. if statement: The ifstatement is a powerful decision making statement and is used to control the flow of execution ofstatements.The general form of a simple ifstatement is

    if(test expression)

    {statement block;

    }

    statement-x;

    if test expression is true, then statement block will be executed; otherwise the statement-blocked will be skipped and theexecution will jump to the statement-x.Remember, when the condition is true both the statement-block and the statement-x are executed in sequence.

    Example:

    int a =1;int b=1;

    if (a>1)

    {b=3;}

    printf(\nb=%d,b);1. (a) ifelse statement: The ifelse statementis an extension of the simple if statement. The general form is :

    if (test expression)

    {

    True block statements;

    }

    else

    {

    False block statements;

    }

    statement-x;if test expression is true, then the true block statements, immediately following the ifstatements are executed; otherwisethe false-block statements are executed. In either case, either true block or false block will be executed, not both.

    Example:

    int a =1;int b;

    if (a>1){

    b=3;}

    else{

    b=5;}

    printf(\nb=%d,b);

    1. (b) Nesting of if.else statements:When we use one ifelse statement insideother ifelse statement then we mayhave to use more than one ifelsestatement in nested form as shown below:

    if (test condition-1)

    {

    if (test condition-2)

    {

    statement-1;

    }

    else

    {statement-2;

  • 8/9/2019 Fundamental of C in Brief.pdf

    20/85

    Sandip MalCentre for Computer Science20

    }

    }

    else

    {

    statement-3;

    }

    statement-x;

    if the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the second test. If thecondition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control istransferred to the statement-x.

    Example:

    void main(){

    int a, b, c;printf(\t Enter three integers\n);scanf(%d%d%d, &a, &b, &c);

    if(a>b){

    if (a>c)printf(lar=%d, a);

    elseprintf(lar=%d, c);

    }else

    {if(b>c)

    printf(lar=%d, a);else

    printf(lar=%d, a);

    }}

    1. (c) The ifelse ladder: There is another way of putting iftogether when multi-path decisions are involved. A multi-path decision is chain of ifin which the statement associatedwith each else is an if. It takes the following generalform:

    if (condition-1)

    {

    statement-1;

    }

    else if (condition-2)

    {

    statement-2;}

    else if (condition-3)

    {

    statement-3;

    }

    else if (condition-n)

    {

    statement-n;

    }

    else

    {

    default-statements;

    }

  • 8/9/2019 Fundamental of C in Brief.pdf

    21/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    22/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    23/85

    Sandip MalCentre for Computer Science23

    b=5;}

    Same coding can be written by using of conditional operator as follows:int a = 1;int b;

    b= (a>1) ? 3 : 5When the conditional operator is used, the code becomes more concise and more efficient.

    4. The goto statement: c programming supports the gotostatement to branch unconditionally from one point to anotherin the program.Label:A label is any valid variable name, and must be followed by a colon. The label is placed immediately beforethe statement where the control is to be transferred.The general form of goto and label are shown below:

    goto label;

    ..

    ..

    .

    label:

    statement;The label can be anywhere in the program either before or after the goto label.Example:

    #includevoid main(){

    int n,x;

    printf("\n Enter a number: ");scanf("%d", &n);

    x=1;increment:

    printf("\n x=%d",x);x++;

    if(x

  • 8/9/2019 Fundamental of C in Brief.pdf

    24/85

    Sandip MalCentre for Computer Science24

    DECISION MAKING AND LOOPING

    for statement

    The for statement is most often used in situations where the programmer knows in

    advance how many times a particular set of statements are to be repeated. The forstatement is sometimes termed a counted loop.

    Syntax : for ( [initialisation] ; [condition] ; [increment] )

    [statement body] ;

    initialisation :- this is usually an assignment to set a loop counter variable forexample.condition:- determines when loop will terminate.increment:- defines how the loop control variable will change each time the loop isexecuted.

    statement body:- can be a single statement, no statement or a block of statements.

    The for statement executes as follows :-

    initialisation

    test condition

    statement body

    increment

    FALSE

    continue

    with nextiteration

    end of statement

    TRUE

    NB : The square braces above are to denote optional sections in the syntax but are not

    part of the syntax. The semi-colons must be present in the syntax.For Example : Program to print out all numbers from 1 to 100.

    #include

    void main(){int x ;

    for ( x = 1; x

  • 8/9/2019 Fundamental of C in Brief.pdf

    25/85

    Sandip MalCentre for Computer Science25

    Curly braces are used in C to denote code blocks whether in a function as in main() oras the body of a loop.For Example :- To print out all numbers from 1 to 100 and calculate their sum.

    #include

    void main(){int x, sum = 0 ;

    for ( x = 1; x

  • 8/9/2019 Fundamental of C in Brief.pdf

    26/85

    Sandip MalCentre for Computer Science26

    Sometimes a for statement may not even have a body to execute as in the followingexample where we just want to create a time delay.

    for ( t = 0; t < 1000 ; t++ ) ;

    or we could rewrite the example given above as follows

    for ( x = 1; x

  • 8/9/2019 Fundamental of C in Brief.pdf

    27/85

    Sandip MalCentre for Computer Science27

    test condition

    statement body

    FALSE

    continue

    with next

    iteration

    end of statement

    TRUE

    For Example: Program to calculate the factorial of a number. Take number through thekeyboard.

    #include void main(){

    lont int i=1;long int f=1;long int n;

    printf(Enter n);scanf(%ld, &n);

    if(n==0)printf(Factorial of %ld is 1, n);else

    {while (i

  • 8/9/2019 Fundamental of C in Brief.pdf

    28/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    29/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    30/85

    Sandip MalCentre for Computer Science30

    For Example:-#includevoid main ()

    {for ( x = 1; x

  • 8/9/2019 Fundamental of C in Brief.pdf

    31/85

    Sandip MalCentre for Computer Science31

    ARRAYSThere are times when we need to store a lot of numbers or other data items. You coulddo this by creating as many individual variables. For example, suppose you want toread in five numbers and print them.#include

    #include void main(){int al,a2,a3,a4,a5;

    printf("\nPlease Enter the five numbers : ");scanf("%d %d %d %d %d",&a1,&a2,&a3,&a4,&a5);

    printf("\n%d %d %d %d %d'',a1,a2,a3,a4,a5);}

    Note: The drawback with this approach is that if we need to read 20 numbers of same typethen it is required to create 20 variables of same type and then enter the numbers one by one.To recover this approach concept of array is introduced.

    Array:An array is a fixed sized sequenced collection of elements of the same datatype. All array elements should be either integers or float numbers or characters. Wecan store elements in an array only of same data type. Simple variable can store onlyone value at a time but array can store more than one value at a time. In the case of Cwe have to declare an arraybefore we use it in the program as same way we do todeclare any other variable.For example,

    int a[5];

    declares an array called awith five elements. Here first element will be a[0],secondelement will be a[1], third element will be a[2], fourth element will be a[3]and thefifth elements will be a[4]. In C array elements counting always start with

    0,1,2,3,4.

    Declaration of an array:

    we can declare array in C using the following method:

    type array[size];declares an array of the specified type and with size elements. The first arrayelement is array[0]and the last is array[size-1].

    int a[5];

    a [0] a[1] a[2] a[3] a[4]

    it declares that number is an array of an integers and it contains five numbers.

    float num[5];

    num[0] num[1] num[2] num[3] num[4]

  • 8/9/2019 Fundamental of C in Brief.pdf

    32/85

    Sandip MalCentre for Computer Science32

    It declares that num is an array of a float numbers and it contains five float numbers.

    Example--- Program to find the maximum element in an array elements.#include

    #include

    #define maxsize 40void main()

    {

    int a[maxsize];int n;int i, x, lar;x:; printf(\t How many number u wants to enter\n);scanf(%d, &n);if(n>maxsize)

    {printf(n is larger than maxsize);

    goto x;}

    printf(Enter the number of elements in an array\n);for(i =0;i < n; ++i)

    {printf("\nElement#: %d number : ",i+1);

    scanf("%d", &a[i]);}

    lar= a[0];for(i=1;ilar)

    lar=a[i];}

    Printf(Largest%d, lar);getche();

    }

    Question: WAP to sort the array elements either in ascending or descending order.

    Initialization of Array Elements:

    We can initialize the elements of an array using the following method:

    type array-name[ ] = { list of values};the values in the list are separated by commas and that will give the number ofelements in an array. For an example,

    int number[ ] = {10,20,30};

    10 20 30

    number[0] number[1] number[2]

    The above statement will declare the number as an array of size 3 and will assignvalues to each element of the array.

  • 8/9/2019 Fundamental of C in Brief.pdf

    33/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    34/85

    Sandip MalCentre for Computer Science34

    row=0,column=0

    row=0,column=1

    row=0,column=2

    row=0,column=3

    row=1,column=0

    row=1,column=1

    row=1,column=2

    row=1,column=3

    row=2,

    column=0

    row=2,

    column=1

    row=2,

    column=2

    row=2,

    column=3

    Representation of a two dimensional array matrix [3][4]in memory

    Example: Write a program in C to add two matrices.Solution:#include

    #include#define MAXROW 10#define MAXCOL 10

    void main()

    {int a[MAXROW][MAXCOL];int b[MAXROW][MAXCOL];int c[MAXROW][MAXCOL];

    int i,j;int r1, c1, r2, c2;

    printf(Enter row and Col of first matrix);scanf(%d%d, &r1, &c1);

    printf(Enter row and Col of second matrix);

    scanf(%d%d, &r2, &c2);if ((r1==r2) && (c1==c2)){

    printf(Matrix Addition possible);printf(Enter Element in the first matrix\n);

    for(i=0;i

  • 8/9/2019 Fundamental of C in Brief.pdf

    35/85

    Sandip MalCentre for Computer Science35

    for(j=0;j

  • 8/9/2019 Fundamental of C in Brief.pdf

    36/85

    Sandip MalCentre for Computer Science36

    The problem with scanf() function is that it terminates its input on first white space itfinds. Therefore, if the name is

    Ahmad AliThen only the string Ahmad will be read into an array name, since the blank space

    after the word Ahmad will terminate the string reading.

    If we want to read the entire name Ahmad Ali, then we may use two characterarrays of appropriate sizes. i.e.

    char name1[10], name2[10];printf(\n Please enter your name: );scanf(%s %s,name1, name2);

    Now the string Ahamdwill be assign to name1 and Aliwill be assign to name2.

    Assignment: Write a program to read your college name using keyboard.#include void main(){

    char cn1[10], cn2[10], cn3[10], cn4[10], cn5[10];

    printf(\n Enter your college name: );scanf(%s %s %s %s %s ,cn1, cn2, cn3, cn4, cn5);

    printf(\n %s %s %s %s %s, cn1, cn2, cn3, cn4, cn5);}

    Writing Strings to ScreenWe can use printf()to display string on to screen.e.g.

    char name[10] = Waljat;printf(%s, name);

    Common Operations performed on character strings:1. Reading and Writing strings2. Combining strings together (Concatenation)3. Copying one string to another string4. Comparing strings for equality5. Extracting a portion of a sting.

    Assignment: Write a program to copy one string into another sting.

    #includevoid main(){

    char string1[80], string2[80];int i;

    printf("\n Enter a string: ");scanf("%s", string1);

    for(i=0; string1[i] !='\0'; i++ ){

    string2[i] = string1[i];}

    string2[i] = '\0';printf("\n Copied String : %s", string2);

    }

  • 8/9/2019 Fundamental of C in Brief.pdf

    37/85

    Sandip MalCentre for Computer Science37

    Putting Strings Together----The process of combining two strings together is called concatenation. Let see theexample given below how strings put together

    Example---

    #includevoid main ()

    {char s1[30], s2[30], s3[30], s4[120];int i, j, k;

    printf(Enter three strings\n);scanf(%s%s%s, s1, s2, s3);for(i=0; i

  • 8/9/2019 Fundamental of C in Brief.pdf

    38/85

    Sandip MalCentre for Computer Science38

    2. strcmp() Function

    The strcmp() function compares two strings and gives value zero if they are equal.If they are not equal, it gives non-zero value. It takes the following form:

    strcmp(string1, string2);

    where string1 and string2 are character arrays.e.g.char name1[] = Waljat;char name2[] = Waljat;

    if(strcmp(name1, name2)==0){printf(\n Given strings are equal.);}

    else{

    printf(\n Given strings are not equal.);}

    3. strcpy() Function

    It takes the following form:

    strcpy(string1, string2);where string1 and string2 are character arrays. It copy the contents of string2 tostring1.e.g.char name1[10] = MUSCAT;char city[10];

    strcpy(city, name1);

    printf(\n %s, city);

    The above statements will copy the contents of array name1 to array city.4. strlen() Function

    It takes the following form:

    n = strlen(string);where string is character array and n is an integer variable.

    e.g.char city[10] = MUSCATint x;

    x = strlen(city);

    printf(\n Length of given string : %d,x);

    The above statement will give the length of string MUSCAT. It will print value6.

  • 8/9/2019 Fundamental of C in Brief.pdf

    39/85

    Sandip MalCentre for Computer Science39

    Using getchar() and putchar()

    getchar()This function read single character from the keyboard. We can store it into a

    character variable.e.g.

    char ch;ch = getchar();

    We can also use a character array to store the values read by getchar(). Thereading will be terminated when the newline character (\n) is entered.

    e.g.char line[81];char ch;

    int c = 0;

    printf(\n Enter the text. Press at the end of line \n);

    do{

    ch = getchar();line[c]=ch;c++;

    } while(ch != \n);

    c = c-1;

    line[c] = \0; // Replace \n by \0 to make line as string.

    printf(\n %s,line);The above program read a line of text containing a series of words from thekeyboard and then display the line on to the screen.

    putchar()This function display a single character on the screen.

    e.g.char ch = A;putchar(ch);

    The above statement will print character A on the screen. If we use a loop

    then with the help of putchar(), we can print a string on the screen.e.g.

    char name[7] = MUSCAT;int i;

    for(i=0; i

  • 8/9/2019 Fundamental of C in Brief.pdf

    40/85

    Sandip MalCentre for Computer Science40

    }printf(\n);

    The above statement will print the contents of array name on to the screen. Itwill print string MUSCAT.

    Using gets() and puts()

    gets()It takes the following form:gets(str);where str is a character array. It reads characters from the keyboard and storeinto str until a new line character (\n) encountered and then appends a nullcharacter (\0) to end of str.e.g.char line[81];

    printf(\nEnter a line : );gets(line);

    printf(%s, line);

    The above statements read a line of text from the keyboard and display it on tothe screen.

    puts()

    It takes the following form:puts(str);where str is a character array. It prints the value of array str and then movesthe cursor to the next line.

    e.g.char line[81];

    printf(\nEnter a line : );gets(line);

    puts(line);

    The above statements read a line of text from the keyboard and display it on tothe screen.

    Assignment: Write a program in C to count the number of characters, number ofwords and number of lines in an entered text.

    Solution:1. A word is a sequence of any characters, except escape characters and blanks.2. Two words are separated by one blank character.

    For counting the words:

    1. Read a line of Text.

  • 8/9/2019 Fundamental of C in Brief.pdf

    41/85

    Sandip MalCentre for Computer Science41

    2. Beginning from the first character in the line, look for a blank. If a blank ( ) is found or \t is found, then increment number of words by one.

    When you enter text then at last need to press Enter key again, it causes a new line

    character (\n) as input to the last line and then last line will contain only the nullcharacter (\0) because of while loop. There we have a condition if (line[0] == \0),

    then because of this condition we will come out from the while loop.

    #include #include

    void main(){

    char line[81];char ch;

    int i, c, end, tchars, twords, tlines;

    tchars=0;twords=0;tlines=0;

    printf("\n Give one space after each word.");printf("\n When completed, Press \n\n");

    printf("\n Please Enter your Text: \n");

    while (1){

    /* Reading a line of Text */c = 0;while ((ch = getchar()) != '\n'){

    line[c] = ch;c++;

    }line[c] = '\0';

    /* Counting the words in a line */

    if (line[0] == '\0'){

    break;}

    else{

    twords++;

    for (i = 0;line[i] != '\0'; i++ )

    {if((line[i] == ' ' )|| line[i] == '\t')

  • 8/9/2019 Fundamental of C in Brief.pdf

    42/85

    Sandip MalCentre for Computer Science42

    {twords++;

    }}

    }

    /* Counting lines and characters */

    tlines = tlines +1;tchars = tchars + strlen(line);

    }printf("\n Number of lines : %d", tlines);printf("\n Number of words : %d", twords);printf("\n Number of characters : %d", tchars);

    }

    Arrays of Strings

    An array of strings is in fact a two dimensional array of characters but it is moreuseful to view this as an array of individual single dimension character arrays orstrings.

    For Example :-char str_array[ 10 ] [ 30 ] ;

    where the row index is used to access the individual row strings and where thecolumn index is the size of each string, thus str_array is an array of 10 strings eachwith a maximum size of 29 characters leaving one extra for the terminating nullcharacter.

    For Example :- Program to read strings into str_array and print them out character bycharacter.

    #include

    char str_array[10][30] ;

    void main(){int i, j ;

    puts("Enter ten strings\n") ;

    for ( i = 0 ; i < 10; i++ ) // read in as strings so a single for loopsuffices

    {printf( " %d : ", i + 1) ;

  • 8/9/2019 Fundamental of C in Brief.pdf

    43/85

    Sandip MalCentre for Computer Science43

    gets( str_array[i] ) ;}

    for ( i = 0; i < 10; i++ ) // printed out as individualcharacters so a

    { // nested for loop structure is requiredfor ( j=0; str_array[i][j] != '\0' ; j++ )

    putchar ( str_array[i][j] ) ;putchar( '\n' ) ;}

    }

  • 8/9/2019 Fundamental of C in Brief.pdf

    44/85

    Sandip MalCentre for Computer Science44

    FUNCTIONSFunctions: Function is a block of statements that perform a particular task.C functions can be classified into two categories:

    1. Library functions: The functions are not required to be written by users,called library functions. Example are printf(), scanf().etc.

    2. User defined functions: The functions which are required to be written byusers, called user-defined functions. main() is an example of user definedfunctions.

    Main () function:Every C program must have a one main () function. The programexecution begins with main () function. It is a special function which is declared bythe program and defined by the user.

    Need for user defined functions:When the program become too large and complexthen it is very difficult to testing, maintaining and debugging. If a program is dividedinto small parts, then each part may be handled and coded separately. Thesesubprograms called functions. It gives the following advantages:

    1. They introduce the top-down modular programming approach.2. The length of the program can be reduced by using the functions.3. It is easy to locate any error in the program.4. A function can be used by the other programs.

    Defining of a FunctionsA function has the following elements:

    1. Function name2. Function type3. List of arguments

    4. Local variable declarations5. Function statements6. A return statement

    We must define a function either above the main () function or below the main ()function. A general format of a function is given below:

    function_type function_name (argument- list)

    {

    local variable declaration;

    statement1;

    statement2;

    .

    .

    .

    return statement;

    }

    A local variable is a variable that is defined inside a function or block.A function may or may not send back any value to the calling function. This is donethrough the returnstatement.When a function reaches its return statement, the control is transferred back to thecalling program.

    In absence of a return statement, we use voidin place of function type.

  • 8/9/2019 Fundamental of C in Brief.pdf

    45/85

    Sandip MalCentre for Computer Science45

    Calling a function:A function can be called by simply using the function name followed by a list ofactual arguments, if any, enclosed in parentheses. When the compiler sees a functioncall, the control is transferred to the function. Then function is executed line by line. Ifreturn statement is there inside the function then a value is returned to the calling

    function.

    Example of functions:(a)void main()

    {float sum (float x, float y); /*function prototype*/float x; /* local variable*/.x = sum (3.0, 2.0); /* function Call */.

    }

    float sum (float x, float y) /* function Header */{

    float result;result = x + y;return (result);

    }

    (b)void main(){

    void sum (int a, int b); /*function prototype*/int x;.sum(2, 3);.

    }void sum (int a, int b){

    int c;c=a+b;

    printf(\nSum = %d,c);}

    (c) void main(){

    void display(void); /*function prototype*/.display();.

    }void display (void){

    printf(\n No type and No arguments);

    }

  • 8/9/2019 Fundamental of C in Brief.pdf

    46/85

    Sandip MalCentre for Computer Science46

    Function Declaration (Function Prototype)All functions in a C program must be declared, before they are invoked. A functiondeclaration contain function_type, function_name and argument list. It has thefollowing format:

    function_type function_name (argument-list);e.g.

    float mul (float a, float b);orfloat mul (float, float );int sum (int a, int b);

    When a function does not take any argument and does not return any value, itsprototype is written as:

    void display(void);

    Type of Arguments / Parameters

    There are two types of arguments:1. Formal arguments: The arguments present in the function header are

    called formal arguments.2. Actual arguments:The arguments present in the function call inside main

    ()are called actual arguments.When we call a function the types of actual arguments and formal arguments must besame.e.g.

    void main(){

    int x;.sum(2, 3); /* 2 and 3 are actual arguments */.

    }void sum (int a, int b) /* a and b are formal arguments */{

    int c;c=a+b;

    printf(\nSum = %d,c);}

    Category (Types) of Functions

    There are following types of functions:1. Functions with no arguments and no return values2. Functions with arguments and no return values3. Functions with arguments and one return values4. Functions with no arguments but return a value5. Functions that return multiple values

    1. Functions with no arguments and no return valuesWhen a function has no arguments and no return values, it does not take any datafrom the calling function and does not give any value to the calling function.

    e.g.

  • 8/9/2019 Fundamental of C in Brief.pdf

    47/85

    Sandip MalCentre for Computer Science47

    void main(){

    void sum(void); /*function prototype*/sum();

    }

    void sum(void){

    int a, b, c;

    a = 5;b = 8;c = a+b;

    printf(\n Sum of numbers: %d, c);}

    2. Functions with arguments and no return valuesWhen a function has arguments and no return values, it takes data from the callingfunction in form of arguments and does not give any value to the calling function.The actual and formal arguments should match in number, type, and order. Thevalues of actual arguments are assigned to the formal arguments on a one to one

    basis, starting with the first argument.Remember that, when a function call is made, only a copy of the values of actualarguments is passed into the called function. What occurs inside the function willhave no effect on the variables used in the actual argument list.e.g.

    void main(){

    void sum(int a, int b);int a, b;

    a = 5;b = 8;

    sum(a, b);}

    void sum(int a, int b){

    int c;

    c = a + b;

    printf(\n Sum of numbers: %d, c);}

    3. Functions with arguments and one return valuesWhen a function has arguments and one return value, it takes data from the calling

    function in form of arguments and gives a value to the calling function. For acceptinga return value in calling function, a special type variable is used.

  • 8/9/2019 Fundamental of C in Brief.pdf

    48/85

    Sandip MalCentre for Computer Science48

    e.g.void main(){

    int sum(int a, int b);int a, b, c;

    a = 5;b = 8;

    c = sum(a, b);printf(\n Sum of numbers: %d, c);

    }

    int sum(int a, int b){

    int t;

    t = a+b;return (t);

    }

    4. Functions with no arguments but return a valueWhen a function has no arguments and one return value, it does not take data fromthe calling function and gives a value to the calling function. For accepting a returnvalue in calling function, a special type variable is used.e.g.

    void main(){

    int sum(void);int c;

    c = sum();

    printf(\n Sum of numbers: %d, c);}

    int sum(void)

    { int a, b, t;

    a = 5;b = 8;

    t = a+b;

    return (t);}

  • 8/9/2019 Fundamental of C in Brief.pdf

    49/85

    Sandip MalCentre for Computer Science49

    5. Functions that return multiple valuesA return statement can return only one value but when we want to return multiplevalues from the calling function then we do not use return statement for returningvalue. We use address of operator (&) and indirection operator (*) for returningmultiple values.

    e.g.void main(){

    void moperation(int a, int b, int *sum, int *diff);int a, b, c, d;

    a = 5;b = 8;

    moperation(a, b, &c, &d);

    printf(\n Sum of numbers: %d, c);

    printf(\n Difference of numbers : % d, d);}

    void moperation(int a, int b, int *sum, int *diff){

    *sum = a + b;

    *diff = ab;}

    Nesting of functionsWhen a function is called from within another function (not from the main()), thismechanism is called nesting of functions.main() call function1, which calls function2, which calls function3,and so on.

    This is nesting of functions.e.g.

    void main(){

    void sum(void);

    sum();}void sum(void){

    void display(int c);int a, b, c;

    a = 5;b = 8;c = a+b;

    display(c); /*Nesting of Functions*/}

  • 8/9/2019 Fundamental of C in Brief.pdf

    50/85

    Sandip MalCentre for Computer Science50

    void display(int c){

    printf("\n Sum of entered numbers: %d", c);}

    Here function main () calls function sum () then function sum () calls functiondisplay (). This is the example of nesting of functions.

    Recursion:

    Recursion is a mechanism in which a function calls itself.Recursion solves the large problems by breaking it down to smaller problems ofsimilar types.Recursive functions are useful in evaluating certain types of mathematical functions.e.g. factorial, fibonacci seriesetc.

    Assignment: Write a C program for finding factorials of a given number using

    recursion.We can create a function factorial (int n) such that

    factorial (n) = n * factorial (n-1)

    When n = 1, factorial (1) = 1.Consider the example of finding the factorial of a number. Let the number be n = 5;Then factorial of 5 = 5 * factorial (4)

    = 5 * 4 * factorial (3)= 5 * 4 * 3 * factorial (2)= 5 * 4 * 3 * 2 * factorial (1)= 5 * 4 * 3 * 2 * 1= 120

    /* Program to find factorial of a number using recursion */

    #include void main(){

    int factorial (int n);int n, facto;printf("\n Enter value for n : ");scanf("%d", &n);

    facto = factorial(n);

    printf("\n Factorial of given number: %d ", facto);

    }int factorial (int n)

    {int facto;

  • 8/9/2019 Fundamental of C in Brief.pdf

    51/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    52/85

    Sandip MalCentre for Computer Science52

    Arguments passing methodsThere are two methods for passing arguments to the function:

    1. Call by value2. Call by reference

    1. Call by value

    In this method only the copy of actual arguments is sent to the formal arguments. Theoriginal values of the actual arguments do not change even though the value of theformal arguments change.

    #includevoid main(){void swap(int a, int b);int a, b;

    a = 8;

    b = 5;printf("\nValue of a : %d",a);printf("\nValue of b : %d",b);swap(a, b);

    printf("\nAfter Execution of SWAP()");printf("\nValue of a : %d",a);printf("\nValue of b : %d",b);}void swap(int a, int b){int t;

    t = a;a = b;

    b = a;}Here in main() function, we pass the copy of value a and b to the function swap().The change occurred in function swap() will not affect the values of a and b infunction main().

    2. Call by reference

    In this method, the address (reference) of the actual arguments is sent to the formalarguments. If there will be any change in the values of formal arguments that willchange the values of actual arguments in the calling functions because both actualarguments and formal arguments refer the same values.

    #includevoid main(){

    void swap(int *a, int *b);int a, b;

    a = 8;

    b = 5;

  • 8/9/2019 Fundamental of C in Brief.pdf

    53/85

    Sandip MalCentre for Computer Science53

    printf("\nValue of a : %d",a);printf("\nValue of b : %d",b);

    swap(&a, &b);

    printf("\nAfter Execution of SWAP()");printf("\nValue of a : %d",a);printf("\nValue of b : %d",b);

    }void swap(int *a, int *b){

    int t;

    t = *a;*a = *b;*b = t;

    }Here in main() function, we passes the references to values of aand bto the functionswap(). The change occurred in function swap() will affect the values of a and b infunction main() also.

    Storage classes in CStorage classes are used to define scope and visibility of variables or functionsThere are four types of variable storage classes available in C:

    1. Local / Automatic variables2. Global / External variables3. Static variables4. Register variables

    Scope: The scope of a variable determines over what region of the program a variableis actually available for the use.Visibility:It refers to the accessibility of a variable from the memory.

    1. Local / Automatic variablesThe variables declared inside functions or blocks are called local variables. They arecreated when function is called and destroyed automatically when the task of thefunction is over.

    void main(){.int x;

    }

    or we may also use the keyword auto to declare automatic variables explicitly.

    void main(){

    .autoint x;

  • 8/9/2019 Fundamental of C in Brief.pdf

    54/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    55/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    56/85

    Sandip MalCentre for Computer Science56

    The name of an array without any index is the address of the first element of the arrayand hence of the whole array as it is stored contiguously. However we need to knowthe size of the array in the function - either by passing an extra parameter or by usingthe sizeof operator..

    For Example :-void main(){int array[20] ;

    func1( array ) ; /* passes pointer to array to func1 */}

    Since we are passing the address of the array the function will be able to manipulatethe actual data of the array in main(). This is call by reference as we are not making acopy of the data but are instead passing its address to the function. Thus the called

    function is manipulating the same data space as the calling function.func1

    x

    main()

    arrayrefers to data

    at address 1000

    data at

    address 1000no data here

    In the function receiving the array the formal parameters can be declared in one ofthree almost equivalent ways as follows :-

    As a sized array :

    func1 ( int x[10] ) {...}

    As an unsized array :

    func1 ( int x[ ] ) {...}

    As an actual pointer

    func1 ( int *x ) {...}

    All three methods are identical because each tells us that in this case the address of anarray of integers is to be expected.

    Note however that in cases 2 and 3 above where we specify the formal parameter asan unsized array or simply as a pointer we cannot determine the size of the array

    passed in using the sizeof operator as the compiler does not know what dimensionsthe array has at this point. Instead sizeof returns the size of the pointer itself, two inthe case of near pointers in a 16-bit system but four in 32-bit systems.For Example :- Program to calculate the average value of an array of doubles.

  • 8/9/2019 Fundamental of C in Brief.pdf

    57/85

    Sandip MalCentre for Computer Science57

    #include void read_array( double array[ ], int size ) ;double mean( double array[ ], int size ) ;

    void main(){double data[ 100 ] ;double average ;

    read_array( data, 100 ) ;average = mean( data, 100 ) ;}

    void read_array( double array[ ], int size ){

    int i ;

    for ( i = 0; i

  • 8/9/2019 Fundamental of C in Brief.pdf

    58/85

    Sandip MalCentre for Computer Science58

    elseprintf( "%s is not a palindrome\n") ;

    }

    int palin ( char array[ ] )

    {int i = 0, j = 0 ;

    while ( array[j++] ) ; /* get length of string i.e. increment j while array[j] != '\0' */j -= 2 ; /* move back two -- gone one beyond '\0' */

    for ( ; i < j ; i++, j-- )if ( array[ i ] != array[ j ]

    return 0 ; /* return value 0 if not apalindrome */

    return 1 ; /* otherwise it is a palindrome */}

  • 8/9/2019 Fundamental of C in Brief.pdf

    59/85

    Sandip MalCentre for Computer Science59

    STRUCTURES AND UNIONS

    STRUCTURES

    A Structure is a data type suitable for grouping data elements together. Lets create anew data structure suitable for storing the date. The elements or fields which make upthe structure use the four basic data types. As the storage requirements for a structurecannot be known by the compiler, a definition for the structure is first required. Thisallows the compiler to determine the storage allocation needed, and also identifies thevarious sub-fields of the structure.

    struct date {int month;int day;int year;

    };

    This declares a NEW data type called date. This date structure consists of three basicdata elements, all of type integer. This is a definition to the compiler.It does notcreate any storage space and cannot be used as a variable. In essence, its a new datatype keyword, like intand char, and can now be used to create variables. Other datastructures may be defined as consisting of the same composition as the datestructure,

    struct date todays_date;

    defines a variable called todays_dateto be of the same data type as that of the newlydefined data type struct date.

    ASSIGNING VALUES TO STRUCTURE ELEMENTS

    To assign todays date to the individual elements of the structure todays_date, thestatement

    todays_date.day = 21;todays_date.month = 07;todays_date.year = 1985;

    is used. NOTE the use of the .element to reference the individual elements withintodays_date.

    /* Program to illustrate a structure */#include

    struct date { /* global definition of type date */int month;int day;int year;

    };

    main(){

    struct date today;

    today.month = 10;today.day = 14;today.year = 1995;

    printf("Todays date is %d/%d/%d.\n", \today.month, today.day, today.year );

  • 8/9/2019 Fundamental of C in Brief.pdf

    60/85

    Sandip MalCentre for Computer Science60

    }

    I niti alising Structures

    Structure elements or fields can be initialised to specific values as follows :-

    struct id {char name[30] ;int id_no ;} ;

    struct id student = { "John", 4563 } ;

    Structure Assignment

    The name of a structure variable can be used on its own to reference the completestructure. So instead of having to assign all structure element values separately, a

    single assignment statement may be used to assign the values of one structure toanother structure of the same type.

    For Example :-struct {

    int a, b ;} x = {1, 2 }, y ;

    y = x ; // assigns values of all fields in x to fields in y

    ARRAYS OF STRUCTURESConsider the following,

    struct date {int month, day, year;

    };

    Lets now create an array called birthdaysof the same data type as the structure date

    struct date birthdays[5];

    This creates an array of 5 elements which have the structure of date.

    birthdays[1].month = 12;birthdays[1].day = 04;birthdays[1].year = 1998;--birthdays[1].year;

    Structures and ArraysStructures can also contain arrays.

    struct month {

    int number_of_days;char name[4];

  • 8/9/2019 Fundamental of C in Brief.pdf

    61/85

    Sandip MalCentre for Computer Science61

    };

    static struct month this_month = { 31, "Jan" };

    this_month.number_of_days = 31;strcpy( this_month.name, "Jan" );

    printf("The month is %s\n", this_month.name );

    Note that the array namehas an extra element to hold the end of string nul character.

    Variations in Declaring StructuresConsider the following,

    struct date {int month, day, year;

    } todays_date, purchase_date;

    or another way is,

    struct date {int month, day, year;} todays_date = { 9,25,1985 };

    or, how about an array of structures similar to date,

    struct date {int month, day, year;

    } dates [100];

    Declaring structures in this way, however, prevents you from using the structuredefinition later in the program. The structure definition is thus bound to the variablename which follows the right brace of the structures definition.

    #include

    struct date { /* Global definition of date */int day, month, year;

    };

    main(){

    struct date dates[5];int i;

    for( i = 0; i < 5; ++i ){printf("Please enter the date (dd:mm:yy)" );scanf("%d:%d:%d", &dates[i].day, &dates[i].month, &dates[i].year );

    }for( i = 0; i < 5; ++i ){

    printf("%d:%d:%d", dates[i].day, dates[i].month, dates[i].year );}

    }

    Additi onal F eatures of Structures

    (a) The values of a structure variable can be assigned to another structure variableof the same type using the assignment operator. It is not necessary to copythe structure elements piece-meal. Obviously, programmers prefer assignmentto piece-meal copying. This is shown in the following example.

    main(){

  • 8/9/2019 Fundamental of C in Brief.pdf

    62/85

    Sandip MalCentre for Computer Science62

    structemployee{char name[10];int age;float salary;

    };structemployee e1={"Sanjay",30,5500.50};structemployee e2,e3;

    /*piece-mealcopying*/strcpy(e2.name,e1.name);e2.age=e1.age;e2.salary=e1.salary;

    /*copyingallelementsatonego*/e3=e2;

    printf("\n%s%d%f",e1.name,e1.age,e1.salary);printf("\n%s%d%f",e2.name,e2.age,e2.salary);printf("\n%s%d%f",e3.name,e3.age,e3.salary);}

    Ability to copy the contents of all structure elements of one variable into thecorresponding elements of another structure variable is rather surprising, since C doesnot allow assigning the contents of one array to another just by equating the two.This copying of all structure elements at one go has been possible only becausethe structure elements are stored in contiguous memory locations. Had this not beenso, we would have been required to copy structure variables element by element. And

    who knows, had this been so, structures would not have become popular at all.

    (b) One structure can be nested within another structure. Using this facility complexdata types can be created. The following program shows nested structures at work.

    main(){structaddresscharphone[15];char city[25];intpin;};

    structemp{char name[25];structaddress a;};structemp e={"jeru","531046","nagpur",10};

    printf("\nname=%sphone=%s",e.name,e.a.phone);printf("\ncity=%spin=%d",e.a.city,e.a.pin);}

    And here is the output...

  • 8/9/2019 Fundamental of C in Brief.pdf

    63/85

    Sandip MalCentre for Computer Science63

    name=jeruphone=531046city=nagpurpin=10

    Notice the method used to access the element of a structure that is part of anotherstructure. For this the dot operator is used twice, as in the expression,

    e.a.pin or e.a.city(c) Like an ordinary variable, a structure variable can also be passed to afunction. We may either pass individual structure elements or the entire structurevariable at one go. Let us examine both the approaches one by one usingsuitable programs.

    /*Passingindividualstructureelements*/main(){structbook{char name[25] ; char author[25] ;

    int callno;};structbookb1={"LetusC","YPK",101};

    display(b1.name,b1.author,b1.callno);}

    display(char *s,char *t,int n){

    printf("\n%s%s%d",s,t,n);}

    And here is the output...

    LetusCYPK101

    Observe that in the declaration of the structure, name and authorhave been declared as arrays. Therefore, when we call the functiondisplay( ) using,

    display(b1.name,b1.author,b1.callno);we are passing the base addresses of the arrays name and author, but the valuestored in callno. Thus, this is a mixed calla call by reference as well as a call by

    value.It can be immediately realized that to pass individual elements would become moretedious as the number of structure elements go on increasing. A better waywould be to pass the entire structure variable at a time. This method is shown in thefollowing program.

    structbook{char name[25];char author[25];int callno;

    };

  • 8/9/2019 Fundamental of C in Brief.pdf

    64/85

  • 8/9/2019 Fundamental of C in Brief.pdf

    65/85

    Sandip MalCentre for Computer Science65

    POINTERS

    Pointers are without a doubt one of the most important mechanisms in C. They are themeans by which we implement call by reference function calls, they are closely

    related to arrays and strings in C, they are fundamental to utilising C's dynamicmemory allocation features, and they can lead to faster and more efficient code whenused correctly.

    A pointer is a variable that is used to store a memory address. Most commonly theaddress is the location of another variable in memory.

    If one variable holds the address of another then it is said to point to the secondvariable.

    Address Value Variable

    10001004 1012 ivar_ptr

    1008

    1012 23 ivar

    1016

    In the above illustration ivar is a variable of type int with a value 23 and stored atmemory location 1012. ivar_ptr is a variable of type pointer to intwhich has a valueof 1012 and is stored at memory location 1004. Thus ivar_ptr is said to point to thevariable ivar and allows us to refer indirectly to it in memory.

    NB : It should be remembered that ivar_ptr is a variable itself with a specific piece ofmemory associated with it, in this 32-bit case four bytes at address 1004 which is usedto store an address.

    6.1 Pointer Variables

    Pointers like all other variables in C must be declared as such prior to use.

    Syntax : type *ptr ;

    which indicates thatptr is a pointer to a variable of type type. For example

    int *ptr ;

    declares a pointer ptr to variables of type int.

    NB:The type of the pointer variable ptr is int *. The declaration of a pointer variablenormally sets aside just two or four bytes of storage for the pointer whatever it isdefined to point to.

    In 16-bit systems two byte pointers are termed near pointers and are used insmall memory model programs where all addresses are just segment offset addresses

    and 16 bits in length. In larger memory model programs addresses include segment

  • 8/9/2019 Fundamental of C in Brief.pdf

    66/85

    Sandip MalCentre for Computer Science66

    and offset addresses and are 32 bits long and thus pointers are 4 bytes in size and aretermed far pointers.

    In 32-bit systems we have a flat address system where every part of memory isaccessible using 32-bit pointers.

    6.2 Pointer Operators * and &

    &is a unary operator that returns the address of its operand which must be a variable.

    For Example :-int *m ;int count = 125, i ; /* m is a pointer to int, count, i are integers */m = &count ;

    The address of the variable count is placed in the pointer variable m.

    The * operator is the complement of the address operator & and is normally termedthe indirection operator. Like the & operator it is a unary operator and it returns thevalueof the variable located at the address its operand stores.

    For Example :-i = *m ;

    assigns the value which is located at the memory location whose address is stored inm, to the integer i. So essentially in this case we have assigned the value of thevariable count to the variable i. The final situation is illustrated below.

    125 125 1000

    1000 1724 1824

    count mi

    indirection

    One of the most frequent causes of error when dealing with pointers is using anuninitialised pointer. Pointers should be initialised when they are declared or in anassignment statement. Like any variable if you do not specifically assign a value to a

    pointer variable it may contain any value. This is extremely dangerous when dealingwith pointers because the pointer may point to any arbitrary location in memory,

    possibly to an unused location but also possibly to a memory location that is used bythe operating system. If your program tries to change the value at this address it maycause the whole system to crash. Therefore it is important to initialise all pointers

    before use either explicitly in your program or when defining the pointer.

    A pointer may also be initialised to 0 ( zero ) or NULL which means it is pointing atnothing. This will cause a run-time error if the pointer is inadvertently used in thisstate. It is useful to be able to test if a pointer has a null value or not as a means ofdetermining if it is pointing at something useful in a program.

  • 8/9/2019 Fundamental of C in Brief.pdf

    67/85

    Sandip MalCentre for Computer Science67

    Example1main(){

    int i=3;printf("\nAddressofi=%u",&i);printf("\nValueofi=%d",i);

    }

    Example2main(){

    int i=3;

    printf("\nAddressofi=%u",&i);printf("\nValueofi=%d",i);printf("\nValueofi=%d",*(&i));

    }

    Example3

    main(){

    int i=3;int *j;

    j=&i;printf("\nAddressofi=%u",&i);printf("\nAddressofi=%u",j);printf("\nAddressofj=%u",&j); printf("\nValueofj=%u",j);printf("\nValueofi=%d",i);printf("\nValueofi=%d",*(&i));

    printf("\nValueofi=%d",*j);}

    Example-4main(){

    int i=3,*j,**k;

    j=&i;k=&j;printf("\nAddressofi=%u",&i);printf("\nAddressofi=%u",j);

    printf("\nAddressofi=%u",*k); printf("\nAddressofj=%u",&j) ; printf ("\nAddressofj=%u",k ) ; printf ( "\nAddress of k =%u",&k); printf("\nValueofj =%u",j);printf("\nValueofk =%u",k);printf("\nValueofi =%d",i);printf("\nValueofi =%d",*(&i));printf("\nValueofi =%d",*j);printf("\nValueofi =%d",**k);

    }

  • 8/9/2019 Fundamental of C in Brief.pdf

    68/85

    Sandip MalCentre for Computer Science68

    Pointers and Arrays

    There is a very close relationship between pointer and array notation in C. As we haveseen already the name of an array ( or string ) is actually the address in memory of thearray and so it is essentially a constant pointer.

    For Example :-char str[80], *ptr ;

    ptr = str ; /* causes ptr to point to start of string str */ptr = &str[0] ; /* this performs the same as above */

    It is illegal however to do the following

    str = ptr ; /* illegal*/

    as str is a constant pointer and so its value i.e. the address it holds cannot be changed.

    Instead of using the normal method of accessing array elements using an index we canuse pointers in much the same way to access them as follows.

    char str[80], *ptr , ch;

    ptr = str ; // position the pointer appropriately

    *ptr = 'a' ; // access first element i.e. str[0]ch = *( ptr + 1 ) ; // access second element i.e. str[1]

    Thus *( array + index ) is equivalent to array[index].

    Note that the parentheses are necessary above as the precedence of * is higher thanthat of +. The expression

    ch = *ptr + 1 ;

    for example says to access the character pointed to by ptr ( str[0] in above examplewith value a) and to add the value 1 to it. This causes the ASCII value of a to be

    incremented by 1 so that the value assigned to the variable ch is b.

    In fact so close is the relationship between the two forms that we can do the following

    int x[10], *ptr ;

    ptr = x ;ptr[4] = 10 ; /* accesses element 5 of array by indexing a pointer*/

    Example---#includevoid main()

    {int x[]={10, 20, 30, 40, 50};

    int I;int *p;

  • 8/9/2019 Fundamental of C in Brief.pdf

    69/85

    Sandip MalCentre for Computer Science69

    p=&x[0];for(i=0;i

  • 8/9/2019 Fundamental of C in Brief.pdf

    70/85

    Sandip MalCentre for Computer Science70

    by 4. Likewise a pointer to type char would be incremented by 1, a pointer to float by4, etc.

    Similarly we can carry out integer subtraction to move the pointer backwards inmemory.

    ptr = ptr - 1 ;ptr -= 10 ;

    The shorthand operators ++ and -- can also be used with pointers. In our continuingexample with integers the statement ptr++ ; will cause the address in ptr to beincremented by 4 and so point to the next integer in memory and similarly ptr-- ; willcause the address in ptr to be decremented by 4 and point to the previous integer inmemory.

    NB :Two pointer variables may not be added together ( it does not make any logical

    sense ).

    char *p1, *p2 ;p1 = p1 + p2 ; /* illegal operation*/

    Two pointers may however be subtracted as follows.

    int *p1, *p2, array[3], count ;p1 = array ;p2 = &array[2] ;

    count = p2 - p1 ; /* legal */The result of such an operation is not however a pointer, it is the number of elementsof the base type of the pointer that lie between the two pointers in memory.

    Comparisons

    We can compare pointers using the relational operators ==, to establishwhether two pointers point to the same location, to a lower location in memory, or toa higher location in memory. These operations are again used in conjunction witharrays when dealing with sorting algorithms etc.

    For Example :- Writing our own version of the puts() standard library function.

    1.Using array notationvoid puts( const char s[ ] ) /* const keyword makes string contents read only */

    {int i ;

    for ( i = 0; s[i] ; i++ )putchar( s[i] ) ;

    putchar( '\n' ) ;}

  • 8/9/2019 Fundamental of C in Brief.pdf

    71/85

    Sandip MalCentre for Computer Science71

    2.Using pointer notationvoid puts( const char *s ) // char *const s would make pointer unalterable{while ( *s )

    putchar( *s++ ) ;

    putchar( '\n' ) ;}

    As you can see by comparing the two versions above the second version usingpointers is a much simpler version of the function. No extra variables are required andit is more efficient as we will see because of its use of pointer indirection.

    For Example :- Palindrome program using pointers.

    #include int palin( char * ) ; /* Function to determine if array is a palindrome. returns 1 if it is a palindrome, 0 otherwise */

    void main( ){char str[30], c ;

    puts( "Enter test string" ) ;gets( str ) ;

    if ( palin( str ) )printf( "%s is a palindrome\n", str ) ;

    elseprintf( "%s is not a palindrome\n") ;

    }

    int palin ( char *str ){char *ptr ;

    ptr = str ;while ( *ptr )

    ptr++ ; /* get length of string i.e. increment ptr while *ptr != '\0' */ptr-- ; /* move back onefrom '\0' */

    while ( str < ptr )if ( *str++ != *ptr-- )return 0 ; /* return value 0 if not a palindrome */

    return 1 ; /* otherwise it is a palindrome */}

  • 8/9/2019 Fundamental of C in Brief.pdf

    72/85

    Sandip MalCentre for Computer Science72

    Arrays of Pointers

    It is possible to declare arrays of pointers in C the same as any other 'type'. Forexample

    int *x[10] ;

    declares an array of ten integer pointers.

    To make one of the pointers point to a variable one might do the following.

    x[ 2 ] = &var ;

    To access the value pointed to by x[ 2 ] we would do the following

    *x[ 2 ]

    which simply de-references the pointer x[ 2 ] using the * operator.

    Passing this array to a function can be done by treating it the same as a normal arraywhich happens to be an array of elements of type int *.

    For Example : -void display( int *q[ ], int size ){int t ;for ( t=0; t < size; t++ )

    printf( "%d ", *q[t] ) ;}

    Note that q is actually a pointer to an array of pointers as we will see later on withmultiple indirection.

    Example#include

    void main(){

    int x=10, y=20, z=50, m=60;

    int p[4];p[0]=&x; p[1]=&y; p[2]=&z; p[3]=&m;int i;

    for(i=0;i

  • 8/9/2019 Fundamental of C in Brief.pdf

    73/85

    Sandip MalCentre for Computer Science73

    Pointers to Functions

    A function even though not a variable still has a physical address in memory and thisaddress may be assigned to a pointer. When a function is called it essentially causesan execution jump in the program to the location in memory where the instructionscontained in the function are stored so it is possible to call a function using a pointer

    to a function.

    The address of a function is obtained by just using the function name without anyparentheses, parameters or return type in much the same way as the name of an arrayis the address of the array.

    A pointer to a function is declared as follows

    Syntax : ret_type ( * fptr ) ( parameter list ) ;

    where fptr is declared to be a pointer to a function which takes parameters of the

    form indicated in the parameter list and returns a value of type ret_type.

    The parentheses around * fptrare required because without them the declaration

    ret_type * fptr( parameter list ) ;

    just declares a function fptr which returns a pointer to type ret_type !

    To assign a function to a pointer we might simply do the following

    int (*fptr)( ) ;

    fptr = getchar ; /* standard library function */

    To call the function using a pointer we can do either of the following

    ch = (*fptr)( ) ;ch = fptr( ) ;

    Example :- Program to compare two strings using a comparison function passed as a

    parameter.

    #include #include void check( char *a, char *b, int ( * cmp ) ( ) );

    void main( ){char s1[80], s2[80] ;int (*p)( ) ;

    p = strcmp ;

  • 8/9/2019 Fundamental of C in Brief.pdf

    74/85

    Sandip MalCentre for Computer Science74

    gets(s1) ;gets( s2 );

    check( s1, s2, p ) ;}

    void check ( char *a, char *b, int (* cmp)( ) ){if ( ! cmp( a, b ) )

    puts( "equal" ) ;else

    puts( "not equal") ;}

    Note that even though we do not specify parameters to the function pointer in theprototype or declarator of the function we must specify them when actually calling thefunction.

    Note also that instead of using an explicitly declared pointer variable to call therequired function in main() we could make the call as follows

    check( s1, s2, strcmp ) ;

    where we essentially pass a constant pointer to strcmp( ).

    Pointers and Structures

    As we have said already we need call by reference calls which are much moreefficient than normal call by value calls when passing structures as parameters. Thisapplies even if we do not intend the function to change the structure argument.

    A structure pointer is declared in the same way as any pointer for example

    struct address {char name[20] ;char street[20] ;} ;

    struct address person ;struct address *addr_ptr ;

    declares a pointer addr_ptr to data typestruct address.

    To point to the variable person declared above we simply write

    addr_ptr = &person ;

    which assigns the address of person to addr_ptr.

    To access the elements using a pointer we need a new operator called the arrowoperator, ->, which can be used only with structure pointers. For example

    puts( addr_ptr -> name ) ;

  • 8/9/2019 Fundamental of C in Brief.pdf

    75/85

    Sandip MalCentre for Computer Science75

    For Example :- Program using a structure to store time values.

    #include

    struct time_var {int hours, minutes, seconds ;} ;

    void display ( const struct time_var * ) ;/* note structure pointer and const */

    void main(){struct time_var time ;

    time.hours = 12 ;time.minutes = 0 ;

    time.seconds = 0 ;display( &time ) ;}void display( const struct time_var *t ){

    printf( "%2d:%2d;%2d\n", t -> hours, t -> minutes, t -> seconds ) ;}

    Note that even though we are not changing any values in the structure variable we stillemploy call by reference for speed and efficiency. To clarify this situation the constkeyword has been employed.

  • 8/9/2019 Fundamental of C in Brief.pdf

    76/85

    Sandip MalCentre for Computer Science76

    FILE MANAGEMENTThe C standard library I/O functions allow you to read and write data to both files anddevices. There are no predefined file structures in C, all data being treated as asequence of bytes. These I/O functions may be broken into two different categories :stream I/O and low-level I/O.

    The stream I/O functions treat a data file as a stream of individual characters. Theappropriate stream function can provide buffered, formatted or unformatted input andoutput of data, ranging from single characters to complicated structures. Bufferingstreamlines the I/O process by providing temporary storage for data which takes awaythe burden from the system of writing each item of data directly and instead allowsthe buffer to fill before causing the data to be written.The low-level I/O system on the other hand does not perform any buffering orformatting of data --instead it makes direct use of the system's I/O capabilities totransfer usually large blocks of information.

    8.1 Stream I/O

    The C I/O system provides a consistent interface to the programmer independent ofthe actual device being accessed. This interface is termed a streamin C and the actualdevice is termed a file. A device may be a disk or tape drive, the screen, printer port,etc. but this does not bother the programmer because the stream interface is designedto be largely device independent. All I/O through the keyboard and screen that wehave seen so far is in fact done through special standard streams called stdinandstdoutfor input and output respectivel