[go: up one dir, main page]

0% found this document useful (0 votes)
19 views47 pages

BCA-PROGRAMMING IN C

An algorithm is a step-by-step procedure for performing a specific task, characterized by clarity, finite steps, and well-defined inputs and outputs. Algorithms can be classified into simple, conditional, and iterative types, and can be represented using pseudocode or flowcharts for better understanding. Additionally, programming languages are categorized into generations based on their abstraction level, with C being a prominent procedural language that supports modularity and is widely used despite the emergence of newer languages.

Uploaded by

saidheeraj668
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)
19 views47 pages

BCA-PROGRAMMING IN C

An algorithm is a step-by-step procedure for performing a specific task, characterized by clarity, finite steps, and well-defined inputs and outputs. Algorithms can be classified into simple, conditional, and iterative types, and can be represented using pseudocode or flowcharts for better understanding. Additionally, programming languages are categorized into generations based on their abstraction level, with C being a prominent procedural language that supports modularity and is widely used despite the emergence of newer languages.

Uploaded by

saidheeraj668
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/ 47
Algorithm: > An algorithm is a step-by-step procedure to perform a specific task > An algorithm is a sequence of instructions to accomplish a particular task is called as an algorithm > It consist several keywords ‘START,STOP,READ, PRINT, IF, THEN, ELSE,GOTOetc., Properties: > It must be simple and clear to understand > It must ensure about the results > It must be identify the number of steps > So that it can be complete within finite number of steps ® syntax: STEP1: START STEP2: — READ.......THENUMBERS STEP3: — PROCESSORFORMULA.......FINDTHESUM STEP4 : PRINT ..... DISPLAY THE RESULTS OR SUM STEPS : sToP Algorithms are classified into 3 types 1. Simple algorithms 2. Conditional algorithms v 3. Iterative or looping algorithms 1. Simple algorithms: > Analgorithm contains simple mathematical operations ie It does not contains any conditions,loops Ex: write an algorithm to find the simple interest STEP1: START ‘STEP2: READP,T,R STEPS: STOP 2. Conditional algorithms: > An algorithm contains conditions to execute only one particular statement > Ituses IF,THEN,ENDIF,ELSE etc., Ex: write an algorithm to check whether the result is pass or fail STEP2: READ marks ‘STEP3:IF marks>=35THEN ———_C-languageforlISem.B.C.A-HONOURS-2024-2025 ____ PRINT“resultispass” ELSE PRINT“resultisfail” END IF; ‘STEP4:STOP 3. Iterative algorithms: Ex: write an algorithm to print 1 to 10 numbers STEP1: START STEP2:READ i: StepS:lF i<=10 THEN GOTO STEP 3 END IF; STEPG: STOP Characteristics/Features of an Algorithm: * Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps should be clear in all aspects and must lead to only one meaning + Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs. It may or may not take input. + Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-defined as well. It should produce at least 1 output. + Finite-ness: The algorithm must be finite, ie. it should terminate after a finite time. + Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with the available resources. It must not contain some future technology or anything. + Language Independent: The Algorithm designed must be language-independent, i.e. it must be just plain instructions that can be implemented in any language, and yet the output will be the same, as expected, ‘+ Input: An algorithm has zero or more inputs. Each that contains a fundamental operator must accept zero or more inputs. = Output: An algorithm produces at least one output. Every instruction that contains a fundamental operator must accept zero or more inputs. + Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to interpret. By referring to any of the instructions in an algorithm one can clearly understand what is to be done. Every fundamental operator in instruction must be defined without any ambiguity. + Finiteness: An algorithm must terminate after a finite number of steps in all test cases. Every instruction which contains a fundamental operator must be terminated within a finite amount of ite loops or recursive functions without base conditions do not possess finiteness. ness: An algorithm must be developed by using very basic, simple, and feasible operations so that one can trace it out by using just paper and pencil. What is Pseudo Codi + APseudocode is defined as a step-by-step description of an algorithm. * Pseudocode does not use any programming language in its representation instead it uses the simple English language text as it is intended for human understanding rather than machine —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ reading ‘+ Pseudocode is the intermediate state between an idea and its implementation(code) in a high-level language. [ Algorithm LW Pseudocode }|——+} Program Example1: Factorial of a Given Number. Start program Declare fact and n Enter number for n fori=1 toi Perform fact = fact * Display fact End program Example2: Find the Sum of Natural Numbers Start program Declare variables n, sum = 0 andi Enter the number forn For i=1 to i<=n Perform operation sum = sum +i Increment i value by one Print sum End program Flowcharts: > Thegraphicalrepresentationofanalgorithmiscalledasflowchart » Whichisusedtoeasilyunderstandtheflowofthedata > Itconsistsseveralsymbols Name symbol Purpose Oval 25 Start/stoporbegin/end Parallagram Read/writeor input/output Rectangle Processorformula Diamond Decisionmaking conditions Arrow Flowofthe data Examples on flowchart: a)Addition oftwo numbers b)Finding Biggest number Inputa Input AB Inpute Sum=A+b Lan 7 Pseudo code: * Itis a form of a structure English that describes algorithms. tt facilitates designer to focus on the logic of the algorithm without getting the details of a language syntax. ‘* Itis a compact and informal highlevel description of an algorithm that uses the structural convections of a programming language. ‘© Pseudo codes are an outline of a programme that can easily convert into programming statements. ‘*) It’smain purpose Is toenhancehuman understandability of the solution. Keywords are used while writing pseudocodes: Examples 1) if condition 2)whilestatement ‘3)casestatement If condition then while condition case expression of Sequence 1 sequence condition1:sequence1; Else end while condition2:sequence2 Sequence 2 others : Endif defaultseqeuence Endcase —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ 4}for statement Foriterationbounds Sequence end for Examples for pseudocode Addition of two numbers Read the value(1)and store into A. Readthevalue (2) and storeintoB. finding biggest number Read the first value into A. Read the second value into B. Calculate sum=A+B, ifA>B print sum, Print end. Elseif AcB PrintB Else Print“Bothareequal”; Endif Endif End Generation of Programming Languages: Programming Languaes a Low Level High Level a ~ a First Second Third Fourth Fifth Generation Generation Generation Generation Generation 1, First-Generation Language : The first-generation languages are also called machine languages/ 1G language. This language is machine-dependent. The machine language statements are written in binary code (0/1 form) because the computer can understand only binary language. Advantages : 1. Fast & efficient as statements are directly written in binary language. 2. No translator is required. Disadvantages : 1. Difficult to learn binary codes. 2. Difficult to understand — both programs & where the error occurred 2. Second Generation Language : The second-generation languages are also called assembler languages/ 2G languages. Assembly language contains human-readable notations that can be further converted to machine language using an assembler. Assembler ~ converts assembly level instructions to machine-level instructions. Programmers can write the code using symbolic instruction codes that are meaningful abbreviations of mnemonics. It is also known as low-level language. ———_C-languageforlISem.B.C.A-HONOURS-2024-2025 ____ Advantages : 1 It is easier to understand if compared to machine language. 2. Modifications are easy. 3. Correction & location of errors are easy. \dvantages : 1. Assembler is required. 2. This language is architecture /machine-dependent, with a different instruction set for different machines. 3. Third-Generation Language : * The third generation is also called procedural language /3 GL. * It consists of the use of a series of English-like words that humans can understand easily, to write instructions. * It's also called High-Level Programming Language. For execution, a program in this language needs to be translated into machine language using a Compiler/ Interpreter. * Examples of this type of language are C, PASCAL, FORTRAN, COBOL, ete. Advantages : 1. Use of English-like words makes it a human-understandable language. 2. Lesser number of lines of code as compared to the above 2 languages. 3. Same code can be copied to another machine & executed on that machine by using compiler-specific to that machine. advantages : 1. Compiler/ interpreter is needed. 2. Different compilers are needed for different machines. 4, Fourth Generation Language : The fourth-generation language is also called a non — procedural language/ 4GL. It enables users to access the database. Examples: SQL, Foxpro, Focus, etc. These languages are also human-friendly to understand. Advantages : 1, Easy to understand & learn. 2. Less time is required for application creation. 3. Itis less prone to errors. isadvantages : 1. Memory consumption is high. 2. Has poor control over Hardware. 3. Less flexible. 5. Fifth Generation Language : The fifth-generation languages are also called SGL. It is based on the concept of artificial intelligence. It uses the concept that rather than solving a problem algorithmically, an application can be built to solve it based on some constraints, j.e., we make computers learn to solve any problem. Parallel Processing & superconductors are used for this type of language to make real artificial intelligence. Examples: PROLOG, LISP, etc. Advantages : 1. Machines can make decisions. 2. Programmer effort reduces to solve a problem. 3. Easier than 3GL or 4GL to learn and use. Dis advantages : 1. Complex and long code. 2. More resources are required & they are expensive too. —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ Structured Programming Language: > Itwas suggested by two mathematicians"CorradoBohm”&“Guiseppelacopini” its also referred to as modular programming. It employs topdown approach on which the over all programming structure broken down into separate modules and these modules are desveloped , tested individually. It is integrated to form the overall program structure. Advantage:- v It’s main goal is to write correct programs that are easy to understand and modify. it enhance the programmers productivity. vv Many programmers can work ona single large program. v It takes less time to write the programs. It is easy to debug. v v itis easy to change as well as understand. Mainprogram Topdowndesign approath pT Module. Module Module + + v Modulea Modules Moduleé C Programming: Cis a general-purpose and procedural programming language It was developed by Dennis Ritchie in 1972 at AT&TBell Labs of USA along with UNIX operating system C language was derived from the earlier languages called BCPL and B language BCPL was developed by Martin Richard B was developed by Ken Thompson Where as BCPL and 8 both languages are type less languages To over come this problem that it can be implemented by Clanguage Despite the emergence of numerous new languages Like Java,Python,JavaScript,and PHP, the popularity of C is not hampered. In fact, these languages have borrowed many of their control structures and other basic features from C. - > VV VVVV Features of C language: 1. Cis. a General purpose programming language: i.e.,we can solve anytype of problem by using c language 2. Cis a Procedure oriented Programming language: > Clanguage follows a specific structure or procedure to perform a specific task that’s why —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ itis also called as a procedure oriented programming language Cis a function oriented programming language: Everything we have to write within the form of functions using C Language. Without function we can’t write program in c 4. C Language supports Modularity: C language allows you to break or divide the large program into number of sub parts using functions which can be stored in the form of libraries for future use and reusability. Powerful language: C Language supports powerful pointers and with the help of powerful pointers dynamically allocate and de allocatethe memory Portable: Portable means light weight i.e,we can easily carry from one computer to another computer ve ve vo Case-sensitive Language: In C,the upper case and lowercase characters are different. That means if is not the same as IF in C language. 8. Platform Dependent: > The programs must be written and run on same operating system is called as platform dependent 9. Mid-LevelProgrammingLanguage: > Eventhough it is an High level language it behaves like a Middle level language i.e,it converts Highlevel language into Machine level and vice versa vn Structure of a C program: > Programs a collection of statements or set of instructions (such as read, calculate, write operations) to perform a specific task. > ThebasicstructureofaCprogramisdividedinto6Sections Documentation Preprocessor directive Section Definition section Global Declaration section Main() Function Sy een Sub Program section [consists commentlines, which describes the descriptionof the program such as author name,and created date and purposeof the program. //forsinglelinecomments Documentation /*multiple Linesofcomments*/ Itcanbewrittenanywherewithintheprogram itisanoptional |All header files are included in this section which contains different functions from the libraries. PreProcessor [These function definitions are processed be for reuse in the program to directive perform a specific task include H#include Which is used to create symbolic constants or macros. It can be specified by #define Definition i When ever these constants are occurred it automatically replace The value in the code. Global Includes dectaration of global variables,function declarations, static global Declaration variables, and functions before the main(). For every C program must contain main().It is mandatory The Main()Function eal " i execution starts from the beginningofmain(}function, It is an optional When ever the program is too large and difficult then the large program is divided into no of sub parts Each sub part is called as sub program(Userdefinedfunctions) [subprograms Writing first ‘C’ program: ‘© We can typetheCprogrambyusingthe Notepador Ceditor. ‘© if we are creating aC program by using’a notepad then we must save the program with the extension name “file.C”. include int main() { printf("Welcometoc\n’); return 0; } Hincludecstdio.h>:- it is a pre processor command which tell the computer to include the standard input / output library header files in the program. Header files contain the function definitions. Int main() :- int defines that the integer type of a value is returned by the program after executing all statement in main() function. The value is returned by using return keyword. All the statements are defined with in the braces. ( {}). printf(“WelcometoC\n”);:-printf()used toprintthe informationonthescreen. Escape Sequences:- these are used with printf{) statement and it will be effect on theoutput. It is followed by back slash(\). The following are escape sequences. \2-audiblesignal,\t-tab, \n-newline,\?-questionsmark, \\-backslash, —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ \F-newpage/clearscreen,\'-singlequite,\’-doublequote,\o-octalconstant, \b-backspaces,\x-hexadecimalconstant,\r-carriagereturn Turboc2commands:- F2—Save the program, F3— load the program, Ctrl + £9 — for compiling and executing, Alt+F5—to see output # define keyword is used to define symbolic constants. Ex: #define PI 3.1416 GlobalDeclaration section:- ‘© There are some variables that are used in more than one function. ‘* Such variables are called global variables and are declared in the global declaration section. ‘© This sectional so contains the declaration so fall the used defined functions main() function:- ‘© Every C program must contain main() function. iti structing to the compiler as a beginning part of the C program execution. ‘¢ It contains two sections. local declaration part which contains declarations of all the variables thataregoingto be used inthissection. © Executablesection contains the set of statements used to perform the specified task. These two parts must be appeared between the opening and closing braces ({}). Sub program section: ‘It contains all the userdefined function,definitions that are called in the main function. User defined functions are generally placed immediately after the main() function and may be appear in any order. Files used in a‘C’program: Every c program has four kinds of files associated with it. It Is shown in below diagram. Filesin‘C’program EEE Sourcefile Headerfile Objectfile Executablefile Source file:- ‘¢ it contains the sourcecode ofthe program. ‘© It defines the main function and may be other functions. © These files will have the extension name “.C”. Headerfiles:- ‘* These files contain the definitions of the functions, ‘© These are used to use the same functions in different program. ‘* These are used to change or add sub routines and those changes reflected in all other programs. ‘© These files will have the extension name “.h”. * _Clanguage includes the following header files. —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ ‘ _sring.h--for string handling functions stdlib.h ~ miscellaneous functions, stdio.h— input/output functions, math.h — for mathematical functions, alloc.h — for dynamic memory allocation conio.h-for clearing the screen Object file: 1. it was generated by compi 2. it contains binary code of the function definitions. 3. Linker uses this file to produce an executable files. 4. These files will have extension name.obj”. r. Executable file: 1. itis generated by linker. 2. These files are directly executed. 3. These file will have extension name“.exe”. Steps involved in the Compi n_and execution of a C prograi + Program Creation * Compilation of the program + Execution oftheprogram + TheoutPutoftheprogram Keys _| Operation F9 [Compile Only Ctrl F9 | Compile & run AtF5 | To see Output Screen F2___ [Save the File AltX | Exit Turbo C F3 [Load File F6 ‘Switch Window Comments in ‘C’ language: 1. Comments are just a way of explaining what aprogram does. 2. itis an internal program documentation. 3. Ignores the comments when forming the object file. 4, c supports two types of commenting 5. i) //-used for single line comments. ii) /*—— + /used for multiple line comments. Ex /*addition of two numbers Date : 25/10/2017 */ Hinclude int main() { Int a,b;//declaration i /* printing message */ printf(“sum=%d\n",a+b); return 0; } Tokens in‘c’ language: The smallest individual units with in a program are known as a tokens. The tokens are classified as 6 types. They are 1) Keywords 2) Identifiers3) constants4) operators5) special symbols6) strings. Keywords: > The key words are also called as pre-defined words or reserved words > It-contains a specific meaning > It should not use for other purpose > Clanguage supports 32 keywords > Allthe keywords must be specified in Lowercase letters only » int Volatile default return char ‘Const break auto float Sizeof continue static Typedef goto extern if while register Else do struct Switch for union Case void enum Identifiers: > Identifiers are the user defined words > Which is used to identify the unique names of the variables > Keywords should not be used as an identifers To create an identifier it must follow some rules or naming conventions vy Rules: + It must start with alphabet or under score(_). + It consists of alphabets, digits, or underscore. + Itshould not contain any special character except underscore(_), ‘+ It should not contain white spaces. + Itshould not exceed more than 32 characters of length Note: identifiers are case-sensitive so names like variable and Variable will be treated as different. Baic datatypes in C: ‘(CHanguage has a rich set of datatypes and these datatypes allow the programmer to define the type of the variable or programming elements that can be used to hold _ the values Variable: Data Types in C Valueless Proc pointer function Built-in data type: Void:- it can be sued in two situations. 1) when the function does not return any value to the calling program then we are defining the return type as avoid. 2) when the function does not receiving any parameter from the calling program then we are defining parameters list as a void. int: * itis usedtostore theinteger numbers. * The basic sizeofthis data typeis 2 bytes. ‘it cansupport signed or unsigned integer. * itis also support short and long integer. The format specifier of int data type is “ %d” Syntay int var_name; char: is used to store the character type of data. © The basi size is 1 byte. * The format specifier of char data type is ” %c” Syntax: Char var_name; ‘* We canalso store the collection of characters is called as string ‘* String must be specified with double quotes. «The format specifier of string data type is “ %s” Syntax: Char var_name[size]; —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ float:- * itis used to store the floating point data. ‘© The basic size is 4 bytes. Syntax: float var_name ; double: it isalso used to storethefloatpoint data.The basicsize is8. bytes. Long double: Itis also used to store the float point data. The basic size is 10 bytes. DataType Size Range in Bytes chr/signed char byte -128t0+127 unsignedchar Abyte Oto 255 int/ signedint 2bytes -32,768to + 32,767 unsigned int 2bytes Oto 65535 short int/signed shortint byte -128t0+127 unsignedshortint Abyte Oto 255 longint /signedlongint 4bytes -2,147,483,648t0+2,147,483,647 unsignedlongint bytes Oto 4,294,967,295 Float bytes 3.4e-38t0 3.4e+38 Double 8bytes 1.7e-308to 1.7¢+308 Longdouble 1Obytes | 3.4e-4932to1.1e+4932 Variable: A variable is a named memory location Which can store the specific value and memory depends on its datatype is called as a variable. Data_type variable_namec=value; _//defining a single variable data_type variable_namei,variable_name2; //defining multiple variables here, data_type: type of data that a variable can store variable_name: name of the variable given by the user. Value: value assigned to the variable by the user. Example Int sno; //va sn ble definition 0; /finitialization or Int sno=10; //variable declaration and definition Examp Int sno; //integer variable Char sname(20]; //character variable Float avg; // float variable —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ Rules: 1. Avariable name must only contain alphabets, digits, and underscore. 2. Avariable name must start with an alphabet or an underscore only. It cannot start with a digit. 3. No white space is allowed with in the variable name. A variable name must not be any reserved word or keyword 1. Local Variables: A Local variable in C is a variable that is declared inside a function or a block of code. Its scope is limited to the block or function in which it is declared. #include Void function() { Int x=10;//localvariable printf("960", x); } void main() { function(); } 2. GlobalVariable AGlobal variable in C isavariable that is declaredoutside the functionora block of code. Its scope is the whole program i.e. we can access the global variable any where in the C program after itis declared. Constants: > Aconstant represents fixedvalue. > Which cannot change or modify the value through out of an entire program is called as a constant Itcanbespecifiedbyconstkeyword v Be Const int c_var=20; > Constants are again classified into several types © Numerical constants © Character constants Numerical constants: > Numerical constants represents the number type of data with or without decimal points > Again Numerical constants are classified into two types such as integer constants and —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ real constants > Integer constants represents number type of data without decimal points Octal Integer constants represents eight values (0 to 7) Decimal Integer constants representstenvalues(0to9) Hexa Decimal integer constants,represents fifteen values(OtoF) Real constants represents number type of data with decimal points Standard real constants represents number with decimal points Scientific constants represents log values like 3.4e Character constants: > Character constants represents a letter or alphabets or text type of data > Single Character constants refers a single letter must be represent in single quotes > String constants refers a collection of characters must be specified with in double quotes vvV Input functions:- i) scanf():-itis used to read the data from the keyboard and assigned into the variables. li) syntax: scanf("control string” &argt,&arg2,...8argn); Ex:-scanf("%d%d”, &x,8y); iii) getchar():- it reads single character from the keyboard, display it on the screen and waitto press enter key, after pressing enter key, type character will be assigned into appropriate variable. Ex:-ch=getchar(); iv) getche():- it reads a single character from the keyboard and display on screen, will not wait to press enter key. Ex:-ch=getche(); v) geteh():. wait to press enter key. vi) gets():-it reads alineof textand assignedinto the variable. Output functions: printf():-it isused to displaymessagesandthe valuesof variableson the screen. Syntax:- printf(“‘control string” argd arg2,..argn); Ex:-printf(“total=%d\n",sum); Control string specifies how the characters will be printed on the screen. reads a gle character from keyboard and does not display on the screen, will not Control string contains the backslash characters and formats pecifiers. putchar():-it is used to print the value of a character variable on the screen, putc{):-it is used to print the value of character variable puts():-it is used to print the string variable. Backslash characters Format specifiers \n—newline %d—integer \b—backspace %f—float \v-verticaltab %c—character \thorizontaltab %s—group of \axbellalert characters —___C-languagefor1]Sem.B.C.A-HONOURS-2024-2025 _ \\slash séld-longinteger \?-questionmark %[...-string \-singlequotation 9%6x-hexadecimal \"-doublequotation ‘%o—octal C-languageforlISem.B.C.A~-HONOURS-2024-2025 Operators: ‘An operator is a symbol that tells the computer to perform simple mathematical or arithmetic operations on the data. i cath; Here,'+’ is the operator known as the addition operator,and’a’and'b’are operands. The addition operator tells the compiler to add both of the operands‘a’ and ‘b’. Some operators may require one or two or three operands.Based on number of operands © Ifit requires only one operand is called as unary operators © Ifit requires only two operands is called as binary operators © If it requires only three operand is called as ternary operators > Clanguage supports 8 types of operators Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Increment & Decrement Operators Conditional operators Special operators vvV PN ON EWNE ArithmeticOperators: > Arithmetic operators are used to perform simple arithmetic oper: addition, subtraction, multiplication, division and module etc., Symbol Meaning + Addition : Subtraction / Division % Module > The division(/) operator returns the result as quotient The module(%) operator returns the result as remainder C-languageforlISem.B.C.A~-HONOURS-2024-2025 Example: WAP to demonstrate the concept of arithmetic operators Hincludecstdio.h> Hinclude void main() { int a,b; clrser(); printf(“entera,bvlaues\n"); scanf("sed5ed",&a,&b); printf(" a = 96d \t b = 96d \n",a,b); printf("addition of %d+ 9d = Sd \n",a,b,a+b); printf("subtractionof%d-%d=%d\n",a,b,a-b); printf(" multiplicationof%d*%d=%d \n",a,b,a*b); printf("division of %d/ %d = 96d \n"a,b,a/b); printf("module of %dmod %d = %d \n",a,b,a%b); getch(); } Ba: include #include voidmain() { int a,b; clrser(}; printf("enter a,b viaues\n"); scanf("%eds6d",&a,&b); printf("before swapping\n"); d\n",a,b); printf("after swapping\n"); printf("a=96dandb=%d\n",a,b); getchi); } x3: WAP to calculate Simple interest and Compound Interest #include #include fincludecmath.h> void main() { int p,t,r,n; double si C-languageforlISem.B.C.A~-HONOURS-2024-2025 clrser(); printf("enter p,t,rvalues\n"); scanf("sedvad3éd", Sep 8, Br); printf("enter how many number of terms\n"); scanf("%6d" &n); printf("principle amount is:%d\n",p); printf("time of amount is : %d\n",t); printf("rate of intrest is : %d\n",r); *t*r}/100; *pow((1+r/n),n*t); printf("simple intrest is : %If\n",si printf("compound intrest is:%If\ getch(); } Relationaloperators: > Relational operators are also called as comparision operators. > Itisused to compare one variable with one value or one variable with another variable > It retums the value of a comparison is either 1 or 0, which means true(1) or false (0). These values are known as Boolean values “cid; symbol Meaning < Lessthan $ Less than or equals to > Greaterthan >= Greater than or equals to Doubleequalsto Notequalsto Logicaloperato > Logical operators are also called as combining operators Logical operators are used to combining two or more cons symbol Meaning Ba LogicalAND i LogicalOR ! LogicalNOT LogicalAND: LogicalOR A |B | A&&B A [8 [AIR TILT T T[T/ T TIF F TlFl| T FLT F Fi[t[ Tt FL E F FF] F C-languageforlISem.B.C.A~-HONOURS-2024-2025 LogicalNOT: a_i” T IF et Bitwise operators: » Bitwise operators are used to perform bit level operations onto the data is called as, Bitwise Operators > Bit stands for binary information tag.Which represents the data in 0's and 1’s > It supports only char and int datatypes only Symbol Meaning & | a BitwiseNOT * BitwisexOR << Bitwiseleftshift > Bitwiserightshift Pp Qa p&q pla pq 0 0 ° 0 0 0 1 0 1 1 1 1 1 1 o 1 ° 0 1 1 Assignment operators: > Assignment operators are used to assigning the value to it’s variable > It assign RHS value to LHS variable ‘Symbol Meaning = Equalsto Plusequalsto_ ‘Minusequalsto + Multiplicationequalsto fe Divisionequalsto = Moduleequalsto C-languageforlISem.B.C.A~-HONOURS-2024-2025 Increment and Decrement operators: Increment operators are used to increment one value to it’s variable. These are again Classified into two types Pre increment : ‘first increment the value and then assign to it’s variable the operator is specified before the operands is called as pre increment Post increment: ‘+ first assign the value to it’s variable and then later increment the operator is specified after the operands is called as post increment ‘© Decrement operators are used to decrement one value to it's variable. These are again classifie Pre decrement: ‘© First decrement the value and then assign to it’s variable '* The operator is specified before the operands is called as pre decrement Post decrement: ‘© First assign the value to it’s variable and then later decrement * The operator is specified before the operands is called as pre decrement Symbol Meaning + Increment = Decrement Conditional operator } tis also called as ternary operator Itrequires 3 operands to perform a specific operation > Syntax : ( Condition ) ? ( Statement! ) : ( Statement2 }; Special Operators: ¥ Special operators are used to improve the performance > Special operators are sizeof,comma, period operators. C-languageforlISem.B.C.A~-HONOURS-2024-2025 Type conversion and type casting: Type conversion or type casing refers to the changing a variable of one data type into another. Typeconversion:-itisdonewhentheexpressionhasvariableofdifferentdatatype. tis done implicitly. Thefollowingdiagramshowsthattheconversionoflowerleveldataintohigherleveldata. longdouble Higherlevel ex: float x; double float unsignediongint longiint nedint int Cosaaioe —] Typecasting:-It is also known as forced conversion. Type casting an arithmetic expression tell the compiler to represent the value of expression in a certain way.lt is done when the value of a higher data type has to be conversion into the value of lower level data type. Ex: floatsalary=10000. 00; int sal; sal=(int)salary; C-languageforlISem.B.C.A~-HONOURS-2024-2025 Unit-2 Control statements: ‘© control statements are used to change the order of execution based on user requirements is called as control statements * A program is a collection of statements. Which are executed in sequential order in which order they will appear that are executed in same order. ‘© some times we don’t want to execute all the statements in a program if you want to change the order of execution based on the user requirements that it can be implemented by control statements Fig, : 2.1 Different Types of Control Statements in C > control statements are classified into 3 types 1. Decision making and branching statements 2. Decision making and looping statements 3. Jumping statements Decision making and branching statements or Conditional Statements: > Decision making and branching statements are used to execute only some particular statements based on the condition is true or false. > Decision making and branching statements again classified into several types 1. If statements 2. Switch statements Hf statements: If statements are again classified into several types © Simple if © Ifelse © Else if ladder © Nested if ‘Simple if > Simpleif isused to checkonly oneconditionif the specified condition is true it allows to execute only true block statements otherwise it will not allow to execute the statements. if(condition) { C-languageforlISem.B.C.A-HONOURS-2024-2025, Code to be executed if condition is true; } tue fine Ilse: Its also used to check only one condition } Insimple If the specified condition is true it will execute the true block statements. otherwise it is not execute anything we can’t understand whether the program contain any erroror system failure.That it can be implemented by using if else ® felse statement if the specified condition is true allow to execute true block and If the condition is false allow to execute false block syntax: if{condition) sf Code to be executed if condition is true; } else { Code to be executed if condition is false; } tue find C-languageforlISem.B.C.A~-HONOURS-2024-2025 Else if ladder: > Else if ladder is used to check more than one condition if the specified condition is true then the associated true block statements are executed otherwise if all the conditions are false the false block statements are executed. Code to be executed if this condition is true; } elseif(condition) { Code to be executed if first condition is false and this condition is true; } else { Code to be executed if all conditions are false; } Ex: WAP to find biggest of three numbers Hincludecstdio.h> #include void main() { inta,b,¢; clrscr(}; printf("enter a,b viaues\n"); scanf("sads6d%d", 8a, &b,&c); iffa>b && a>c) { printf("a is big\n"); } elseif(b>c) { printf("b is big\n"); } else { printf("c is big\n"); } getch(); C-languageforlISem.B.C.A~-HONOURS-2024-2025 } Switch: > switch statement is an alternative to the if-else if-else statement which does almost the same thing. ® tis used to select only one particular statement from li ® Itconsists Case Braek Default keywords. of values Syntax: switch(n) { caselabel1 code to be executed if n=label1; break; caselabel2; code to be executed if n=label2; break; caselabel3: code to be executed if n=label3; break; default: code to be executed if n is different from all labels; } Example: Hinclude #include void main() { Intday; clrser(); printf("enter a day from 1to”\n"); scanf("%d",& day); switch(day) { case1:printf("today is Monday\n"); break; case2:printf("today isTuesday\n"); break; case3:printf("today is Wednesday\n"); break; case4:printf("today is Thursday\n"); break; caseS:printf("today is Friday\n"); break; case6:printf(""today is Saturday\n"); break;

You might also like