[go: up one dir, main page]

0% found this document useful (0 votes)
62 views27 pages

C

c document

Uploaded by

Arati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
62 views27 pages

C

c document

Uploaded by

Arati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 27
FACE “If it wasn't for C, we'd be writing programs in BASI, PASAL, and OBOL.” ‘Contents Introduction ~ Evolution - Versions of C - Structure of C ~ Executing & Conipiling ~ Program development steps Basies of C = Data types - Variables , Constants & keywords ~ Input & Output Operators: [Control Statements, Looping & Branching _ Chapter 1: Introduetion Cis a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operatin, system. This prograniming language was initially developed by Dennis Ritchie between 1969 and 1973 at AT&T Bel Labs. Cis one of the most widely used programming languages of alltime, and there are-very few computer architecture for which a C compilet does not exist. Many later languages have borrowed directly or indirectly from C, including C# D, Go,Java, JavaScript, Limbo, LPC, Perl, PHP, Python, Unix’s C shell and Zeno, 1.1 Evolution; * ALGOL was the first Computer larigtage tease block stricture: * In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) primaril spa Focus Academy fir Career Enhanicement | www. focusacademy.in Page | of 17 Scanned by CamScanner WIZ ee "H.C wos evolved fry for writing system software, ' oy many features of CPL and called it 'B from In 1970, Ken Thompson created a language using mat: bes ALGOL, BCPL and B by Dennis Ritchie at Bel! Laboratories in Aon Se Cuses many concepts from these languages and added some new UNIX operating system was coded almost entirely in C. res like data tyes jons af C: ic pays no attention to Single-quotes ang traditional ive welif, Herror, ate. Ritchie, Some addtt ‘Traditional C— It. can invoke traditional prepracessors using me double-quotes. # and aif are not available, and will not reeognt K & RC — li was developed by Brain Kemigham and Dennis retum type), Struct Assignment for struct, enum Spo Ate ANSI on en Netal Sits ata adopted by ISO in 1990 and hence called as C 189 refers to the same programming language. ‘C99 —It includes inline functions, new data types like long long i create fi Embedded € Used for Miceconvoer and Microprocessor based applications, 10 eteate Biles eae Rin, Historically, embedded C programming requires nonstandard cxtensions to the C Oe Ipport exotic features such as fixed-point arithmetic, multipte distinct memory banks, and basic 1/0 op ; onal concepts WETE Void{withog sat and complex type; one line comment f ucture of C: Cis also called “Procedural language” because it follows a particular pattern while programming, For example, we include header files for those related functions and declare variable name before they are used. /* Sample program *) —* * Comment line*/ ffinclude /* Preprocessor directive */ void main{ ) &* fanction*/ int b, sum 5 (* Declaration part */ int a= 10; /* Initialization part */ printf(‘An Enter the value oF bi"); Ougpur scanittid”, &b); Input */ sum= a+b; &* Processing */ printi(*Sum of a and b is: Yad", surn); /* Ougpus */ geteh( } Output: Enter the value of b : 20 Sum of a and bis :30 _ Executing and compiling: Pre processing - Using a Preprocessor program to convert € sure code j "wdefine” statements will be processed and replaced in the asurce oon in aepawted Source code, “include” and _ Brprocsiting Belloc an swing output to hello.i) * Cepp bello.c -o hello" - Preprocessor * Compilation - Using a Compiler program ta convent © hello" - Comper compiling bello and saving output to elle se mee to assembly source code. ("cel hello.i -0 - ("as hello.s -0 hello.o" - Scanned by CamScanner FACE Wizi3-01 — © Loading - Using a Loader program ta load the executable cade into CPU for execution. ("lead hello” ~ Loader loading bello and running hello) ‘Sourse program preprocessing 1 Source peoeram comping i Assenibty progam assembling 4 Machine instractont ‘ Sakic 4 Executable code * Program development steps: © Analysis — Define the problem © Design - Algorithm * Coding Documenting © Compiling and Running * Testing and Debugging © Maintenance “Test your shill: 1. C cannot be used on a. MS-DOS b Linux ©. Windows None of these 2, The default return type for main( ) is : aint ‘b double ‘cereturn: dvoid 3. How many main() function can we have in © program? al m= ¢. Compiler dependent d. Unlimited 4, What is the header file for handling FILES in C7 = — a. FILE. b. stdio.h ¢, file d. conio.h 5. What is the header file for eprintf in C? a. stdioh b. conio.h ¢. string.h d. None of these 6. Which of the following is the flowchart symbol for exception or run-titie error? ‘oO “RB ‘O ‘a Focus Academy for Career Enhancement | www.focusacademy.in, Scanned by CamScanner WIZA3.01 ee ‘Chapter 2: Basies of C Data types: p Jeinds of data and 10 provide wsefit ip progmmmer to process cor Tad called program, A program ing, ban is yosed to hel akg pei Port ipct Tished by executing series of comma f. The task of data processing is secon ee aly contain diferent types of datatypes Cineger, oa, character ete) and mn pen pels ce being used in the program. C language is rich of data types. A.C programmer eat Variables, Constants & keywords: i aia) madame) [eoroameaam bd lenar aey Yyeedat ioe danstion oat pointer double ‘erveture voit union A variable is just @ named area of storage that can hold single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually ‘uy to do anything with it. The Programming language C has two types of variables: * Local Variables © Global Variables p A constant is a number, eharacter, or character string that can be used as a value in s program. Use eonstants to represent floating-point, integer, enumeration, of character values that cannot be modified, The predefined words of the C-languige thal are used for special purposes’ in the source program are Keyyonde, Keywords RERSORSOWASE reserved words: For Example! keyword "int" is used to declare the integer type varia Input & Output: ‘The header file STDIO.H and its associated abject code file define the standard ji printf) function : This is one of the most frequently used functions in C for ping fc fo print a integer, Ys is being used to print a sting os being use to print a Hoat and ac is being used to print a characte. Example; include ‘maint ) t intdee~ 5; char surf] = "abe"; | char ch float pi = 3 Focus Acideimy for Career Enhancement | www. focusaeademy.in apni age Scanned by CamScanner FACE Wine | printi("$6a %és 96 %cln", dee, sir, pi,ch); } scanf) Fanction : This is one of the most frequently used functions in C for input from te command line, Here %éd is being used to read an integer value and we are passing Adee o store the value of the input being read, Here & indicates the address of variable dec. Example: ‘include main() t int dees char st J; char ch; float pi; prinef("Enter the valves:in"); scanfl"%d %s %f Yecin", &edec,str, &pidech); printi{"Entered values are:" Printféd Shs %6f Men", dec, str, pieh); ? Output: Enter the values: 5 abe 3.140000 c Entered values are: 5 abe 3.140000 ¢ {$printf() and fseanf{ ) are commonly used to access files. sprintf) and sscanf{) are similar‘o fprint{ ) and Beanf{ ) except they are Gsed to read as and write to string, ‘Test your skill: 1, Which of the following special symbol is allowed in a variable-name ? a" (asterisk) B_(underscore) (ot) 4.— (hyphen) 2, Whats the maximum length of the variable name in C? a. 8 or 31 b4 20rd Unlimited 3. How many of the following are invalid variable name? NUMBER _oum Bnum ‘aum93 firstname last namie nUMBER ‘midname, 4321 as b3 e2 4, More than 5 4, Which of the fotlowing is not a data type in C? Focus Academy for Garces Eabancement] www, focusneademy.in Pape Sof 17 Scanned by CamScanner FACE ie . string, a. int b. float 5. How many decimal digits does a floating point value support? ad b6 e8 6. What is the size of LONG DOUBLE in C? a4 Bytes b. & Bytes ©. 10 Bytes 7, Guess the output: main() ( clrsert); int x=10; Printf{“%od" x); } Error ©. Garbage Value: a 10 8. What could be the output far following? main() f int a= ~~ 2; Prin a «11 10, Predict the output of following cod: (0 int var=20; Fea tirm int var=30; pe th } a. Error b.20,30 ©. 20,20 d. 16 Bytes d None of these d. Error ~ 40,1 d. Garbage value Focus Academy for Career Enhancement | Www focusacademy.in Paoe Kat | Scanned by CamScanner PACE wiei3o1 TO ‘Chapter 3: Operators ‘An operator is symbol that operates on a certain datatype and produces the output as the result of the operation. C Programming language provides several operators to perform different kind of operations There are operators for assignment, srithmetie functions, logical functions and many. more, ‘These: operators Senerally work on many types of variables or constants, iheugh some are restricted to work on certain types, Mest Operators are binary, meaning they take two operinds.A few ane unary and only take one operand. The following is the order of precedence, ftom highest to lowest, for the C programming language: Description Associntivity JParentheses function cally lef-to-night lBrackets (anay subscript} [Member selection via objact name [Member selection via pointer [Postiix increment/dectement [Prefix incrementicecrement right-to-left lUnary plusfminus Logical negation/bitwise complement [Gast (convert value to temporary value of type) Dereierence [Address (of operand) Determine size in bytes on this implementation Multiplication/dimsionfmodlus left-to-right ‘Addition/subiraction left-to-aght Bitwise shift let, Bitwise shit right left-to right Relational less than/iess than or equal to left-to-right Relational gteater thaniqraster than or cepa to Relational is equal tos not equal to letcioright Bicwise ANO lettonight * Ektwise exclusive OR left-to-ight 1 Bitwise inclusive OR lek-to-night ry Logical AND lotco-ight i Toga OR Tet-to-right 2: [Temary conditional right-to-left = [Assignment night-toleh = ‘Addition/subtraction assignment *= = | Multipicationldivision assignment %= B= | Modulus/bitwise AND assignment. =F \Gtwise exclusive/inclusive OR assignment See >> |Bitwise shift lefuiright assignment. (Comma (separate expressions) leflto-right Note: The value of result is not guaranteed to be consistent across different compilers, because it is not clear whether y : Of the division operator) before using it, cmeading on which compiler you are using, the variable result can vary, The bottom line is that you should net anc the same variable multiple times in a single expression when using opetators with side effects Foeus Academy for Career Enhancement | www. focusacademy.in Page 7 of 17 rr Scanned by CamScanner FACE Test your skill: wine) 11. Which among the following operator has the right to left associativity? 2. Arithmetic b. logical . Relational 12,Predict the outpat of following code: ~ intxa-10, Re S+II-6 ta; printf(-%ed"x); ) asl b.5L5 e3l 13.Prediet the output of following code: b.20 0.22 14.Predict the output of following code: main() j { bese int a=10,x=20; aah + 10; Xm + Ha; ©. 10,20 b 1220 0. 22,43 15.Predict the output of following code: int) int i=10,j=2,k=0.m, mat Hid dct Sed He, pea amie kan); a. 113,11 © 113,10 b.11,2,0,1 i. Increment/Decrement None of these 4.23 42,42 .10,2,0,1 Focus Academy for Career Enhancement | www.focusacademy in Page 8 of 17 Scanned by CamScanner FACE wiztn Se 16 Predict the output of following code: ‘main() { ft 102,60, mt e+ i print(™Soded4 dei kara): ) a 3,11 bh 2 e310 10,201 17, Predict the ouput of following code: maint) t int i=10, Printed, Ye Hie: 1 12 Bag ect M 41110 18, Predict the output of following code: L535 ret io, a. Envor ‘bis? 19.Predict the output of follow: 20.Predict the output of following cade: me int x=10y—10; printf ex \t"x<<2): printf “%6x"y>>2}; } 0.28 fild b.40 3 ¢. Error 00 Foss Academy for Career Fnbancement| www focusscademy.in Page 9of 17 Scanned by CamScanner Fach wien ——_ Chapter 4 - Control statements, Looping and Branching Control stztements enable us ta specify the flow of pangram como: je the order in which the instwetions in a program must be executed, They inake it possible lo make decisions to perform lasks repesiedly orto jump from ome section of cade to another. 1, if-else if-else statement ~ This control statement executes a bloek of code when corresponding: condition statement is satisfied. A simple if-else statement have syntax: iffcondition) { ) else if (condition) . Meade . Ieode { } che eee ' : Heode I 2. for statement — Code under for statement is:executed when ever condition is: satisfied. Syntax of for control statesnent; for(initialization; condition; iteration} { } 3. whille statement — ee which repeate:a. block of code: while condition is true, Extra care should be taken con #6 hile satement an enter infinite loop if it do a a isis licade. Meode 4, do-while statement - It is similar co while statement. Only difference is do-white statement is before checking the condition. aaa do. { Uieode ) while(condition); 3. snitccae tena ~ This is another focra of the multi way decision. It is well structured. The syntax for switch ‘switch{expression) Focus ‘Academy for Career Enhancement | Www. focusacademy. in Page 10 of 17 a Scanned by CamScanner FACE wizi3-01 Heode break; fase condition 2: Heode break; case condition n: Hoade break; default: Heade } ‘The value of this expression is either generated during program execution or read in as user input. The case ‘whose value is the same as that of the expression is selected and executed. The optional default label is used to specify the code segment to be executed when the value of the expression does not match with any of the case values. “Test your skill: 1. Predict the output of following code: a. ais the smallest number b. b is the smallest number Predict the output of following code: main() { if) a, Enor bhai c.hello No oops Focus Acaclemy for Career Enhancement | www.focusacademy.in Page 11 of 17 Scanned by CamScanner FACE 4. Predict the output of following code: main() { iN{5.4,3,2,1,0) prineft“True”); else Print “False"), , a True b. False . True False 5. Predict the output of following code: main() f iff prine(“Hai") printi{“Face”); 2 else pet Foca a. Error b, HaiFace ©, HaiFocus 6. Predict the output of following cade: main) { if) : printf(“True”; else - printf(“False"); } a Tue 6, True False Predict the output of folkowing codes...» main() { int #=100,b=300, iffa>s0) a=200; b=400; printi("*6d"b); } a. 400 b. 300 ©, 100 8, Pind the error, if any, in the while loop WiE3o 4 Brvor Face d. Error d. Error Scanned by CamScanner FACE inti= 1; while( i-<= 5) { priatfi'“tod “, i): if(i=2) goto here: } } Fume) t here: printf(“\n Tam here"); Error: 9. Predict the output of following code main() { int a=2; iffa—,—a, 3) printi(“Tom"y, else primti(“Jerry"); ? a. Tom ‘b. Jerry © Tom Jerry 10,Prediet the output of following cove: 8, onetwothree: b, Invalid option ¢. one two 11. Can the switch statement have strings? ( Yes/No) Practice exercise: 1, Guess the output: main() Print” stat Focus Academy for Career Enhancement | www.focusacademy.in WIzA3-01 d. Error d. None of these Page 13 of 17 Scanned by CamScanner WITI3-01 FACE a } a2ord 2. Predict the output of following code: b Lord ©. Garbage value main() ( int a=b=c=d=10, printi("%e, od, Yea, a,bie.8), 1 a. Error 'b, 19,10,10,10 ©. GV,GV,GV,10 NOTE: GV-Garbage Value 3. Predict the output of following, cade: ae 6.201 a. Error b. 195 aged b, mot equal ©. Enor 5. What is the retumn type of printf) and scant) friction? a. int b. char c. void ‘6. What is the output for following? ; ian) printi(%626%4%"), ) a. 64696 b. 6% eee Fouts Academy for Carer Enhancement | www focusacademy, in ASCH valuc of a d.GV.GV,GV.GV 4. cqual not equal 4. float d, Garbage Value Page 14 of 17 Scanned by CamScanner ao bl c. Garbage value Error 8. How do you print ‘in’ on the output screen? 9. How do you print “hai” on the console without using single semicolon in code? 10, Guess the output: nain() hatte ks"); Printf"b mia"; printf" han"); ) . ksmiba b mis hai 4. hamiks: 1.,Predictthe ourpot of following code: a. FACES b. Error ¢. Garbage value d. FACE 13. Predict the output of following code: ‘main() precy a. FACE BFA 6. CE 4. Garbage value |4.Predict the output of following code: maint) bewraton; Focus Academy for Carver Enhancement | www. focusacademy.in Page 15 of 17 Scanned by CamScanner Wizisar Se printi(“Ya2d",a); ! #2000 6.20 ©. 4000 d. Garbage value 15. Predict the ourput of following code: main() { int x=10,..4,; detx +x, =x BA x | Iprintit"hait"); ax Rd x Sa printi"hailt"), printh("%ad, Yd, 264" dca); + 11 bai had 0 1,1 hat a. Error behai 10,1,1 16,Predict the output of following code: main() innxa-to seam lO?printf(“haiW")-print("bellovn"), : i ahai 4 b. Error © hello 3 a. hai hello 17 Predict the ou ff towing de: , Oxf 4, ox0000 18.Predict the output of following code: os int a=10,b=20,c5,d; d=a) Any neater ofa mrocute can be accessed as: structure_varlable_name.member_name Suppose, we want to access salary for variable p2, It can Be accessed as; p2.salary Structures within structures Structures ean be nested within other structures in C programming. gear Tosa Academy for Career Enhancerien | eye Scanned by CamScanner FACE wizt3-02 struct complex{ int imag_vatue; float real_value; k struct number{ struct complex cl: int rea Yet,n2; Defining a Union To define a union, we mist use the union statement as we did while defining structure. The union statement defines. ‘@ new data type, with more than one member for aur program. The format of the union statement Is as follows: union [union tag] { member definition; member definition; member definition } fone or more union variables]; ‘The union tag is optional and each member definition is a normal variable definition, such as int |; or float f; or any ‘ather valid variable definition. At the end of the union's definition, befare the final semicalon, you can specify one or ‘more union variables but itis optional, Scanned by CamScanner CHAPTER 9: MEMORY ALLOCATION ‘The C language supports two kinds of memory allocation through the variables in C programs: * Static allocation is what happens when you declare a static or global variable, Each static or global variable defines one block of space, of a fixed size. The space is allocated once, when your program is started (part of the exec operation), and is never freed. & © Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable, The space for an automatic variable is allocated when the compound statement containing the declaration isentered, and is treed when that compound statement Is exited. In GNU C, the size of the automatic storage can be an expression that varies. in ather implementations, it must be a constant, Dynamic memory allocation is a technique in which programs determine as they are running where to store some information. You need dynamic allacation when the amount of memory yauneed, or how long you continue to need it, depends on factors that are not known before the program runs, Storage classes A storage class defines the scopetvistbility) and lifetime of vartables and / or functions within a C program. The following are the storage classes used in'C * auto register static «extern In C programming, static and automatic memory allocation is done implicitly, But by writing program, wecan allocate memory dynamically. The functions used for dynamic allocation are malloc(), ealloc() and realloc() Allocating a block of memory: void *maiioc(size_t size); Allocating multiple block of memory: void *calloc(size_t num, size_t size); Releasing used space: free(ptr): aa cy Tr Caran area ww coca nea Scanned by CamScanner FACE WIZ13-02 CHAPTER 10; FILES A file Is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind, The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual ‘document; fields and records belonging to a database; or pixels from a graphical image. Essentially there are two kinds of files that programmers deal with, they are text files and binary files. These two classes of files will be discussed in the following sections. ASCII Text files A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file Is usually opened for only one kind of operation (reading. writing, or appending) at any given time. Binary files A binary file is no different to a text ler itis collection of bytes in C Prograifiming Language a byte and a character are equivalent. Hence a binary file is also referred ta as a character stream, but there are two essential differences, 1. No special processing of the data‘occurs and each byte of data is transferred to or from the disk unprocessed. 2. € Programming Language places no constraints an the file, and it may be read from, or written to, in any manner chasen by the programmer. There are types and functions in the library stdla.h that are used for file //0. One must ensure about including the header file while working with files, For files, to read of write, we need a file painter, Example : F FILE Open a file ‘To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and autput functions on the fie. FILE “fopen{const char “filename, const char *mode); Modes to open a file A file can be opened for various intentions and some of them are ‘w open for writing (file need not exist) 2 open for appending (fle need not exist) 1+ open for reading and writing, start at beginning ‘wt - open for reading and writing {overwrite file} 2+ open for reading and writing (append if file exists) Close a file ‘To close @ function you can use the function: Int fclose(FILE “a_file); felose returns zero if the file is closed successfully. An example of fclose is: fclose(fpls me cus Aeadiny Tor Career Eancemenn] wore Focucaderayi Page tn Scanned by CamScanner

You might also like