0% found this document useful (0 votes)
1K views

BESCk104E 2023 Solved Paper (1)

2nd sem besck104 solved question paper

Uploaded by

divyanm1114
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)
1K views

BESCk104E 2023 Solved Paper (1)

2nd sem besck104 solved question paper

Uploaded by

divyanm1114
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/ 62
Gdcs Schlsile USN Ca BESCK104E/ BESCKE104 First Semester B.E./B. Tech. Degree Examination, Jan./Feb. 2023 Introduction to C Programming Time: 3 hrs. Max. Marks: 100 Note: |. Answer any FIVE full questions, choosing ONE full question from each module. 2..M: Marks , L: Bloom's level , C: Course outcomes. © scanned with OKEN Scanner ‘A computer, in simple terms, can be defined as an electronic device that is designed to accept data, perform the Fequired mathematical and logical operations at high speed, and output the result. Speed * Computers can perform millions of operations per second. + The speed of computers is usually given in nanoseconds and picoseconds, ‘Accuracy * Acomputer is a very fast, reliable, and robust electronic device. + It always gives accurate results, provided the correct data and set of instructions are input to it. ‘Automation * Computers are automatable devices that can perform a task without any user intervention. ligence Even ifa large number of executions need to be executed, each and every execution requires the same duration, and is executed with the same accuracy. Versatile * Versatilityis the quality of being flexible. computers are versatile devices as they can perform multiple tasks of different nature at the same time. Memory The internal memory of computers is very expensive and limited in size, the secondary storage is cheaper and of bigger capacity. The computer stores a large amount of data and programs in the secondary storage space. NoIa Economi © scanned with OKEN Scanner The following are the key characteris ic features of the stored program concept: Y Before any data is processed, instructions are read into memory. Vv Instructions are stored in the computer’s memory for execution. V Instructions are stored in binary form (using binary numbers—only Os and 1s). v Processing starts with the first instruction in the program, which is copied into a control unit circuit. v The control unit executes the instructions. V Instructions written by the users are performed sequentially until there is a break in the current flow. ¥ Input/Output and processing operations are performed simultaneously. © scanned with OKEN Scanner A computeris an electronic device that performs five major operations: + Accepting data or instructions (input) * Storing data + Processing data * Displaying results (output) * Controlling and coordinating all operations inside a computer Input unit — Input unit is a unit that accepts any input device. The input device is used to input data into + the computersystem. Function of input unit: o It converts inputted data into binary codes. olt sends data to main memory of computer. Central Processing Unit (CUP)— CPU is called the brain of a computer. An electronic circuitry that carries out the instruction given by a computer program. CPU can be sub classified into three parts, -Controlunit (CU) ii, Arithmetic & Logic unit (ALU) iii, Memory Unit (MU) © scanned with OKEN Scanner i. Control unit (CU)- the control unit manages the various components of the computer. It reads instructions from memory and interpretation and changes in a series of signals to activate other parts of the computer. It controls and co-ordinate is input output memory andall other units. Arithmetic & Logic unit (ALU) — The arithmetic logic u stich as +.-,*, / and logical operation such as >. <, ete. i. Memory Unit (MU)- Memory is used to store data and instructions before and after processing. Memory is also called Primary memory or intemal memory. It is used to store data temporary or permanently. Functions of CPU- It controls all the parts and software and data flow of computer. It performs all operations. It accepts data from input device, It sends information to output device. Executing programs stored in memory It stores data either temporarily or permanent basis. It performs arithmetical and logical operations. Output Unit- Output unit is a unit that constituents a number of output device. An output device is used to show the result of processing. Function of Output unit: It accepts data or information sends from main memory of computer It converts binary coded information into HLL or inputted languages. (ALU), which performs simple arithmetic operation © scanned with OKEN Scanner + Apart from being classified by generations, computers can also be categorized by their size. The size of a computer is often an indirect indication of its capabilities. ‘Supercomputers: + These are huge machines having the most powerful and fastest processors. + Ituses multiple CPUs for parallel data processing. * Speeds are measured n flops (floating-point operations per second). The fastest operates at 34 petaflops. + They are used for weather forecasting and analysis of geological data. They have enormous storage, use more power and generate a lot of heat. They are used by government agencies. Mainframes: + These are multi-user machines that support many users using the feature of time-sharing. It can run multiple programs even with a single CPU, ‘+ The processor speed is measured in MIPS (Million instructions per second). * tis used to handle data, and application related to organization and online transactions in banks, financial * institutions, and large corporation © scanned with OKEN Scanner Minicomputers/Midrange computers: + Itwas introduced by DEC (Digital Equipment Corporation). + They can serve hundreds of users and are small enough to partiallyoccupy a room. They are used in smaller organizationsor a department of a large one. + They are not affordable to be used at the home. Microcomputers: + The microcomputer or PC is introduced by Apple and endorsed by IBM. This is a single-user machine powered by a single-chip microprocessor. They are very powerful machines having gigabytes of memory. + They are both used in standalone mode and in a network. + Amicrocomputer takes the form of a desktop, notebook (laptop), or netbook (smaller laptop). PCs todayare powered by 3 types of OS~ windows (7, 8, of 10), Mac OSX (Apple), and Linux. They are used for engineeringand scientific applications and for software development. ‘Smartphones and Embedded Computers: + The smartphone is a general-purpose computer i.e., capable of making phone calls. It has a powerful processor, with multiple cores, supports GBs of memory, and runs a developed OS (Android or iOS). + Itcan be operated with a keyboard, touch, or stylus. + Embedded Computers or micro-controllersare very small circuits containinga CPU, non-volatile memory, and input andoutput + handlingfacilities. + They are embedded into many machines that we use — cars, washing machines, cameras, ete, The processor here runs single unmodifiable program stored in memory. © scanned with OKEN Scanner Formatted Input It refers to an input data that has been arranged in particular format Syntax: scanf(‘control string’, argt,arg2,-. arg n); Control string: field format in which data is entered ‘Argi,arg2: address of the location where data is stored Example: scanf("%d %d", &@, &b); FORMATTED OUTPUT The printf function is used for printing the captions and results. Syntax: printf(‘control string’, arg1, arg2, -... argn); Control string contains three types of items. 1. Characters that will be printed on the screen as they ap} 2. Format specifications that define the output format for display of each item. 3. Escape sequence characters such as \n, \t and \b. Examplewith format specifier %d: 10, b=77; printi(‘%d 9d”, a , b); Output: 1077 © scanned with OKEN Scanner Unformatted Input getchar(): Reading a single character can be done by using the function getchar and it does not have any parameter. + Syntax: variable_name= getchar( ); + Where, variable_nameis valid and has been declared in char type. Example: char name; name = getchar( ); gets(}: Alternative method to read strings is gets) (read it as get string}function whichis an unformatted string input function, Advantage of gets(Jis it can read multi-word strings. + Example:char name(10}; + Writing single character can be done by using the function putchai + Syntax: putchar(variable_name); + Example:name='y'; + putchar(name); + Will displaythe charactery on the screen puts():This function can be used to display entire string on monitor screen without the help of %sspecifier. + Example: char name] = “Bengaluru” + puts(name); ‘+ puts{ ) will display the string value stored in parameter passed to it on monitor. In this case it is— Bengaluru. © scanned with OKEN Scanner C program consists of different sections. The structure of C program is as shown below. + Documentation Section: It consists of a set of comment line giving the name of the program, the author and other details. Compilerignores these comments. There are two formats: 8) Line comments //Single line comment b) Block comments /*Multi line comment*/ + Link Section: It provides instruction to the compilerto link functions from system library. + Definition Section: It defines all symbolic constants, + Global Declaration Section: The variables which are used in more than one function are called global variables and are declared in this section. + main() Section: Every ‘C’ program has one main( ) function and it contains two parts: i. Declaration Part: Here, all the variables used are declared. ji, Executable Part: Here, it contains at least one executable statement. The main( ) function is enclosed within flower brackets and the statements ends with semicolon. + Sub-program Section: It contains all the user defined functions that are called by main( ) function. © scanned with OKEN Scanner ‘STRUCTURE OF ‘C’ PROGRAM Documentation section Link section Definition section Global declaration section main( ) Section { Declaration part Executable part } Sub program section Function 1 Function 2 Function n Example //Addition of two numbers Hinclude void main( ) { int a, b, sum; printf(“Enter two numbers\n”); scanf("%d%d", &a, &b); sum =a+b; printf(“The sum is %d”, sum); } © scanned with OKEN Scanner + The conditional operator or Ternary operator (? :) is just like an if-else statement that can be within expressions. Such an operatoris useful in situations in which there are two or more alternatives for an expression. + The syntaxof the conditional operatoris exp1 ? exp2 : exp3 + Where, + Expression1 : Condition + Expression2 : Statement followed if conditionis true Expression3 Statement followed if conditionis false + Exclarge = (a> 2) 24: 2~large = 4 To find largest of 3 numbers using conditional operator ftincludecstdio.h> int main() { int num1,num2,num3,large; printf(“Enter 3 numbers \n "}; scanf(“%éd %d %d", &num’,&num2,&num3); large=num>num2?(num1>num3?numi:num3):(aum2>num3?num2:num3); printf("the largest number is:%d”, large); return 0; i © scanned with OKEN Scanner TYPE CONVERSION AND TYPE CASTING + Type conversion and type casting of variables refers to changing a variable of one data type into another. + While type conversion is done implicitly. casting has to be done explicitly by the programmer. ‘Type conversionis done when the expression has variables of different data types. So to evaluate the expression, the data type is promoted from lower to higher level where the hierarchy of data types can be given as: double, float, long, int, short and char. For example, type conversion is automatically done when ‘we assign an integer value to a floating point variable. For ex: float x; inty= x Now, x = 3.0, Type casting is also known as forced conversion. It is done when the value of a + higher data type has to be converted in to the value of a lower data type. For example, we need to explicitly type cast an integer variable into a floating point variable. + Typecasting can be done by placing the destination data type in parentheses followed by the variable name that haas to be converted. + When floating point numbers are converted to integers, the digits after the decimal are truncated. + Typecasting is done to make a variable one data type to act like a variable of another type. + Examples: res = (int) 9.5; 9.5 is converted to 9 by truncation and then assigned to res. (int) 12.3 / (int) 4.2 It is evaluated as 12/4 and the value 3 is assigned to res. res © scanned with OKEN Scanner The ‘switch’ statement is @ control statement used to make a select one alternative among several alternatives. Itis a ‘multi-way decision statement’ that tests whether an expression matches one of the case values and branches accordingly. Here switch, case, break and default are built-in C language words. +f the choice matches to label! then block! will be executed else if it evaluates to label2 then block2 will be executed and so on. +f choice does not matches with any case labels, then default block will be executed Syntax for switch ease Switeh(ehoiee) t cease label: cease label2: 1 de. cease label3: Deft Hock break: deft default-block: break: 7 : Revie © scanned with OKEN Scanner Example: #include void main() { char Operator; float num1, num2, result = 0; printf("Enter an Operator (+, -, *, /) :\n"); scanf("9c", &Operator); printf("Enter the Values for two Operands: numt and num? : \n*); scanf("%f%f", &num1, &num2); switch(Operator) { case '+'; result = num1 + num2; break; case: result = numt - num2; break; result = num * num2; break; case’: result=num1 / num2; break; default: printi("In You have entered an Invalid Operator % } printf("\1n The result of %f %c %f = %F", num1, Operator, num2, result); } © scanned with OKEN Scanner \cludecstdio.h> int main( ) { int num,rem,revitemp; printf("Enter a positive integer number:\n" scanf{"9%d", &num); rev=0; temp=num; while(num!=0) { rem=num%10; num=num/10; rev=rem+(rev*10); } if{temp==rev) printf("The given number %d is palindrome", temp); else printf("The given number %d is not a palindrome", temp); } © scanned with OKEN Scanner The ‘switch’ statement is @ control statement used to make a select one alternative among several alternatives. Itis a ‘multi-way decision statement’ that tests whether an expression matches one of the case values and branches accordingly. Here switch, case, break and default are built-in C language words. +f the choice matches to label! then block! will be executed else if it evaluates to label2 then block2 will be executed and so on. +f choice does not matches with any case labels, then default block will be executed Syntax for switch ease Swithehoiee) t cease label: cease label2: 1 dee. cease label3: ete Mock break default defaul-block: break: 7 : Neri © scanned with OKEN Scanner Example: #include void main() { char Operator; float num1, num2, result = 0; printf("Enter an Operator (+, -, *, /):\n"); scanf("9c", &Operator); printf("Enter the Values for two Operands: numt and num? : \n*); scanf("%f%f", &num1, &num2); switch(Operator) { case '+'; result = num1 + num2; break; case: result = numt - num2; break; result = num * num2; break; case’: result=num1 / num2; break; default: printi("In You have entered an Invalid Operator % } printf("\1n The result of %f %c %f = %F", num1, Operator, num2, result); } © scanned with OKEN Scanner \cludecstdio.h> int main( ) { int num,rem,revitemp; printf("Enter a positive integer number:\n" scanf("9%d", &num); rev=0; temp=num; while(num!=0) { rem=num%10; num=num/10; rev=rem+(rev*10); } if{temp==rev) printf("The given number %d is palindrome”, temp); else printf("The given number %d is not a palindrome", temp); } © scanned with OKEN Scanner for loop: + Itis a pretest loop and also known as entry controlled loop. + “for” keyword is used here. * Here, the head of the for loop containsall the three components that is initialization, condition and Updation. General synta for (initialization; test-conditio { Statement block; } Statement y; increment/decrement) The execution of for statement is as follows. 1. First the control variable will be initialized. (Example i=1) 2. Next the value of control variable is tested using test condition. (ic=n) 3. If the condition is true the body of the loop is executed else terminated. 4. If loop is executed then control variable will be updated (i++) then, the condition is checked again. #include int main() i intnt=0,n2=1 number; printf‘Enter the number of elements’); scanf(‘%d", &number); printf(" %d %d", n1,n2); for(i=2;i Storage: memory. > Default initial value: garbage value, local to the block in which the variable is defined. > Life: tll the control remains within the block in which the variable is defined. A program to illustrate the use of auto. nclude i “0 register Storage: CPU Register. ( > Default initial value: garbage value. % Scope: local to the block in which the variable is defined. 7 a guce int <3) Life: tll the control remains within the block in which the variable is defined. printf ("\ntd", 1); A program to illustrate the use of register. , Winclude prints ("8d") 20; void main() ) t printe ("tas iy int iy , pice10; i++) er uetr output: ) yn 4 © scanned with OKEN Scanner static > Storage: memory. > Default initial value: 2er0, Scope: local to the block in which the variable is defined. > Life: value of the variable persists between different function calls. > The different Ww two programs Ist auto and 2nd static storage class for variable “i the scope of auto and static both use local to the block in which the variable is declared. > Those program consists two functions main () ana increment ( ). The increment () function called from main () function for three times. > Each time increment the value of and print. > When variable “is auto each time increment and re-intislized to 1. extern A Program example to illustrate the use of exter. Storage: memory. > Default initial value: zero, da > Scope: plat. Iipetudeetdion> Life: as long asthe program's exccution doesn’t come to an end. The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else. The extern declaration docs not allocate storage for variables © scanned with OKEN Scanner ‘Sumas: —data_ype array namefarray Examples: int marks{4]; Sloat temperature S]: Note: Declaration specifies the datatype of aray, its name and size. Example: printf("Enter4 marks”); Initialization of One-Dimensional Array: After array is declared, next is storing valves in to am array is called initialization, There are two types of array initialization: 4; i++) 1. Compile-time initialization scanf(" Sd”, &marks[i); Run-time initialization } lization: If we assign values tothe array during declaration itis called sompile e can initialize values to all the elements of the array. Syntax: data_type array_namelarray_sizel=|listof values); 95,35, 67, 87} b) Ini ion without size: We needn't have to specify the size of array provided we are initializing the values in beginningitself. Syntax: data_type array_name| ]=(list of values); 95,35, 67, 87}; Run time initialization: Run time initialization is storing values in an array when program is. running or executing. © scanned with OKEN Scanner Hinclude int main() { lot af]. search, |, nz printd["Enter number of elements in array\n"k scanf("%d", Bn; printt("Eriter ted integer(s}\n", a): for (| = O:b< nzite) sanf("d", Barraytch: printf{("Enter 2 number to search\n"}; scanf("%d", Baearch); for (( © O:b int main() t char str[100], lower_str [100]; int izo, 520; Printf("\n Enter the string : gets(str); while(str[i] 1= ‘\o'y { 3 if(str[i]>="a' a& str[i]<='2") lower_str[j] = str[i] + 32; Ise lower_str[j] = str[i]; itt; j44; } lower_str[j] = ‘\o'; Printf("\n The string converted into lower case is : "); puts(lower_str); return 0; } Output Enter the string : HeLLo The string converted into lower case is: hello © scanned with OKEN Scanner G863 STEM USN | BESCK104E/ BESCK E104 First Semester B.E./B.Tech. Degree Examination, Jan/Feb, 2023 Introduction to C Programming Time: 3 hrs. Max. Marks: 100 Note: |. Answer any FIVE fuel! questions, choosing ONE fiall question from cack module. 2M: Marks, f Bloom's level .C: Course owtcomes, © scanned with OKEN Scanner The following are the key characteristic features of the stored program concept: Y Before any data is processed, instructions are read into memory, ¥ Instructions are stored in the computer's memory for execution, ¥ Instructions are stored in binary form (using binary numbers —only Os and 1s). v Processing starts with the first instruction in the program, which is copied into a control unit circuit. ¥ The control unit executes the instructions. ¥ Instructions written by the users are performed sequentially until there is a break in the current flow. ¥ Input/Output and processing operations are performed simultaneously. © scanned with OKEN Scanner Formatted |nput It refers to an input data that has been arranged in particular format Syntax: scanf(‘control string’, arg,arg2,-. arg n); Control string: field format in which data is entered ‘Arg1,arg2: address of the location where data is stored Example: scanf("%d %d", &@, &b); FORMATTED OUTPUT The printf function is used for printing the captions and results. ‘Syntax: print{(‘control string’, arg1, arg2, -... argn); Control string contains three types of items: 1. Characters that will be printed on the screen as they ap} 2. Format specifications that define the output format for display of each item. 3. Escape sequence characters such as \n, \t and \b, Examplewith format specifier %d: 10, b=77; printi(‘%d 9d”, a , b); Output: © scanned with OKEN Scanner Unformatted Input getchar(): Reading a single character can be done by using the function getchar and it does not have any parameter. + Syntax: variable_name= getchar(); + Where, variable_nameis valid and has been declared in char type. Example: char name; name = getchar( ); gets(}: Alternative method to read strings is gets) (read it as get string}function whichis an unformatted string input function, Advantage of gets(Jis it can read multi-word strings. + Example:char name[10); + Writing single character can be done by using the function putchai + Syntax: putchar(variable_name); + Example:name='y'; + putcharname); + Willdisplaythe charactery on the screen puts():This function can be used to display entire string on monitor screen without the help of %sspecifier. + Example: char name{]] = “Bengaluru” + puts(name); ‘+ puts{ ) will display the string value stored in parameter passed to it on monitor. In this case it is— Bengaluru. © scanned with OKEN Scanner C program consists of different sections. The structure of C program is as shown below. + Documentation Section: It consists of a set of comment line giving the name of the program, the author and other details. Compilerignores these comments. There are two formats: 8) Line comments //Single line comment b) Block comments /*Multi line comment*/ + Link Section: It provides instruction to the compilerto link functions from system library. + Definition Section: It defines all symbolic constants, + Global Declaration Section: The variables which are used in more than one function are called global variables and are declared in this section. + main() Section: Every ‘C’ program has one main( ) function and it contains two parts: i. Declaration Part: Here, all the variables used are declared. ji, Executable Part: Here, it contains at least one executable statement. The main( ) function is enclosed within flower brackets and the statements ends with semicolon. + Sub-program Section: It contains all the user defined functions that are called by main( ) function. © scanned with OKEN Scanner ‘STRUCTURE OF ‘C’ PROGRAM Documentation section Link section Definition section Global declaration section main( ) Section { Declaration part Executable part } Sub program section Function 1 Function 2 Function n Example //Addition of two numbers Hinclude void main( ) { int a, b, sum; printf(“Enter two numbers\n”); scanf("%d%d", &a, &b); sum =a+b; printf(“The sum is %d”, sum); } © scanned with OKEN Scanner + The conditional operator or Ternary operator (? :) is just like an if-else statement that can be within expressions. Such an operatoris useful in situations in which there are two or more alternatives or an expression. + The syntaxof the conditional operatoris expt ? exp2 : exp3 + Where, + Expression2 : Statement followed if conditions true Expression3 :Statement followed if conditionis false + Exclange =(4> 2) 24: 2->large= 4 To find largest of 3 numbers using conditional operator Hincludecstdio.h> int main() { int numi,num2,num3,large; print{("Enter 3 numbers \n”); scanf("Shd %d %d", &numi,&num2,&num: large=num1>num2?(num1>num3?num1:num3):(num2>num3?num2:num3); printf("the largest number is:%d”, large); return 0; ) © scanned with OKEN Scanner TYPE CONVERSION A TYPE CASTID + Type conversion and type casting of variables refers to changing a variable of one data type into another. + While type conversion is done implicitly, casting has to be done explicitly by the programmer. ‘Type conversionis done when the expression has variables of different data types. So to evaluate the expression, the data type is promoted from lower to higher level where the hierarchy of data types can be given as: double, float, long, int, short and char. For example, type conversion is automatically done when ‘we assign an integer value to a floating point variable, For ex: float x; inty=3; xy; Now, x = 3.0, Type casting is also known as forced conversion. It is done when the value of a + higher data type has to be converted in to the value of a lower data type. For example, we need to explicitly type cast an integer variable into a floating point variable. float salary = 1000.00; it sal = (int) salary; + Typecasting can be done by placing the destination data type in parentheses followed by the variable name that has to be converted. + When floating point numbers are converted to integers, the digits after the decimal are truncated. + Typecasting is done to make a variable one data type to act like a variable of another type. + Examples: res = (int) 9.5 : 9.5 is converted to 9 by truncation and then assigned to res. res = (int) 12.3 /(int) 4.2 Itis evaluated as 12/4 and the value assigned to res. © scanned with OKEN Scanner The ‘switch’ statement is a control statement used to make a select one alternative among several alternatives. {tis a *multi-way decision statement’ that tests whether an expression matches one of the case values and branches accordingly. Here switch, case, break and default are built-in C language words. +If the choice matches to label! then block1 will be executed else if it evaluates to label2 then block2 will be ‘executed and so on. *If choice does not matches with any case labels, then default block will be executed Syntax for switch case Seite ehoice) t cease labell: —_blockt: break: cmelabel2: Hk ] tres sin cmselabels: block [ati treks ; deta: deta Mocks trea © scanned with OKEN Scanner Example: Hinclude void main() { char Operator; float numt, num2, result = 0; printf("Enter an Operator (+, scanf("%c", &Operator); printf("Enter the Values for two Operands: numt and num2 : \n"); scanf(%f%6", &num1, &num2); switch(Operator) { case ‘+: result = num1 + num2; break; case: result = numt - num2; break; result = num * num2; break; “Dany; case case’: result = numt / num2; break; default: printi("n You have entered an Invalid Operator % } printf("\n The result of 94f %e %f = %F, num, Operator, num2, result); } © scanned with OKEN Scanner while do... while Itis a pre-test loop. It is a post-test loop. Tris an entry controlled loop. Tris an exit controlled loop. The condition is at top. The condition is at bottom. There is no semi colon at the end of while. The semi colon is compulsory at the end of while Tris pised when condition is important Tris used when process is important. Here, the body of loop gets executed ifand only if condition is true. Here, the body of loop gets executed atleast once even if condition is false. SYNTAX. FLOWCHART. EXAMPLE (Same as in explanation) SYNTAX. FLOWCHART. EXAMPLE (Same as in explanation) © scanned with OKEN Scanner Hincludecstdio.h> int main( ) it int num,rem,revtemp; printf("Entera positive integer number:\n" scani("%d", &num); while(num!=0) { rem=num%10; num=num/10; revsrem+(rev"10}; ) ifftemp==rev) printf("The given number %d is palindrome”, temp); else printf("The given number %d is not a palindrome”, temp); © scanned with OKEN Scanner forloop: + [tis a pretest loop and also known as entry controlled loop. + “for” keyword is used here. + Here, the head of the for loop containsall the three components that is initialization, condition and Updation. General syntay for (initialization; test-conditio { Statement block; } Statement y; jincrement/decrement) The execution of for statement is as follows. 1. First the control variable will be ed. (Example i=1) 2. Next the value of control variable is tested using test condition. (ic=n) 3. If the condition is true the body of the loop is executed else terminated. 4. If loop is executed then control variable will be updated (i++) then, the condition is checked again. sinclude int main() { int n1=0,n2=1,,number, printf(‘Enter the number of elements” scanf("%d", &number); printf" %d %d", n1,n2); for(i=2;i void saint register auto int tet; > Storage: CPU Register. t > Default initial value: garbage valve. pocolio® ize % Scope: local to the block in which the variable is defined. vy . . eutouiat 1-3) > Life: tll the control remains within the block in which the variable is defined. printf (™\ntd", 105 A program to illustrate the use of register. Hinclude printe("ad™, £07 void main() ) ( peinte(™td", £7 register int 4: , for (i= Goes , Prise a © scanned with OKEN Scanner > Storage: memory. > Defaul inital valve: zero. > Scope: local to the block in which the variable is defined. > Life: value ofthe variable persists between different function calls. > The different tvw two programs Ist auto and 2nd static storage class for variable “i? the scope of auto and static both use local to the block in which the variable declared. Those program consists two functions main () ana werement () The increment ( ) function called from main () function for three times, Each time increment the value of and print When variable ‘i is auto each time inerement and re-intialized to 1. extern A Program example to illustrate the use of extern, Storage: memory. 1 Defauke initial value: ze, —- > Scope: slob inctudestdion> Life: as long asthe program's exccution doesn’t come Wo an end. nth: 7 The extern keyword is used before a variable to inform the compiler that this variable void increment0: is declared somewbere che, The exter declaration does not allocate sorage for void main variables ‘ print; incremert0: increment: © scanned with OKEN Scanner Smumz—_dava_pe arm. mamefornay ste]: Examples int mais: oat tempore as ° Run time initializtaion “Nite Decantion specifies he data ype of ray, is nae ad size Dl At declare socs orks Initialization of One-Dimensional Array; Afr aray is declare, next is storing vals in to an sray is <6; called intialization. Thee are two types of ery intaizaton: we 0; ica i++) 1, Compitetineinisization scant(" a", &mark 2. Run-time initialization ) 1. Compite time initialization we assign valu tothe array during declaration itis called sompile 4a) Initialization with size: we can initialize values to all the elements of the array. Syntax: data_typearray_namelarray_size]={list of values); int marks{4]={ 95,35, 67, 87); b) Initialization without size: We needn't have to specify the size of array provided we are the valuesin beginning itself. ‘Syntax: data_typearray_name| }=(list of values}; Examples: int marks{ ]=( 95,35, 67, 87); Run time initialization: Run time initializationis storing values in an array when program is running or executing. © scanned with OKEN Scanner include int main() { inta[S}, search, i, n; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter %d integer(s)\n", n); for (i= O;i int main() { int a[3}{3}, b(3)(3], result(3)(3]; 11 Taking input using nested for loop printf("Enter elements of 1st matrix\n"); for (inti 3 +i) for (int j= 0; j< 3; +4)) { scanf{"%d", &afilU); ) J Taking input using nested for loop printf("Enter elements of 2nd matrix\n"); for (inti = 0; 1 <3; ++i) for (int j = 0; <3; +4)) { scanf("%d", &bfi}U}): ) // adding corresponding elements of two matrices for (int for (int { result(il) ) // Displayingthe sum printf("Sum Of Matrix: 0; 1<3; ++i) 1 <3; +44) MiG) + DEG): for (int y <3; ++i) 1; §< 3; +4)) printf("%d\t", result(i))); ) printf("\n"); } return 0; © scanned with OKEN Scanner A string is a collection of characters enclosed within the double quotes. A string is a null-terminated character array. This means that after the last character, a null character (‘\0’) is stored to signify the end of the character array. If we declare a string by writing char str{100}; Then str can be read from the user by using three ways use scanf function using gets() function using getchar{) function repeatedly The string can be read using scanf() by writing scant("%s", str); The string can be read by writing gets(ste); gets) takes the starting address of the string which will hold the input. The str automatically terminated with a null character. inputted using gets) is © scanned with OKEN Scanner The string can also be read by calling the getchar() repeatedly to read a sequence of single characters (unless a terminating characteris entered) and simultaneously storing it in a character array. chegetchar(); // get a character while(ch t= ‘*") { ste] = ch; //store the read character in str ; //get another character ) Stefi] ="\O';_// terminate str with null character © scanned with OKEN Scanner #include int main( ) { char str[] = "Programming is fun"; inti; while(str[i]!= '\O') i++; printf("Length of the string: %d", i); return 0; } OUTPUT: Length of the string: 18 © scanned with OKEN Scanner Sprintf() Function The Library function sprintf( ) is similar to printf(). The only difference is that the formatted output is written to a memory area rather than directly to a standard output(screen). Syntax of sprintf( ) is int sprintf(char *buffer, const char *format[,argument,...]); Ex: sprintf(buf, “num=%3d”,num); Sscanf( ) Function The sscanf() function accepts a string from which to read input. It accepts a template string and a series of related arguments. The sscanf{() is similar to scanf function except that the first argument of sscanf specifies a string from which to read, whereas scanf can only read from standard input. Syntax: sscanf(const char *str, const char *format,[p1,p2,...]); Ex: sscanf(str, “%d”, &num); Similar to scanf( ), sscanf( ) terminates as soon as it encounters a space. © scanned with OKEN Scanner #include { include if(atj)>atje1}) void main() { { int a[50},i,j,temp,n; /* Declaration of the variables*/ printf("Enter the value of n\n"); scanf("s6d",&n); /* Read the size of an array */ printf("Enter the array elements\n"); } forli=O;icn;i++) } scanf("%d",&ali)); /* Read the elements */ printf("\nThe array after sorting\n"); /* Display the printf("The given array elements are \n"); array after sorting */ forli=0;icn;i++) forli=O;icn;i++) printf("9%d\t",ali)); printf("%d\t",ali)); } /* Perform Bubble Sort */ for(i: i++) { for(j=0;jcn-i;j++) © scanned with OKEN Scanner A function calling itself repeatedly is called Recursion. 0 All recursive functions have two elements each call either solves one part of the problem or it reduces the size of the problem. 0 The statement that solves the problem is known as base case. 0 The rest of the function is known as general case. Minclude Ant Fact(int); int main() t int num, factorial; printf("\n Enter the number: scanf("xd", &num); factorial = Fact(num); printf("\n Factorial of Xd = Xd", num, factorial); return 0; int Fact(int n) return 1; else return (n * Fact(n-1)); @ scanned with OKEN Scanner Function isalnum(int c) | ‘isalpha(int c) | isentri(int c) isdigit(int ¢) isgraph() isprint(int c) [ee (Checks whether character ¢ is ‘an alphanumeric character Checks whether character ¢ is! isalpha("2"); an alphabetic character ample isalpha(’A'}: islower(int c) | isuppertint ¢) Checks whether character cis scanf(“sed", | | iSpunctfint c) a control character (Checks whether character € isadigit Checks whether character © isa graphic or printing ‘character. The function ‘excludes the white space character (Checks whether character € isa printing character. The function includes the white ‘space character ‘&c);iscntri(c); isdligit(3); | | isspace(int c) isgraph“l'); | | isxdigit(int c) ‘Checks whether the character cis in lower case ‘Checks whether the character cis in upper case ‘Checks whether the character is a punctuation mark Checks whether the character cis a white space character ‘Checks whether the character cis a hexadecimal digit Converts the character ¢ to lower case ‘Converts the character ¢ to upper case EXPLAIN ANY 5 FROM THE GIVEN LIST OF FUNCTIONS istower('k’ isupper("K’); ispunct(’?); isspace(’ *); isxdigit(F); tolower(‘K") returns k tolower(‘k’) retums K © scanned with OKEN Scanner Streat Fun Syntax: char *strcat( char *str1,const char str2); The strcat function appends the string pointed to by str2, to the end of the string pointed to by str1.The process stops when the terminating null character of str2 is copied sinclude sinclude Ant main() ( char ste1{50] = “Programming char stra{] * “In C7; streat(stri, stra} printf("\n Stet: XS", stra); return 0; ) Output sted: Programming In C Strncat Function Syntax: char *strncat( char *str1,const char str2, size_t n); This function appends the string pointed to by str2 to the end of the string pointed to by str1 upto n characters jong. Copying stops when n characters are copied or the terminating null character of str2 is copied. include Hinclude int main() { char str1(50) = "Programming char str2{] = "In C5 strncat(str2, str2, 2); print#("\n stra: Xs", stea} return 0; Programming In @ scanned with OKEN Scanner Ss any 4 siring manipul 10) 12) Cos Strlen Function Strepy Function Syntax: size_t strlen(const char *str); Syntax: char *strcpy(char *str1, const char *str2); This function calculates the length of the string str This function copies the string pointed to by str2 to up to but not including the null character, i.e., the _ str1 including the null character of str2. It returns function returns the number of characters inthe the argument str1. Here str1 should be big enough string. to store the contents of str2. (© Scanned with OKEN Scanner + Generally, the computer has three areas of memory + each of which is used for a specific task. These areas of, memory include- stack, heap and global memory. © Stack- A fixed size of stack is allocated by the system and isfilled as needed from the bottom to the top, one element at a time. These elements can be removed from the top to the bottom by removing one element at a time. Thats, the last element added to the stack is removed first. . + Heap- Heap is a contiguous block of memory that is available for use by the program when need arise. A fixed size heap is allocated by the system and is used by* the system in a random fashion. ‘© When the program requests a block of memory, the dynamic allocation technique carves out a block fromthe * heap and assigns it to the program. . ‘© When the program has finished using that block, it returns that memory block to the heap and the location of the memory locationsin that block is added to the free list. ‘© Global Memory- The block of code that is the main() program (along with other functions in the program) is stored in the global memory. The memory in the global area is allocated randomly to store the code of different functions in the program in such a way that ‘one function is not contiguous to another function. Besides, the function code, all global variables declared in the pro Other Memory Layouts- C provides some more memory areas like- text segment, BSS and shared library segment. © The text segment is used to store the machine instructions corresponding to the compiled program. This is generally a read-only memory segment BSS is used to store un-initialized global variables «© Shared libraries segment containsthe executable image of shared libraries that are being used by the program. gram are stored in the global memory area. © scanned with OKEN Scanner Applications © Apointeris a variable that containsthe memory location of another variable. DECLARING POINTER VARIABLES ¢ The general syntax of declaring pointer ariableis data_type *ptr_name; Here, data_typeis the data type of the value that the pointer will point to. For example: int *pnum; char *pch; float *pfnum; 10; int *ptr = &x; The" informs the compiler that ptr is a pointer variable and the int specifies that it will store the address of an integer variable. The & operatorretrieves the Ivalue (address) of x, and copies that to the contents of the pointer ptr. int: To pass information back and forth. To return multiple data items. To access individual elementsin alternative way To pass arrays and strings Enable references to functions To create complex data structures For dynamic memory allocation © scanned with OKEN Scanner Structure is a userdefined data type that can store related information of different data types together. After defining a structure format we can declare _ variable for that type. It includes the following elements: i.Keyword struct ii, A structure or tagname ili, List of variables separated by comma iv. Terminating semicolon Syntax: struct structurename list_of_variables; Example: struct bookbank book1, book2; struct student s1, s2; Syntax of structure variable declaration struct tagname { datatype member 1; datatype member 2; datatype member n; i struct structurename of_variables; Structure to store book information struct bookbank { char author[50]; char title[SO}; int year; float price; ‘ struct bookbank book1, book2; © scanned with OKEN Scanner Initialization of structures Syntax: struct struct_name data-type member_1; data-type member_2; data-type member_n; } Struct struct_name struct_var={ constant], constant2. Example struct student int r_no; char name[20]; char course[20]; float fees; } struct student stud1={01,"Rahul”, “BCA”, 45000}; © scanned with OKEN Scanner

You might also like