cppt saved

402
12/25/21 Version-1.2 1 C Programming

Upload: gayathri-suresh

Post on 21-Apr-2017

245 views

Category:

Documents


0 download

TRANSCRIPT

  • C

    Programming

    Version-1.2

  • Slides Prepared By: Vikas karanthand Leelavati

    Version-1.2

  • ObjectivesWhat is programming

    Types of Programming Languages

    Need of Compilers and Translators

    History of C

    Program Development Cycle

    Compiling C Programs

    Running C Programs

    Version-1.2

  • What is a Programming?The art of writing instructions for a computer to solve a specific task is known as programming.

    The output of programming is a well-defined set of instructions. This is called a program.

    Software is a program or collection of programs.

    Software can be developed by computer languages.

    Version-1.2

  • Classification of Computer LanguagesProgramming LanguagesLow Level LanguagesHigh Level LanguagesMachine LanguageAssembly LanguageModularObject Oriented

    Version-1.2

  • Classification of LLLsMachine LanguageProgramming is done at machine levelComputer consists of 2 words 0 and 1.Machine dependent Can be directly typed and executedNo Translator program is required Difficult to remember,understand, modify and debug errors.Assembly LanguageUses Symbolic instructionsUses symbolic words in this language are referred to as mnemonicsE.g. ADD for Addition SUB for Subtraction ST Z to store the resultInstructions are English like, the computer does not understand the instructions So the translators are required to convert these instructions to machine language.

    Version-1.2

  • High Level LanguagesHLLs are English like. Elements of these languages are alphabets,digits,punctuations and other special symbols.Instructions are machine dependent.The programmer can easily understands the program but the computer does not.Translators are required to translate this program into computer readable form .The Compiler and Interpreter are 2 translator programs that are used to translate the HLL into machine language.

    Source ProgramTranslatorCompiler InterpreterMachine Code

    Version-1.2

  • Advantages of High-level languages over low-level ones:Readability: A good high-level language will allow programs to be written in English description of the underlying algorithms. If care is taken, the coding may be done in a way that is essentially self-documenting, a highly desirable property

    Portability: High-level languages, being essentially machine independent, hold out the promise of being used to develop portable software.

    Structure and object orientation: There is general agreement that the structured programming movement of the 1960s and the object-oriented movement of the 1990s have resulted in great improvement in the quality and reliability of code.

    Version-1.2

  • Generality: Most high-level languages allow the writing of a wide variety of programs, thus relieving the programmer of the need to become expert in many diverse languages.

    Brevity: Programs expressed in high-level languages are often considerably shorter (in terms of their number of source lines) than their low-level equivalents.

    Error checking: Being human, a programmer is likely to make many mistakes in the development of a computer program. Many high-level languages - or at least their implementations - can, and often do, enforce a great deal of error checking both at compile-time and at run-time.

    Version-1.2

  • Difference between Compiler and InterpreterCompilersIt takes entire HLL program as input and translate in into M/C Language

    All errors that occur in the program are listed and displayed.Debugging is faster.Requires more memoryCostlier InterpreterIt takes one statement of a high level language program as input and translates it into M/C language and executes it.Errors that occur only in the statement being taken for translation are displayedDebugging is slowerRequires less memoryCheaper

    Version-1.2

  • Classification of HLLsGeneral Purpose HLL are used in almost all fields such as teaching,training,business,art,science etc.Eg. BASIC(Beginers All purpose Symbolic Instruction Code),Pascal,C.

    2. Specific purpose HLLare restricted to a particular field.Eg. COBOL,FORTRAN,C++,PROLOG,JAVA,C#

    Version-1.2

  • COMPILERS

    Translates-Source language to Target language.

    Version-1.2

  • Basics of a Typical C Environment

    Phases of C Programs:EditPreprocessCompileLinkLoadExecute

    Version-1.2

  • Phases of compiler:

    Version-1.2

  • Lexical analysesThe first phase, called the lexical analyzer, or scanner,which separates characters of the source language in to groups that logically belong together; these groups are called tokens.

    The usual tokens are keywords, such as if, while, break, identifiers, such as X or NUM, operator symbols such as < = or +, and punctuation symbols such as parentheses or commas.

    The output of the lexical analyzer is a stream of tokens, which is passed to the next phase, the syntax analyzer, or parser.

    Version-1.2

  • The syntax analyzer groups tokens together in to syntactic structures.

    For examples, the three tokens representing A+B might grouped into a syntactic structure called an expression. Expressions might further be combined to form statements.

    The intermediate code generator uses the structure produced by the syntax analyzer to create a stream of simple instructions.

    Many styles of intermediate code are possible. One common style uses instructions with one operator and a small number of operands.

    The primary difference between intermediate code and assembly code is that the intermediate code need not specify the registers to be used for each operation.

    Version-1.2

  • Code optimization is an optional phase designed to improve the intermediate code so that the ultimate object program runs faster and or takes less space.

    The final phase, code generation, produces the object code by deciding on the memory locations for data, selecting code to access each datum, and selecting the registers in which each computation is to be done.

    That table management or book keeping, portion of the compiler keeps the track of the names used by the program and records the essential information about each, such as its type (integer, float, etc). That data structure used to record this information is called symbol table.

    The error handler is invoked when a flaw in the source program is deducted. It must warn the programmer by issuing a diagnostic, and adjust the information being passed from phase to phase, so that each phase can proceed. Both table management and error handling routines interact with all phases of the compiler.

    Version-1.2

  • Cs memory map

    Version-1.2

  • Text segment : Includes the executable code.

    Stack segment: contains the program stack , which includes the return address, parameters and local variables of the functions being executed.

    Heap Segment: contains memory allocated dynamically.

    Initialized data segments: contains the initialized data i.e, the static variables and the global variables whose initial values are stored in the executable file.

    Uninitialized data segments: contains the uninitialized data i.e, all global variables whose initial values are not stored in the executable file.

    Version-1.2

  • LibrariesEach high level source code file is transformed through several steps in to an object file, which contains the machine code of the assembly language instructions corresponding to the high level instructions.

    An object file can not be executed, since it doenot contain the linear address that corresponds to each reference such as functions in libraries or other source code files of the same program.

    The assigning, or resolution, of such address is performed by the linker, which collects all the object files of the program and constructs the executable file.

    The linker also analyses the librarys functions used by the program and use them in to the executable file.

    Version-1.2

  • All executable files in traditional UNIX systems were based on static libraries.

    This means that executable file produced by the linker includes not only the code of the original program but also the code of the library functions.

    Modern UNIX system use shared libraries. The executable file doenot contain the library object code, but only a reference to the library name.

    When the program is loaded in memory for execution, a program called program interpreter (ld.so) takes care of analyzing the library names in the executable file, by locating the library in the systems directory tree. A process can also load additional shared libraries at run time by using the dlopen ( ) library function.

    This is done by memory mapping.

    Version-1.2

  • Dynamic Linking and Loading Dynamic linking defers much of the linking process until a program starts running. It provides a variety of benefits that are hard to get otherwise: Dynamically linked shared libraries are easier to create than static linked shared libraries.

    Dynamically linked shared libraries are easier to update than static linked shared libraries.

    The semantics of dynamically linked shared libraries can be much closer to those of unshared libraries.

    Dynamic linking permits a program to load and unload routines at runtime, a facility that can otherwise be very difficult to provide.

    Version-1.2

  • Dynamic Linking and LoadingThere are a few disadvantages, of course.

    The runtime performance costs of dynamic linking are substantial compared to those of static linking, since a large part of the linking process has to be redone every time a program runs.

    Every dynamically linked symbol used in a program has to be looked up in a symbol table and resolved.

    Dynamic libraries are also larger than static libraries, since the dynamic ones have to include symbol tables.

    Version-1.2

  • ELF dynamic linkingSun Microsystems' SunOS introduced dynamic shared libraries to UNIX in the late 1980s.

    ELF was clearly an improvement over the previous object formats, and by the late 1990s it had become the standard for UNIX and UNIX like systems including Linux and BSD derivatives.

    Version-1.2

  • Version-1.2

  • The Genesis of CMultics (Multiplexed Information and Computing Service) is a mainframe timesharing operating system begun in 1965.

    Multics started out as a joint venture between MIT, General Electric, and Bell Labs. It was a research project, and was an important influence on operating system development.

    By 1969, Bell Labs management, and even the researchers came to believe that the promise of Multics could be fulfilled only too late, and too expensively.

    Version-1.2

  • The Genesis of CEven before the GE-645 Multics machine was removed from the premises of Bell Labs, an informal group, led by Ken Thompson, had begun investigating alternatives.

    In 1969, Ken Thompson and Dennis Ritchie designed a file system for the Bell Labs in order to provide a more convenient environment for programming.

    This file system evolved into an early version of the UNIX Operating System.

    Version-1.2

  • The Genesis of CThis file system was implemented on a PDP-7 computer, and in 1971, on a PDP-11 computer.

    Not long after Unix first ran on the PDP-7 in 1969, Doug McIlroy created the systems first high-level language, an implementation of McClures TMG (TransMoGrifiers).

    TMG is a language for writing compilers in a top-down, recursive-descent style that combines context-free syntax notation with procedural elements.

    Version-1.2

  • The Genesis of CChallenged by McIlroys feat in reproducing TMG, Thompson decided that Unix possibly it had not even been named yet needed a systems programming language.

    In a rapidly scuttled attempt at Fortran, he created, instead, a language of his own, which he called B.

    Language B was in turn influenced by BCPL (Basic Control Programming Language) of Martin Richards. Its name most probably represents a contraction of BCPL.

    Version-1.2

  • The Genesis of CIn 1971, Dennis Ritchie made extensions to language B, and also rewrote its compiler to generate PDP-11 machine instructions instead of threaded code.

    Thus, the transition from B to C was contemporaneous with the creation of a compiler capable of producing programs fast and small enough to compete with assembly language.

    By early 1973, the essentials of modern C were complete.

    Version-1.2

  • The Genesis of CThe language and compiler were strong enough to permit the rewriting of the Unix kernel for the PDP-11 in C during the summer of 1973.

    Also, during this period, the compiler was retargeted to other nearby machines, particularly the Honeywell 635, and IBM 360/370.

    Because the language could not live in isolation, the prototypes for the modern libraries of the C language were developed.

    Version-1.2

  • Why Use C?C is a powerful and flexible language. C is used for projects as diverse as operating systems, word processors, graphics, spreadsheets, and even compilers for other languages.

    C is a portable language. Portable means that a C program written for one computer system (an IBM PC) can be compiled and run on another system(a DEC VAX system) with little or no modification. Portability is enhanced by ANSI standard for C, the set of rules for C compilers.

    C is modular. C code can(and should) be written in routines called functions. These functions can be reused in other applications or programs. By passing pieces of information to the functions, one can create useful, reusable code.

    First Program

    Version-1.2

  • C Program StructureDocumentation SectionLink SectionDefinition SectionGlobal Declaration Sectionmain() Function Section

    {Declaration PartExecutable Part}Sub Program Section

    Function 1Function 2-(User defined Functions)-Function n

    Version-1.2

  • Variables , constants Operators in C

    Version-1.2

  • ObjectivesConstant and Variable Types Variables Variable Names Constants Expressions and Operators Assignment Statement Arithmetic operators Relational Operators Logical Connectors

    Version-1.2

  • C Tokens

    Version-1.2

  • C TokensKeywordsOperatorsIdentifiersSpecial SymbolsConstantsStrings

    Version-1.2

  • Key Words defined by 89 standred

    Version-1.2

  • Key Words defined by 99 standard

    Version-1.2

  • Cs memory map

    Version-1.2

  • Variables (identifiers)A variable is a named data storage location in the computer's memory. Variable Names The name can contain letters, digits, and the underscore character (_).

    The first character of the name must be a letter. The underscore is also a legal first character, but its use is not recommended.

    Case matters (that is, upper- and lowercase letters). Thus, the names count and count refer to two different variables.

    C keywords can't be used as variable names. A keyword is a word that is part of the C language.

    For many compilers, a C variable name can be up to 31 characters long. (It can actually be longer than that, but the compiler looks at only the first 31 characters of the name.)

    Version-1.2

  • Many naming conventions are used for variable names created from multiple words.

    One style: interest_rate. Using an underscore to separate words in a variable name makes it easy to interpret.

    The second style is called camel notation. Instead of using spaces, the first letter of each word is capitalized. Instead of interest_rate, the variable would be named InterestRate

    Numeric Variable Types C's numeric variables fall into the following two main categories:Integer variables hold values that have no fractional part (that is, whole numbers only). (signed and unsigned values)

    Floating-point variables hold values that have a fractional part (that is, real numbers).

    Version-1.2

  • C's numeric data types.

    Version-1.2

    Sheet1

    Variable TypeKeywordBytes RequiredRange

    Characterchar1-128 to 127

    Integerint2 or 4-32768 to 32767

    or

    2,147,483,648 to 2,147,438,647

    Short integershort2-32768 to 32767

    Long integerlong4-2,147,483,648 to 2,147,438,647

    Unsigned characterunsigned char10 to 255

    Unsigned integerunsigned int20 to 65535

    Unsigned short integerunsigned short20 to 65535

    Unsigned long integerunsigned long40 to 4,294,967,295

    Single-precisionfloat41.2E-38 to

    floating-point3.4E381

    Double-precisiondouble82.2E-308 to

    floating-point1.8E3082

    1Approximate range; precision = 7 digits.

    2Approximate range; precision = 19 digits.

    Sheet2

    Sheet3

  • Data type sizes# include Main(){printf(size of integer is %d\n,sizeof(int));printf(size of float is %d\n,sizeof(float));printf(size of char is %d\n,sizeof(char));printf(size of long is %d\n,sizeof(long));printf(size of short is %d\n,sizeof(short));printf(size of double is %d\n,sizeof(double));printf(size of integer is %d\n,sizeof(long double));}

    Version-1.2

  • Variable DeclarationsBefore using a variable in a C program, it must be declared

    A variable declaration has the following form:

    typename varname; //typename specifies the type of variable// varname is the variable name

    e.g.. int count, number, start; /* three integer variables */ float percent, total; /* two float variables */

    Version-1.2

  • The typedef Keyword The typedef keyword is used to create a new name for an existing data type

    typedef int integer; //Creates integer as a synonym for int integer count; that typedef doesn't create a new data type; it only lets the usage of a different name for a predefined data type

    Version-1.2

  • Initializing Numeric Variables If the value of the variableisnt defined. It might be zero, or it might be some random garbage value. Before using a variable, always initialize it to a known value.

    int count; /* Set aside storage space for count */count = 0; /* Store 0 in count */

    Be careful not to initialize a variable with a value outside the allowed range. Here are two examples of out-of-range initializations:int weight = 10000000000;unsigned char value = 2500;

    The C compiler doesnt catch such errors. The program might compile and link, but unexpected results might be obtained when the program is made to run.

    Version-1.2

  • Constants A constant is a data storage location used by the program. Unlike a variable, the value stored in a constant can't be changed during program execution

    C has two types of constants 1. Literal Constants A literal constant is a value that is typed directly into the source code wherever it is needed. count = 20; tax_rate = 0.28; Decimal constants can contain the digits 0 through 9 and a leading minus or plus sign. Octal constants can contain the digits 0 through 7 and a leading minus or plus sign. Hexadecimal constants can contain the digits 0 through 9, the letters A through F, and a leading minus or plus sign

    Version-1.2

  • Constants2.Symbolic ConstantsA symbolic constant is a constant that is represented by a name (symbol) in the program. Like a literal constant, a symbolic constant can't change. C has two methods for defining a symbolic constant: the #define directive and the const keyword. #define CONSTNAME literal This creates a constant named CONSTNAME with the value of literal. literal represents a literal constant e.g.. #define PI 3.14159 /* a constant for PI is defined. */Defining Constants with the const Keyword const int count = 100;const float pi = 3.14159;const long debt = 12000000;

    Version-1.2

  • Statements, Expressions, and Operators StatementsA statement is a complete direction instructing the computer to carry out some task.e.g. x = 2 + 3; The term white space refers to spaces, tabs, and blank lines in the source code. is equivalent to this statement:x = 2 + 3;It is also equivalent to this:x =2+3;

    Version-1.2

  • Statements, Expressions, and Operatorsprintf("Hello,\world!");Null StatementsIf a semicolon is placed by itself on a line,a null statement is created. A statement that doesn't perform any action.This is perfectly legal in C. Compound StatementsA compound statement, also called a block, is a group of two or more C statements enclosed in braces. { printf("Hello, "); printf("world!");}

    Version-1.2

  • Statements, Expressions, and OperatorsSimple Expressions The simplest C expression consists of a single item: a simple variable, literal constant, or symbolic constant. E.g. PI,12.5,rate,-1.25

    Complex Expressions Complex expressions consist of simpler expressions connected by operators. E.g. 1.25 / 8 + 5 * rate + rate * rate / cost

    Operators

    Version-1.2

  • Statements, Expressions, and OperatorsOperators An operator is a symbol that instructs C to perform some operation, or action, on one or more operands. An operand is something that an operator acts on. In C, all operands are expressions. The Assignment Operator The assignment operator is the equal sign (=). x=y; it means, "assign the value of y to x. Mathematical Operators 1. Unary Mathematical Operators 2. Binary Mathematical Operators

    Version-1.2

  • Statements, Expressions, and Operators

    1. Unary Mathematical Operators

    Version-1.2

  • main(){ int m, i =5; m = i++ + ++i; printf("Ist %d\n",m);//5 + 5 = 10 i = 5; m = i++ + i++; printf("Ist %d\n",m);//6 + 6 = 12 i = 5; m = i++ + ++i + i++; printf("Ist %d\n",m);//6 + 6 + 6 = 18 i = 5; m = i++ + ++i + ++i;//6 + 6 + 7 = 19 printf("Ist %d\n",m); getchar();}

    Version-1.2

  • Binary Mathematical Operators .

    Version-1.2

  • Order of Subexpression Evaluation .DO use parentheses to make the order of expression evaluation clear.DON'T overload an expression. It is often more clear to break an expression into two or more statements. This is especially true when using the unary operators (--) or (++).

    Version-1.2

  • A Program to find area of Trianglemain(){float base,height,area;printf("Enter the base and height of the triangle\n");scanf("%f %f",&base,&height);area = 1 / 2.0 * base * height;printf("The area of the triangle is %f\n",area);}Go Back

    Version-1.2

  • Swap numbers without temporary variablemain(){int num1,num2;printf("Enter any 2 numbers :");scanf("%d %d",&num1,&num2);printf("numbers before swaping\n ");printf("num1 = %d \t num2 = %d\n",num1,num2);num1 = num1 + num2;num2 = num1 - num2;num1 = num1 - num2;printf("numbers after swaping \n");printf("num1 = %d \t num2 = %d\n",num1,num2);}

    Version-1.2

  • Relational Operators .

    Version-1.2

  • Logical Operators C's logical operators let to combine two or more relational expressions into a single expression that evaluates to either true or false.

    Version-1.2

  • Compound Assignment Operators C's compound assignment operators provide a shorthand method for combining a binary mathematical operation with an assignment operation

    e.g.. x = x + 5;using shorthand operator we can write x +=5;

    Version-1.2

  • The Conditional Operator The conditional operator is C's only ternary operator, meaning that it takes three operands. Its syntax is exp1 ? exp2 : exp3; If exp1 evaluates to true (that is, nonzero), the entire expression evaluates to the value of exp2. If exp1 evaluates to false (that is, zero), the entire expression evaluates as the value of exp3. 1. assigns the value 1 to x if y is true and assigns 100 to x if y is false e.g. x = y ? 1 : 100; 2. to make z equal to the larger of x and y, one could writez = (x > y) ? x : y;

    Version-1.2

  • Max 3 using ternary operatormain(){int num1,num2,num3,max;printf("Enter any 3 numbers :");scanf("%d %d %d",&num1,&num2,&num3); max=((num1>num2)&(num1>num3)?num1:(num2>num3)?num2:num3);printf("The greatest of three numbers is %d\n",max);}

    Version-1.2

  • The Comma Operator The comma is frequently used in C as a simple punctuation mark, serving to separate variable declarations, function arguments, and so on

    Separating two sub expressions with a comma can form an expression. The result is as follows:Both expressions are evaluated, with the left expression being evaluated first.e.g. i=(j=3 , j+2);

    here first value 3 is assigned to j and then the expression j+2 is evaluated giving 5

    Version-1.2

  • Precedence and Order of Evaluation

    Version-1.2

  • The if Statement Statements in a C program normally execute from top to bottom, in the same order as they appear in source code file. A program control statement modifies the order of statement execution. In its basic form, the if statement evaluates an expression and directs program execution depending on the result of that evaluation.

    The form of an if statement is as follows: if (expression) statement;

    If expression evaluates to true, statement is executed. If expression evaluates to false, statement is not executed.

    Version-1.2

  • The if Statementa block is a group of two or more statements enclosed in braces. if (expression){ statement1; statement2; /* additional code goes here */ statementn;}

    An if statement can optionally include an else clause. The else clause is included as follows:if (expression) statement1;else statement2;If expression evaluates to true, statement1 is executed. If expression evaluates to false, statement2 is executed

    Version-1.2

  • If statements in different formatThe if StatementForm 1Form 2if( expression )if(expression) statement1;statement1;next_statement;else{statement2;next statement; }Form 3if( expression1 ) statement1;else if( expression2 ) statement2;else statement3;next_statement; E.g. Programs

    Version-1.2

  • A program to find max of 2 numbersmain(){int num1,num2;printf("\n Enter any two numbers");scanf("%d %d",&num1,&num2);if(num1 > num2)printf("%d is greater than %d\n",num1,num2);elseprintf("%d is greater than %d\n",num2,num1);}

    Version-1.2

  • Find Max of 3 numbers main(){int num1,num2,num3,max;printf("Enter any 3 numbers :");scanf("%d%d%d",&num1,&num2,&num3);if(num1>num2)if(num1>num3)max = num1;elsemax = num3;else if(num2> num3)max = num2;elsemax = num3;printf("The greatest of three numbers is %d\n",max);}

    Version-1.2

  • The switch Statement C's most flexible program control statement is the switch statement, which lets the program to execute different statements based on an expression that can have more than two values.

    switch (expression){ case template_1: statement(s); case template_2: statement(s); ----- case template_n: statement(s); default: statement(s);}The switch statement allows for multiple branches from a single expression. It's more efficient and easier to follow than a multileveled if statement. E.g.Program

    Version-1.2

  • Exiting the Program A C program normally terminates when execution reaches the closing brace of the main() function. However, a program can be terminated at any time by calling the library function exit().

    The exit() Function The exit() function terminates program execution and returns control to the operating system. This function takes a single type int argument that is passed back to the operating system to indicate the program's success or failure. The syntax of the exit() function isexit(status);If status has a value of 0, it indicates that the program terminated normally. A value of 1 indicates that the program terminated with some sort of error. The return value is usually ignored. To use the exit() function, a program must include the header file stdlib.h.

    Version-1.2

  • Program to find roots of quadratic equation #include# include #includemain(){float a,b,c,dino,disc,x1,x2,xr,xi,x;

    printf(\n ENTER THE value FOR THE 1 NUMBERS:");scanf("%f",&a);printf(\n ENTER THE value FOR THE 2 NUMBERS:");scanf("%f",&b);printf("ENTER THE value FOR THE 3 NUMBERS:");scanf("%f",&c);disc=b*b-4*a*c;

    Version-1.2

  • Program to find roots of quadratic equationif (disc>0){printf("THE ROOTS ARE REAL AND DISTINCT:-\n");dino=2*a;x1=(-b+sqrt(disc))/dino;x2=(-b-sqrt(disc))/dino;printf("\n");printf("THE FIRST ROOT: %f\n",x1);printf("\n");printf("THE SECOND ROOT: %f\n",x2);}

    Version-1.2

  • Program to find roots of quadratic equationelse if(disc
  • Program to find roots of quadratic equationelse{printf("THE ROOTS ARE COMPLEX:-\n");x=-b/(2*a);printf("\n");printf("ROOTS ARE: %f%f\n",x,x);}

    }

    Version-1.2

  • Company C Aptitude Questions1) What is the output of the following question (Wipro)

    main(){ int result=0 ,temp, n=7623; while(n){ temp=n%10; result =result * 10+ temp; n=n/10; } printf("%d\n",result);}

    Version-1.2

  • 2) What is the output of the following question (Wipro)

    If A>B then F=F(G); else B>C then G=G(F);

    in this , for 75% times A>B and 25% times B>C there are 10000 instructions ,then the ratio of F to G[a] 7500:2500 [b] 7500:625 [c] 7500:625

    Ans :[a]

    Version-1.2

  • 3)What is the output ? (IBM)int i=10;printf("%d%d%d",i,i++,++i);ans: compiler dependent

    4) What is the output ? (IBM)

    printf("Enter two values a and b:"):scanf("%d%d",a,b);printf("%d+%d=%d",a,b,a+b);ans:core dumped

    Version-1.2

  • 5) What is the output ? (IBM)main(){ int I; for(i=0;i
  • 6) A>B, B>C, C=D, D>E, then which is greatest (Wipro)?

    7) The C language terminator is (Tcs) (a) semicolon (b) colon (c) period (d) exclamation mark

    8) What is false about the following -- A compound statement is (TCS) (a) A set of simple statements (b) Demarcated on either side by curly brackets (c) Can be used in place of simple statement (d)* A C function is not a compound statement.

    Version-1.2

  • 9. Main must be executed as (TCS) (a)* The first function in the program (b) Second function in the program (c) Last function in the program (d) Any where in the program

    10. Which of the following about automatic variables within a function is not correct ? (a) Its type must be declared before using the variable (b) They are local (c) They are not initialised to zero (d)* They are global

    Version-1.2

  • 11. Which of the following about the C comments is incorrect ? (a) C comments can go over multiple lines (b) Comments can start any where in the line (c) A line can contain comments with out any language statements (d) Comments can occur within comments

    12. What is the value of y in the following code? x=7; y=0; if (x=6) y=7; else y=1; (a) 7 (b) 0 (c) 1 (d) 6

    Version-1.2

  • 13) What is y value of the code if input x=10 (TCS) y=5; if (x==10) ; else if(x==9) ; else y=8; (a)9 (b)8 (c)*5 (d)7

    14) The operator for exponential is (a) ** (b) ^ (c) % (d) not available

    Version-1.2

  • 15) cond 1?cond 2?cond 3?:exp 1:exp 2:exp 3:exp 4; is equivalent to which of the following? (a)if (cond 1) exp 1; else if (cond 2) exp 2; else if (cond 3) exp 3; else exp 4;

    (b) if (cond 1) if cond 2 if cond 3 exp 1; else exp 2; else exp 3; else exp 4; (c) if cond 1 && cond 2 && cond 3 exp 1 |exp 2|exp 3|exp 4; (d) if cond 3 exp 1; else if cond 2 exp 2; else if cond 3 exp 3; else exp 4;

    Version-1.2

  • Objectives The loop The do while loopThe for loopThe break Statement The continue Statement The goto StatementEnding Loops Early The switch Statement Exiting the Program The exit() Function

    Version-1.2

  • LoopsA C programming construct that executes a block of one or more statements a certain number of times.

    It is sometimes called the for loop because program execution typically loops through the statement more than once.

    There are 3 loops in C programming

    1.For loop2.while loop3.Do while loop

    Version-1.2

  • The for loopThe for statement is a C programming construct that executes a block of one or more statements a certain number of times.

    for ( initial; condition; increment ) statement; 1. The expression initial is evaluated. initial is usually an assignment statement that sets a variable to a particular value. 2. The expression condition is evaluated. condition is typically a relational expression. 3. If condition evaluates to false (that is, as zero), the for statement terminates, and execution passes to the first statement following statement. 4. If condition evaluates to true (that is, as nonzero), the C statement(s) in statement are executed. 5. The expression increment is evaluated, and execution returns to step 2.

    E.g. Program (Multiplication Table )

    Version-1.2

  • To generate multiplication tablemain(){int num,counter;printf("Enter any number :");scanf("%d",&num);for(counter=1;counter
  • program to generate even and odd number main(){int counter;printf("printing even numbers in 0 to 100\n\n");for(counter=0;counter
  • A program to print fibonacci seriesmain(){int firstnum=0,secondnum=1,resultnum=1,counter,num;printf("Enter any number :");scanf("%d",&num);for(counter=0;counter
  • Factorial of the number#includemain(){int num,fact=1,i;

    printf("ENTER any number:");scanf("%d",&num);

    for (i=num; i>0; i--)fact=fact*i;

    printf("THE factorial of %d IS : %d",num,fact);}

    Version-1.2

  • Prime numbers between 1 to 100#include #include main(){int m,n,i,j,flag=1;printf("enter 2 numbers\n");scanf("%d%d",&m,&n);for(i=m;i
  • Prime numbers between 1 to 100for(j=2;j
  • The while loop The while statement, also called the while loop, executes a block of statements as long as a specified condition is true.

    Syntax: while (condition) statement 1. The expression condition is evaluated. 2. If condition evaluates to false (that is, zero), the while statement terminates, and execution passes to the first statement following statement. 3. If condition evaluates to true (that is, nonzero), the C statement(s) in statement are executed. 4. Execution returns to step 1

    Version-1.2

  • A program to find number of vowelsmain(){char ch;int counter=0;printf("\n Enter any String ");while((ch=getchar()) !='\n') {switch(ch){case 'a': case 'A':case 'e': case 'E':case 'i': case 'I':case 'o': case 'O':case 'u': case 'U':counter++; break;} }printf("number of vowels %d",counter);}

    Version-1.2

  • The do...while Loop the do...while loop, which executes a block of statements as long as a specified condition is true. The do...while loop tests the condition at the end of the loop rather than at the beginning, as is done by the for loop and the while loop.

    do statements while(condition);

    1. The statements in statement are executed.

    2. condition is evaluated. If it's true, execution returns to step 1. If it's false, the loop terminates.

    The statements associated with a do...while loop are always executed at least once. This is because the test condition is evaluated at the end, instead of the beginning, of the loop.

    Version-1.2

  • A program to reverse a number#includemain(){int num,rev,r;char rep='y';do{system("clear");printf(\n ENTER ANY number:");scanf("%d",&num);printf("THE reverse OF THE NUMBER i.e '%d' IS: ",num);rev=0;

    Version-1.2

  • A program to reverse a numberwhile(num!=0){r=(num % 10);num=(num / 10);rev=rev*10+r;}printf("%d\n",rev);printf("Do you wish to continue [y/n] or [Y/N]:")_fpurge(stdin);scanf("%c",&rep);}while(rep=='y' || rep=='Y');printf("Press any key return back to the program...........");}

    Version-1.2

  • Nested Loops The term nested loop refers to a loop that is contained within another loop.. C places no limitations on the nesting of loops, except that each inner loop must be enclosed completely in the outer loop; overlapping loops are not allowed.

    Good indenting style makes code with nested loops easier to read. Each level of loop should be indented one step further than the last level. This clearly labels the code associated with each loop.

    Version-1.2

  • Ending loops earlyIn all three loops, termination or exit of the loop occurs only when a certain condition occurs. To exert more control over loop execution. The break and continue statements provide this control.

    The break Statement

    break is used inside a loop or switch statement. It causes the control of a program to skip past the end of the current loop (for, while, or do...while) or switch statement. No further iterations of the loop execute; The following is an example:for (count = 0; count < 10; count++) if ( count == 5 ) break;

    Version-1.2

  • The continue Statement Like the break statement, the continue statement can be placed only in the body of a for loop, a while loop, or a do...while loop. When a continue statement executes, the next iteration of the enclosing loop begins immediately. The statements between the continue statement and the end of the loop aren't executed.

    E.g.int x;

    printf("Printing only the even numbers from 1 to 10\n"); for( x = 1; x

  • The goto Statement The goto statement is one of C's unconditional jump, or branching, statements. When program execution reaches a goto statement, execution immediately jumps, or branches, to the location specified by the goto statement.

    This statement is unconditional because execution always branches when a goto statement is encountered; the branch doesn't depend on any program conditions (unlike if statements, for example).

    A goto statement and its target must be in the same function, but they can be in different blocks. syntax goto location;

    location is a label statement that identifies the program location where execution is to branch. A label statement consists of an identifier followed by a colon and a C statement:

    location: a C statement;

    Version-1.2

  • Infinite Loops (ODD Loops)

    An infinite loop is one that, if left to its own devices, would run forever. It can be a for loop, a while loop, or a do...while loop. For example, while (1){ /* additional code goes here */} An infinite loop is created. The condition that the while tests is the constant 1, which is always true and can't be changed by the program.

    The break statement is used to exit a loop. Without the break statement, an infinite loop would be useless.

    An infinite for loop or an infinite do...while loop, can also be done as follows:for (;;) { /* additional code goes here */}do { /* additional code goes here */} while (1);

    Version-1.2

  • Input and Output

    Version-1.2

  • ObjectivesInput and Output The Standard Input Output File Character Input / Output getchar putchar Formatted Input / Output printf scanf Whole Lines of Input and Output gets puts

    Version-1.2

  • Fundamentals of Input and OutputTo display some information on the screen or to get some data from the keyboard we need input and output functions Classification of Input /Output functionsprintf() , scanf()Formatted I/OCharacter I/Ogetchar(), putchar()String I/Ogets(),puts()Unformatted I/OI/O

    Version-1.2

  • Formatted I/OThe printf() Function The printf() function, part of the standard C library, is perhaps the most versatile way for a program to display data on-screen.

    The printf() Format Strings A printf() format string specifies how the output is formatted.

    Literal text is displayed exactly as entered in the format string.

    Version-1.2

  • Formatted I/OAn escape sequence provides special formatting control. An escape sequence consists of a backslash (\) followed by a single character

    A conversion specifier consists of the percent sign (%) followed by a single character. In the example, the conversion specifier is %d. The %d tells printf() to interpret the variable x as a signed decimal integer.

    When using printf(),need to include the standard input/output header file, stdio.h

    Version-1.2

  • Unformatted Character I/OThe character input functions read input from a stream one character at a time.

    The getchar() FunctionThe function getchar() obtains the character from the stream stdin. It provides buffered character input with echo, and its prototype is

    int getchar(void);

    The putchar() function

    The C library's character output functions send a single character to a stream. The function putchar() sends its output to stdout (normally the screen).

    The prototype for putchar(), which is located in STDIO.H, is as follows

    int putchar(int c);

    Version-1.2

  • Whole Lines of Input and Output Inputting Strings Using the gets() Function

    The gets() function gets a string from the keyboard. When gets() is called, it reads all characters typed at the keyboard up to the first newline character (which is generated by pressing Enter). This function discards the newline, adds a null character, and gives the string to the calling program.

    If there is a problem getting the string, gets() returns null.

    Displaying Strings Using the puts() Function

    The programs display strings on-screen more often than they display single characters. The library function puts() displays strings.

    Version-1.2

  • Displaying Messages with puts() The puts() function can also be used to display text messages on-screen, but it can't display numeric variables. puts() takes a single string as its argument and displays it, automatically adding a new line at the end

    Any program that uses puts() should include the header file stdio.h. Note that stdio.h should be included only once in a program.

    Version-1.2

  • Formatted Input / Output To input / output mixed data types we need format specifiers

    Conversion SpecifiersThe format string must contain one conversion specifier for each printed variable.

    Version-1.2

  • Formatted Input/OutputThe format string must contain one conversion specifier for each printed variable.

    printf(%d + %d = %d ,a,b,a+b);

    scanf() uses a format string to describe the format of the input. The format string utilizes the same conversion specifiers as the printf() function.

    scanf() is a function that uses a conversion specifier in a given format-string to place values into variable arguments. The arguments should be the addresses of the variables rather than the actual variables themselves.

    For numeric variables, it is possible to pass the address by putting the address-of operator (&) at the beginning of the variable name. When using scanf(),include the stdio.h header file.

    Version-1.2

  • Functions

    Version-1.2

  • ObjectiveWhat a function is and what its parts areAbout the advantages of structured programming with functionsHow to create a functionHow to declare local variables in a functionHow to return a value from a function to the programHow to pass arguments to a functionRecursive functions

    Version-1.2

  • Functions: The Basics Functions are those, which break large computing tasks into smaller ones .A function is a self-contained block of statements that perform a coherent task of some kind.

    A function is defined as a name given to an independent section of C code that performs a specific task

    Each function has a unique name. By using that name in another part of the program, it is possible to execute the statements contained in the function. This is known as calling the function. A function can be called from within another function.

    A function can return a value to the calling program. When program calls a function, the statements it contains are executed. If necessary, these statements can pass information back to the calling program.

    Version-1.2

  • How a Function Works Any C program contains at least one function it must be main(). There is no limit on the number of functions in a C program. Always execution begins with main().

    A function will not be executed until the function is called by another part of the program. When a function is called, the program can send the function information in the form of one or more arguments.

    An argument is a mechanism used to convey information to the function . The statements in the function then execute, performing whatever task each was designed to do

    When the function's statements have finished, execution passes back to the same location in the program that called the function. Functions can send information back to the program in the form of a return value. The arguments are sometimes called as parameter.

    Version-1.2

  • Function definitionFunction Prototype

    return_type function_name( arg-type name-1,...,arg-type name-n);

    A function prototype provides the compiler with a description of a function that will be defined at a later point in the program.

    Function Definition

    return_type function_name( arg-type name-1,...,arg-type name-n){ /* statements; */}

    A function definition is the actual function. The definition contains the code that will be executed.

    Version-1.2

  • Writing a Function The first step in writing a function is that to know what the function has to do.

    The Function Header

    The first line of every function is the function header, which has three components, each serving a specific function.

    1. The Function Return Type The function return type specifies the data type that the function returns to the calling program. The return type can be any of C's data types: char, int, long, float, or double. It is also defined that function doesn't return a value by using a return type of void. 2. The Function Name Naming a function is fully depend on the user, but it should follow the rules for C variable names. A function name must be unique

    3. The Parameter List Many functions use arguments, which are values passed to the function when it's called.

    Version-1.2

  • Arguments / ParametersA parameter is an entry

    in a function header; it serves as a "placeholderfor an argument.

    A function's parameters arefixed; they do not change during program execution.

    The Function Body The function body is enclosed in braces, and it immediately follows the function header. It's here that the real work is done.

    An argument is an actual value passed to the function by the calling program.

    Each time a function is called, it can be passed different arguments. In C, a function must be passed the same number and type of arguments each time it's called, but the argument values can be different.

    Version-1.2

  • Variables declaration in functionIt is possible to declare variables within the body of a function. Variables declared in a function are called local variables. The term local means that the variables are private to that particular function and are distinct from other variables of the same name declared elsewhere in the program.

    Function Statements

    There is essentially no limitation on the statements that can be included within a function. The only thing should not be done inside a function is define another function. It is possible to use all other C statements, including loops, if statements, and assignment statements. Can call library functions and other user-defined functions.

    Version-1.2

  • Function headerFunction length

    C places no length restriction on functions, but as a matter of practicality, it is advisable to keep functions relatively short.

    Returning a Value

    To return a value from a function, return keyword is used, followed by a C expression.

    When execution reaches a return statement, the expression is evaluated, and execution passes the value back to the calling program.

    Version-1.2

  • Function PrototypeThe prototype for a function is identical to the function header, with a semicolon added at the end. Like the function header, the function prototype includes information about the function's return type, name, and parameters.

    The prototype's job is to tell the compiler about the function's return type, name, and parameters. With this information, the compiler can check every time the source code calls the function and verify that it is passing the correct number and type of arguments to the function and using the return value correctly. If there's a mismatch, the compiler generates an error message.

    They should be placed before the start of main() or before the first function is defined.

    Version-1.2

  • Passing Arguments to a Function To pass arguments to a function, listing them in parentheses following the function name is a must. The number of arguments and the type of each argument should match the parameters in the function header and prototype.

    For example, if a function is defined to take two type int arguments, It is mandatory to pass exactly two int arguments--no more, no less--and no other type.

    If the function takes multiple arguments, the arguments listed in the function call are assigned to the function parameters in order: the first argument to the first parameter, the second argument to the second parameter, and so on.

    Each argument can be any valid C expression: a constant, a variable, a mathematical or logical expression, or even another function (one with a return value).

    Version-1.2

  • Here is the function power and a main program to exercise it, so you can see the whole structure at once.

    int power(int m, int n); /* test power function */

    main() { int i; for (i = 0; i < 10; ++i)printf("%d %d %d\n", i, power(2,i), power(-3,i));return 0;} /* power: raise base to n-th power; n >= 0 */

    int power(int base, int n) { int i, p = 1; for (i = 1; i

  • Calling Functions There are two ways to call a function

    Any function can be called by simply using its name and argument list alone in a statement is called as call by value, as in the following example. If the function has no return value, then it is void function.

    void swap (10 , 20) ;

    functions that have a return value. Because these functions evaluate to a value (that is, their return value), they are valid C expressions and can be used anywhere a C expression can be used.

    For example :

    int power(int base, int n) { int i, p = 1; for (i = 1; i

  • # include void swap(int, int);//function prototype

    main(){intp,q;printf("Enter two integers\n");scanf("%d%d",&p,&q);printf("\np = %d,q = %d\n",p,q);swap(p,q);//function invocationprintf("\np = %d,q = %d\n",p,q);}

    void swap(int x, int y)//function definition{int temp = x;x = y;y = temp;}

    Version-1.2

  • The second method of calling a function by address

    # include void swap(int*, int*);//function prototype

    main(){intp,q;printf("Enter two integers\n");scanf("%d%d",&p,&q);printf("\np = %d,q = %d\n",p,q);swap(&p,&q);//function invocation by sending an addressprintf("\np = %d,q = %d\n",p,q);}

    void swap(int *x, int *y)//function definition {int temp = *x;*x = *y;*y = temp;}

    Version-1.2

  • RecursionThe term recursion refers to a situation in which a function calls itself either directly or indirectly. Indirect recursion occurs when one function calls another function that then calls the first function. C allows recursive functions, and they can be useful in some situations.

    For Example:main(){puts(I will be printed till stack overflows);main();}

    Version-1.2

  • /* PROGRAM TO FIND THE factorial OF THE NUMBER recursivly */# include

    int factorial(int);

    main(){int num;printf("Enter a number \n");scanf("%d",&num);printf("%d\n",factorial(num));}int factorial(int n){if(n == 0)return 1;return (n * factorial(n - 1));}

    Version-1.2

  • 1) What is the value of Zap if n = 6 (Wipro)int zap(int n){ int Zap; if(n
  • 3) What is returned (TCS)conv(int t){ int u; u=5/9 * (t-32); return(u); } (a) 15 (b) 0 (c) 16.1 (d) 29

    4) What is returned (TCS)func(int i){ if(i%2)return 0; else return 1;} main() { int i=3; i=func(i); i=func(i); printf("%d",i);} (a) 3 (b) 1 (c) 0 (d) 2

    Version-1.2

  • 5) main (){ } (TCS)int a; f1(){} f2(){} which of the functions is int a available for?

    a. all of them b. only f2 c. only f1 d. f1 and f2 only

    Version-1.2

  • 6)C allows a) only call by value b) only call by reference c) both

    7) What is the output of this program?#includeint my(int va){if(va==1)return (1);else return (va+my(va-1));}void main(void){int i=6;printf("%d",my(i));}

    Version-1.2

  • Storage Class Specifies

    Version-1.2

  • Storage Class SpecifiesThere are four storage class specifiers supported by C:externstaticregisterAuto

    These specifiers tell the compiler how to store the subsequent variable. The general form of a declaration that uses one is shown here.

    storage_specifier type var_name;

    Version-1.2

  • Typical memory arrangement

    Version-1.2

  • Local VariablesVariables that are declared inside a function are called local variables. In some C/C++ literature, these variables are referred to as automatic variables.

    Local variables may be referenced only by statements that are inside the block in which the variables are declared.

    That is, a local variable is created upon entry into its block and destroyed upon exit.

    The most common code block in which local variables are declared is the function.

    example, consider the following two functions:void func1(void){int x;x = 10;}void func2(void){int x;x = -199;}

    Version-1.2

  • Global VariablesUnlike local variables, global variables are known throughout the program and may be used by any piece of code. Also, they will hold their value throughout the program's execution. You create global variables by declaring them outside of any function. Any expression may access them, regardless of what block of code that expression is in.

    #include int count; /* count is global */void func1(void);void func2(void);

    int main(void){count = 100;func1();return 0;}

    Version-1.2

  • void func1(void){int temp;temp = count;func2();printf("count is %d", count); /* will print 100 */}

    void func2(void){int count;for(count=1; count

  • volatileThe modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program. For example, a global variable's address may be passed to the operating system's clock routine and used to hold the real time of the system. In this situation, the contents of the variable are altered without any explicit assignment statements in the program.

    A variable should be declared volatile whenever its value can be changed by something beyond the control of the program in which it appears, such as a concurrently executing thread

    Volatile, can appear only once in a declaration with any type specifier; however, they cannot appear after the first comma in a multiple item declaration. For example, the following declarations are legal :

    Version-1.2

  • /* Let T denotes some data type */

    typedef volatile T i; volatile T i; T volatile i ;And the following declaration is illegal

    T i, volatile vi ;

    Syntax

    Keyword volatile can be placed before or after the data type in the variable definition. For example following declaration are identical: Volatile T a =3;T volatile a=3; The declaration declares and initializes an object with type volatile T whose value will be always read from memory.

    Pointer declaration

    volatile T * ptr; T volatile * ptr; Ptr is a a pointer to a volatile T: volatile pointer to a volatile variable int volatile * volatile ptr;

    Version-1.2

  • volatile can be applied to derived types such as an array type ,in that case, the element is qualified, not the array type.

    When applied to struct types entire contents of the struct become volatile. You can apply the volatile qualifier to the individual members of the struct.

    Type qualifiers are relevant only when accessing identifiers as l-values in expressions. volatile does not affects the range of values or arithmetic properties of the object.. To declare the item pointed to by the pointer as volatile, use a declaration of the form:

    volatile T *vptr;

    To declare the value of the pointer - that is, the actual address stored in the pointer - as volatile, use a declaration of the form:

    T* volatile ptrv;

    Version-1.2

  • Use of volatile

    An object that is a memory-mapped I/O port

    An object variable that is shared between multiple concurrent processes.

    An object that is modified by an interrupt service routine.

    An automatic object declared in a function that calls setjmp and whose value is-changed between the call to setjmp and a corresponding call to longjmp .

    Version-1.2

  • # An object that is shared between multiple concurrent processesif two threads/tasks concurrently assign distinct values to the same shared non-volatile variable, a subsequent use of that variable may obtain a value that is not equal to either of the assigned values, but some implementation-dependent mixture of the two values. so a global variable references by multiple thread programmers must declare shared variable as volatile.

    the compiler may use a register to store the num variable in the main thread , so the change to the value by the second thread are ignored . The volatile modifier is a away of telling the compiler that no optimization applied to the variable its value be not placed in register and value may change outside influence during evaluation.

    Version-1.2

  • volatile int num ;void* foo(){while(1) { ++num ; sleep(1000); }}

    main(){ int p ; void *targ =NULL ; thread_t id ; num = 0; p = thr_create((void*)NULL , 0,foo,targ,0,&id); if(!p) printf(" can not create thread "); while(1) { printf("%d" , num ) ; }}

    Version-1.2

  • # An automatic object declared in a function that calls setjmp and whose value is-changed between the call to setjmp and a corresponding call to longjmp static jmp_buf buf ;main( ){ volatile int b; b =3 ; if(setjmp(buf)!=0) { printf("%d ", b) ; exit(0); } b=5; longjmp(buf , 1) ; }

    Version-1.2

  • volatile variable isn't affected by the optimization. So value of b is after the longjump is the last value variable assigned. Without volatile b may or may not be restored to its last value when the longjmp occurs.

    Version-1.2

  • # An object modified by an interrupt service routine Interrupt service routines often set variables that are tested in main line code. One problem that arises as soon as you use interrupt is that interrupt routines need to communicate with rest of the code .A interrupt may update a variable num that is used in main line of code .An incorrect implementation of this might be:

    static long int num ;void interrupt update(void){++num ;}main(){long val ;val = num ;while(val !=num)val = num ;return val ;}

    Version-1.2

  • When compilation system execute while statement, the optimizer in compiler may notice that it read the value num once already and that value is still in the register.

    Instead of re reading the value from memory, compiler may produce code to use the (possibly messed up) value in the register defeating purpose of original C program.

    Some compiler may optimize entire while loop assuming that since the value of num was just assigned to val , the two must be equal and condition in while statement will therefore always be false .

    Version-1.2

  • To avoid this ,you have to declare num to be volatile that warns compilers that certain variables may change because of interrupt routines.

    static volatile long int num ;

    With volatile keyword in the declaration the compiler knows that the value of num must b read from memory every time it is referenced.

    Version-1.2

  • externC/C++ allows separate modules of a large program to be separately compiled and linked together, there must be some way of telling all the files about the global variables required by the program.

    Although C technically allows you to define a global variable more than once, it is not good practice (and may cause problems when linking). More importantly, in C++, you may define a global variable only once.

    extern lets the compiler know what the types and names are for these global variables without actually creating storage for them again. When the linker links the two modules, all references to the external variables are resolved.

    Version-1.2

  • Version-1.2

  • static Variablesstatic variables are permanent variables within their own function or file. Unlike global variables, they are not known outside their function or file, but they maintain their values between calls.

    This feature makes them useful when you write generalized functions and function libraries that other programmers may use.

    static has different effects upon local variables and global variables.

    static Local Variables When you apply the static modifier to a local variable, the compiler creates permanent storage for it, much as it creates storage for a global variable.

    Version-1.2

  • static VariablesThe key difference between a static local variable and a global variable is that the static local variable remains known only to the block in which it is declared.

    In simple terms, a static local variable is a local variable that retains its value between function calls.

    Applying the specifier static to a global variable instructs the compiler to create a global variable that is known only to the file in which you declared it.

    This means that even though the variable is global, routines in other files may have no knowledge of it or alter its contents directly, keeping it free from side effects. For the few situations

    Version-1.2

  • where a local static cannot do the job, you can create a small file that contains only the functions that need the global static variable, separately compile that file, and use it without fear of side effects.

    Version-1.2

  • void fun(void);main(){ fun(); fun(); fun(); fun(); }void fun(void){ static int i = 0; printf("I is %d\n",i++);}

    Version-1.2

  • static global Variables//app.cvoid fun(void);void fun1 (void);

    static int i = 0;main(){ fun(); fun(); fun1(); fun1(); }

    void fun(void){printf("I is %d\n",i++); }

    // Lib.cvoid fun1(void){printf("I is %d\n",i++);}

    Linker error

    Version-1.2

  • register VariablesThe register storage specifier originally applied only to variables of type int, char, or pointer types. However, in Standard C, register's definition has been broadened so that it applies to any type of variable.

    Originally, the register specifier requested that the compiler keep the value of a variable in a register of the CPU rather than in memory, where normal variables are stored.

    This meant that operations on a register variable could occur much faster than on a normal variable because the register variable was actually held in the CPU and did not require a memory access to determine or modify its value.

    Version-1.2

  • int int_pwr(register int m, register int e){register int temp;temp = 1;for(; e; e - -) temp = temp * m;return temp;}In this example, e, m, and temp are declared as register variables because they are all used within the loop.

    The fact that register variables are optimized for speed makes them ideal for control of or use in loops.

    In C, you cannot find the address of a register variable using the & operator

    Version-1.2

  • Version-1.2

  • 1) Consider the following C code main(){ int i=3,x; while(i>0){ x=func(i); i--; } int func(int n){ static sum=0; sum=sum+n; return(sum);}

    The final value of x is (a) 6 (b) 8 (c) 1 (d) 3

    Version-1.2

  • 1. #includeInt main(void){int x=4;int a=2;int b=4;int c=8;if(x==b) x=a;else x=b;if(x!=b) c=c+b;else c=c+a;printf("c=%d\n",c);}2. where does printf write its output

    3.Write syntax of 'auto'. What it means?

    Version-1.2

  • 4. Which is correct syntax?unsigned long double floatinteger struct int

    5.Which is correct statement with printf to print, 30 character ,4 decimalvalue double value%-30.4f %-30.4e %#30.4f %4.30e %-4.30f

    6. maximum decimal number in a byte is ?

    7. What the stdio.h contains?

    Version-1.2

  • 8. What is the output of this program? #include void main(void) { printf("2"); while(3) printf("3"); printf("4"); }

    9. What is the output of this program?#includevoid main(void){int v=2;switch(v){case 1:printf("0");case 2:printf("1");case 3:printf("2");default :printf("3"); break;}}

    Version-1.2

  • 10. What is the output of this program?#includevoid main(void){int x=1/2;if(x)printf("%d",x);} 11) main() {extern int a;a=10;printf("%d",a);}

    Version-1.2

  • Arrays

    Version-1.2

  • ObjectiveWhy Arrays?What Is an Array?

    Single-Dimensional ArraysNaming and Declaring Arrays Initializing Arrays Multidimensional Arrays Initializing Multidimensional Arrays Maximum Array Size

    Version-1.2

  • ArraysAn array is a collection of data storage locations, each having the same data type and the same name. Each storage location in an array is called an array element.

    Single-Dimensional Arrays

    A single-dimensional array has only a single subscript. A subscript is a number in brackets that follows an array's name. This number can identify the number of individual elements in the array.

    Declaration of array is as follows :float expenses[12];

    The array is named expenses, and it contains 12 elements. Each of the 12 elements is the exact equivalent of a single float variable. All of C's data types can be used for arrays .

    Version-1.2

  • ArraysAll of C's data types can be used for arrays

    C array elements are always numbered starting at 0, so the 12 elements of expenses are numbered 0 through 11.

    When an array is declared, the compiler sets aside a block of memory large enough to hold the entire array. Individual array elements can be stored in sequential memory locations.

    Individual elements of the array are accessed by using the array name followed by the element subscript enclosed in square brackets.

    e.g. expenses[1]=34.90;expenses[10] = expenses[11]; When using arrays, keep the element numbering scheme in mind: In an array of n elements, the allowable subscripts range from 0 to n-1.

    Version-1.2

  • Naming and Declaring Arrays An array name must be unique.

    It can't be used for another array or for any other identifier (variable, constant, and so on).

    array declarations follow the same form as declarations of non array variables, except that the number of elements in the array must be enclosed in square brackets immediately following the array name.

    When an array is declared, one can specify the number of elements with a literal constant (as was done in the earlier examples) or with a symbolic constant

    #define MONTHS 12int array[MONTHS]; //is equivalent to below statement:int array[12];

    Version-1.2

  • Initializing Single Dimensional Array int array[4] = { 100, 200, 300, 400 };

    If the array size is omitted, the compiler creates an array just large enough to hold the initialization values. Thus, the following statement would have exactly the same effect as the previous array declaration statement:

    int array[] = { 100, 200, 300, 400 };

    It can be however, include too few initialization values, as in this example:int array[10] = { 1, 2, 3 };

    If an array element is not explicitly initialized, it is not sure that what value it holds when the program runs. If too many initializers are included (more initializers than array elements), the compiler detects an error.

    Version-1.2

  • A program to read and display the elements#include

    main(){int element[10],ctr;printf("\n Reading the elements\n");for(ctr=0;ctr

  • Multidimensional Arrays A multidimensional array has more than one subscript. A two-dimensional array has two subscripts; a three-dimensional array has three subscripts, and so on. There is no limit to the number of dimensions a C array can have.

    For example, a program that plays checkers can be written. The checkerboard contains 64 squares arranged in eight rows and eight columns. This program could represent the board as a two-dimensional array, as follows:

    int checker[8][8];

    The resulting array has 64 elements: checker[0][0], checker[0][1], checker[0][2]...checker[7][6], checker[7][7].

    Similarly, a three-dimensional array could be thought of as a cube. All arrays, no matter how many dimensions they have, are stored sequentially in memory

    Version-1.2

  • Initializing Multidimensional Arrays Multidimensional arrays can also be initialized.

    The list of initialization values is assigned to array elements in order, with the last array subscript changing first.

    For example:

    int array[4][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

    results as array[0][0] is equal to 1 array[0][1] is equal to 2 array[0][2] is equal to 3 and so on.

    Version-1.2

  • Initializing Multidimensional Arrays results as array[0][0] is equal to 1 array[0][1] is equal to 2 array[0][2] is equal to 3 and so on.

    The following initialization is equivalent to the one just given:

    int array[4][3] = { { 1, 2, 3 } , { 4, 5, 6 } ,{ 7, 8, 9 } , { 10, 11, 12 } };Remember, a comma must separate initialization values even when there is a brace between them. Also, be sure to use braces in pairs a closing brace for every opening brace or the compiler becomes confused.

    E.g.Program

    Version-1.2

  • Adding matrix elements#includemain(){int m1[2][2],m2[2][2],m3[2][2];int i,j,r,c;

    printf("Enter matrix size\n");scanf("%d%d",&r,&c);

    printf("enter the elements into matrix m1\n");for(i=0;i

  • Adding matrix elementsprintf("enter the elements into matrix m2\n");for(i=0;i
  • PROGRAM TO MULTIPLY THE TWO MATRIX#include#includemain(){int a[10][10],b[10][10],c[10][10];int row1,row2,col1,col2;int i,j,k;printf("ENTER THE ROW AND COLUMN ORDER FOR THE MATRIX A :\n");scanf("%d%d",&row1,&col1);printf("ENTER THE ROW AND COLUMN ORDER FOR THE MATRIX B :\n");scanf("%d%d",&row2,&col2);

    Version-1.2

  • PROGRAM TO MULTIPLY THE TWO MATRIXif ((row1 == row2) && (col1 == col2)){printf("ENTER THE %d ELEMENTS INTO %d * %d MATRIX A :\n, row1*col2,row1,col1);for (i=0; i
  • PROGRAM TO MULTIPLY THE TWO MATRIXprintf("ENTER THE %d ELEMENTS INTO %d * %d MATRIX B :\n",row1*col2,row1,col1);for (i=0; i
  • PROGRAM TO MULTIPLY THE TWO MATRIX for (i=0; i
  • THE TRANSPOSE OF THE MATRIX#includemain(){int a[10][10];int row,col;int i,j;printf("ENTER THE ROW AND COLUMN ORDER FOR THE MATRIX :\n");scanf("%d%d",&row,&col);if (row == col){printf("ENTER MATRIX A :\n");for (i=0; i
  • THE TRANSPOSE OF THE MATRIXfor (i=0; i
  • THE NORM AND TRACE OF THE MATRIXmain(){int *a,i,j,n,trace=0;float norm=0.0;printf("ENTER THE ORDER OF THE MATRIX :");scanf("%d",&n);for (i=0; i
  • THE NORM AND TRACE OF THE MATRIXfor(i=0; i
  • Maximum Array Size The size of an array in bytes depends on the number of elements it has, as well as each element's size. Element size depends on the data type of the array and computer. These are the data type sizes for many PCs.

    To calculate the storage space required for an array, multiply the number of elements in the array by the element size. For example, a 500-element array of type float requires storage space of 500 * 4 = 2000 bytes.

    one can determine storage space within a program by using C's sizeof() operator; sizeof() is a unary operator, not a function. It takes as its argument a variable name or the name of a data type and returns the size, in bytes, of its argument.

    Version-1.2

  • Selection sort #include

    void selection(int [],int );

    main(){int n,a[10],i;

    printf("enter limit of an array");scanf("%d",&n);for(i=0;i

  • Selection sortvoid selection (int a[],int n){int i,j,temp;for(i=0;i
  • Understanding Pointer

    Version-1.2

  • ObjectivesWhat Is a Pointer Declaring Pointers Initializing Pointers Pointers and Variable Types Pointers and Arrays Pointer Arithmetic Incrementing Pointers Other Pointer Manipulations Passing Arrays to Functions

    Version-1.2

  • What Is a Pointer ?To understand pointers, a basic knowledge of how the computer stores information in memory is needed.

    A PC's RAM consists of many thousands of sequential storage locations, and each location is identified by a unique address. The memory addresses in a given computer range from 0 to a maximum value that depends on the amount of memory installed.

    When declaring a variable in a C program, the compiler sets aside a memory location with a unique address to store that variable. The compiler associates that address with the variable's name. When the program uses the variable name, it automatically accesses the proper memory location. The location's address is used, but it is hidden.

    To summarize, a pointer is a variable that contains the address of another variable. Now here are some details of using pointers in the C programs.

    Version-1.2

  • Declaring Pointers A pointer is a numeric variable and, like all variables, must be declared before it can be used.

    A pointer declaration takes the following form:

    typename *ptrname;

    Example

    char *ch1, *ch2;float *value, percent;

    Version-1.2

  • Initializing Pointers Until a pointer holds the address of a variable, it isn't useful.

    the program must put it there by using the address-of operator, the ampersand (&). When placed before the name of a variable, the address-of operator returns the address of the variable. Therefore, initialize a pointer with a statement of the form

    pointer = &variable;

    Version-1.2

  • Pointers and Variable TypesThe address of a variable is actually the address of the first (lowest) byte it occupies.

    int vint = 12252;char vchar = 90;float vfloat = 1200.156004;

    int *p_vint;char *p_vchar;float *p_vfloat;

    Version-1.2

  • Pointers and Variable Types

    p_vint = &vint;p_vchar = &vchar;p_vfloat = &vfloat;Each pointer is holds the address of the first byte of the variable.

    Version-1.2

  • # include main(){int x = 5;int *p = &x;printf("x=%d\n",x); printf("p=%u\n",p);printf("&x=%u\n",&x);printf("*p=%d\n",*p);printf("&p=%u\n",&p);printf("It is address of x *&p=%u\n",*&p);}

    Version-1.2

  • void pointersPointers defined to be of a specific data type cannot hold the address of some other type of variable.

    To assign the address of an integer variable to a pointer of type float. This problem can overcome by using a general purpose pointer type called void pointer.

    E.g.Void *v_ptr;

    Pointers defined in this manner do not have any type associated with them and can hold the address of any type of variable.

    Pointers to void cannot be directly dereferenced like other pointer variables using the indirection operator. Prior to dereferencing a pointer to void, it must be suitably typecast to the required data type.

    Syntax :*((data type *))pointervariable;

    Version-1.2

  • E.g. void pointer main(){ int i1=100; float f1=200.5; void *vptr ; vptr = &i1; printf(" i1 contains %d",*((int *)vptr));}

    Version-1.2

  • Pointers and ArraysAn array name without brackets is a pointer to the array's first element. Thus, if declared an array data[], data is the address of the first array element.

    Using the expression &data[0] to obtain the address of the array's first element is allowed. In C, the relationship (data == &data[0]) is true.

    The name of an array is a pointer to the array. Remember that this is a pointer constant; it can't be changed and remains fixed for the duration of program execution.

    Version-1.2

  • Pointers and ArraysThe declaration int a[10]; defines an array of size 10, that is, a block of 10 consecutive objects named a[0], a[1], ...,a[9].

    The notation a[i] refers to the i-th element of the array. If pa is a pointer to an integer, declared as ,

    int *pa; then the assignment pa = &a[0];

    sets pa to point to element zero of a; that is,

    pa contains the address of a[0].

    Version-1.2

  • Pointers and Arraysa[i] -> is internally evaluated as :

    Base address + index * sizeof(data_type);Thus a[5] : By considering base address(2000) which is evaluated as 2000 + 5 * 4 = 2020 -> cof(2020)Example :

    Version-1.2

  • Pointers and Arrays#include int my_array[] = {1,23,17,4,-5,100};

    int *ptr;int main(void){ int i; ptr = &my_array[0]; /* point our pointer to the first element of the array */ printf("\n\n");for (i = 0; i < 6; i++) {printf("my_array[%d] = %d ",i,my_array[i]); /*

  • Pointers and Arraysmain(){int num[10],i,j,t;int *p=num;printf("enter elements into the array\n");for(i=0;i
  • Pointers and Arraysif (*(p+j) > *(p+(j+1))){t=*(p+j);*(p+j)=*(p+(j+1));*(p+(j+1))=t;}}puts("printing ...............\n");for(i=0;i
  • Pointer Arithmetic There is a pointer to the first array element; the pointer must increment by an amount equal to the size of the data type stored in the array. If ip points to the integer x, then *ip can occur in any context where x could, so *ip = *ip + 10; increments *ip by 10. The unary operators * and & bind more tightly than arithmetic operators, so the assignment y = *ip + 1 takes whatever ip points at, adds 1, and assigns the result to y, while *ip += 1 increments what ip points to, as do ++*ip and (*ip)++ The parentheses are necessary in this last example; without them, the expression would increment ip instead of what it points to, because unary operators like * and ++ associate right to left.

    Version-1.2

  • Other Pointer ManipulationsThe only other pointer arithmetic operation is called differencing, which refers to subtracting two pointers. If two pointers are pointing to different elements of the same array, subtract them and find out how far apart they are.

    ptr1 - ptr2

    Pointer comparisons are valid only between pointers that point to the same array. Under these circumstances, the relational operators ==, !=, >, =, and

  • Other Pointer Manipulationsptr1 < ptr2

    is true if ptr1 points to an earlier member of the array than ptr2 does.This covers all allowed pointer operations. Many arithmetic operations that can be performed with regular variables, such as multiplication and division, don't make sense with pointers. The C compiler doesn't allow them. For example, if ptr is a pointer, the statement

    ptr *= 2;generates an error message.

    Version-1.2

  • Pointers and Strings C permits two alternate ways of achieving the same thing. First, one might write:

    char my_string[40] = {'T', 'e', 'd', '\0',}; But this also takes more typing than is convenient. So, C permits:

    char my_string[40] = "Ted"; When the double quotes are used, instead of the single quotes as was done in the previous examples, the nul character ( '\0' ) is automatically appended to the end of the string.

    #include

    char strA[80] = "A string to be used for demonstration purposes";char strB[80];int main(void) {

    Version-1.2

  • Pointers and Strings int main(void)

    { char *pA; /* a pointer to type character */ char *pB; /* another pointer to type character */ puts(strA); /* show string A */ pA = strA; /* point pA at string A */ puts(pA); /* show what pA is pointing to */ pB = strB; /* point pB at string B */ putchar('\n'); /* move down one line on the screen */ while(*pA != '\0') /* line A (see text) */ { *pB++ = *pA++; /* line B (see text) */ } *pB = '\0'; /* line C (see text) */ puts(strB); /* show strB on screen */ return 0; }

    Version-1.2

  • Pointers and function argumentsSince C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function.In the swap(a, b); function call by value , swap cant affect the argument a and b in the routine that called it. The way to obtain the desired effect is for the calling program to pass pointer to the values to be changed :Swap (&a, &b);Since the operator & produces the address of a variable, &a is a pointer to a.Thus the function looks like:

    void swap(int *px, int *py){int temp = *px;*px = *py;*py = temp }

    Version-1.2

  • Pointers and functionsWhen an array name is passed to a function, the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address.Here is a function xstrlen(), which computes the length of a string.

    Main(){charstr[25] = hello world;printf(%d\n,xstrlen(str));}

    /* xstrlen: return length of string s */int xstrlen(char *s){ int n; for (n = 0; *s != '\0', s++) n++;return n; }

    Version-1.2

  • We will illustrate more aspects of pointers and arrays by studying versions of two useful functions adapted from the standard library.

    The first function is strcpy(s,t), which copies the string t to the string s. It would be nice just to say s=t but this copies the pointer, not the characters. To copy the characters, we need a loop.

    The array version first:

    /* strcpy: copy t to s; array subscript version */ void strcpy(char *s, char *t){ int i; i = 0; while ((s[i] = t[i]) != '\0') i++; }

    Version-1.2

  • For contrast, here is a version of strcpy with pointers:

    /* strcpy: copy t to s; pointer version */void strcpy(char *s, char *t){ int i; i = 0;while ((*s = *t) != '\0'){ s++; t++; }}/* strcpy: copy t to s; pointer version 2 */void strcpy(char *s, char *t){ while ((*s++ = *t++) != '\0') ;} As the final abbreviation, observe that a comparison against '\0' is redundant, since the question is merely whether the expression is zero. So the function would likely be written as

    /* strcpy: copy t to s; pointer version 3 */ void strcpy(char *s, char *t) { while (*s++ = *t++) ; }

    Version-1.2

  • The second routine that we will examine is strcmp(s,t), which compares the character strings s and t, and returns negative, zero or positive if s is lexicographically less than, equal to, or greater than t. The value is obtained by subtracting the characters at the first position where s and t disagree. /* strcmp: return t */

    int strcmp(char *s, char *t){ int i; for (i = 0; s[i] == t[i]; i++) if (s[i] == '\0') return 0; return s[i] - t[i];}

    The pointer version of strcmp:int strcmp(char *s, char *t){ for ( ; *s == *t; s++, t++) if (*s == '\0')return 0; return *s - *t; }

    Version-1.2

  • Initialization of Pointer ArraysConsider the problem of writing a function month_name(n), which returns a pointer to a character string containing the name of the n-th month. This is an ideal application for an internal static array. month_name contains a private array of character strings, and returns a pointer to the proper one when called. This section shows how that array of names is initialized. The syntax is similar to previous initializations:

    /* month_name: return name of n-th month */

    // Function returning pointer

    char *month_name(int n){ static char *name[] = { "Illegal month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; return (n < 1 || n > 12) ? name[0] : name[n]; }

    Version-1.2

  • Array of pointersAlthough we have phrased this discussion in terms of integers, by far the most frequent use of arrays of pointers is to store character strings of diverse lengths, as in the function month_name. Compare the declaration and picture for an array of pointers:

    char *name[] = { "Illegal month", "Jan", "Feb", "Mar" };

    with those for a two-dimensional array:

    char aname[][15] = { "Illegal month", "Jan", "Feb", "Mar" };

    Version-1.2

  • malloc

    Version-1.2

  • void *malloc(size_t size)

    malloc returns a pointer to space(memory) for an object of size size, or NULL if the request cannot be satisfied. The space is uninitialized.

    Calls to malloc and free may occur in any order; malloc calls upon the operating system to obtain more memory as necessary.

    Rather than allocating from a compiled-in fixed-size array, malloc will request space from the operating system as needed.

    Version-1.2

  • Rather than allocating from a compiled-in fixed-size array, malloc will request space from the operating system as needed.

    Since other activities in the program may also request space wit