S y lla b u s , Int r o d uction PRO G RAM M IN G F O R PROB L EM S O L VING (PPS) B . T e c h I Sem CST
Unit 1 Introduction to Programming : Compilers, compiling and executing a program. Representation of Algorithm – Algorithms for finding roots of quadratic equations, finding minimum and maximum numbers of a given set, finding if a number is a prime number Flowchart/Pseudocode with examples, Program design and structured programming.
Unit 1 Introduction to C Programming Language: variables (with data types and space requirements), Syntax and Logical Errors in compilation, object and executable code, Operators, expressions and precedence, Expression evaluation, Storage classes (auto, extern, static, and register), type conversion,
Unit 1 The main method and command line arguments Bitwise operations: Bitwise AND, OR, XOR, and NOT operators. Conditional Branching and Loops: Writing and evaluation of conditionals and consequent branching with if, if-else, switch-case, ternary operator, goto , Iteration with for, while, do-while loops. I/O: Simple input and output with scanf and printf , formatted I/O, Introduction to stdin, stdout , and stderr. Command line arguments.
T e xtbooks & R efe r ences J eri R. Hanly and Elliot B. Koffman , “Problem Solving and Program Design in C,” 7th Edition, Pearson. A.B. Forouzan and F.S. Gilberg , “C Programming and Data Structures,” Cengage Learning, 3rd Edition.
C i s a p r og r amming language developed at Bell Laboratories of USA i n 19 7 2 b y Dennis Ritchie
C i s a p r og r amming lan g ua g e de v eloped at Bell Laboratories of USA in 1972 by Dennis Ritchie
Numbering System
Decimal to Binary
Decimal to Binary
Decimal to Binary 156 (10) 10011100 (2)
Binary representation (Decimal to Binary D e cimal n o . = 1 23 Bina r y n o . = 1 11 1 011 De c ima l n o . = 255 Binary no. = 1111 1111 De c ima l n o . = 486 Binary no. = 111100110
Binary to Decimal
Binary to Decimal
Binary to Decimal
Binary to Decimal
Binary to Decimal Binary no. = 110011 Decimal n o . = 51 Binary no. = 1111 0001 Decim a l n o . = 2 41
Algorithm Algorithm Algorithm is a finite set of instructions that if followed accomplishes a particular task. Problem Input Output Com p uter
Problem: Shortest distance Input n nodes con n ecting nodes distance between nodes Output Sho r test distance: 18
P r oblem: Sea r c h
P r oblem: Sea r c h
P r oblem: So r t
P r oblem: So r t
Characteristics of Algorithm Input Output Definiteness Effectiveness Finiteness O De u f t i p n u it t e − ne A s n s a − l S g h o o r u it l h d m b s e ho cl u e ld ar h a a n v d e 1 or lea d to only one meanin g . I E n f p fe u c t ti − ve A n n e a ss lg − or A it n hm al s g h o o r u it ld hm ha sh v o e u ld o h r ave m ste o p re -b w y e -s ll t - e d p ef d in ir e e d cti i o np ns u , ts w . hich should be independent of any programming code Finiteness − An algorithm must terminate after a finite number of steps
Characteristics of Algorithm Input − Should have or more well-defined inputs. Output - Should have 1 or more well-defined outputs, and should mat c h the de s ire d o utput. Definiteness − Should be clear and unambiguous. Effectiveness − Should have step-by-step directions, which sh o uld be inde p en d ent of a n y p r o g r amming c o d e . Finiteness − Must terminate after a finite number of steps.
P rog r am to displ a y “ W elcome to C” #include< s t di o . h > int main() { prin t f (“ W el c ome to C ”); return 0; }
P r oblem 1: Addition of t w o numbers Inpu t : 🞑 t w o nu m b ers (nu m1 = 4, num2 = 6) Output: 🞑 Sum = 10 Algorithm Step 1: Start Step 2: R ead the fi r st n u m b er(n um1) Step 3: R ead seco n d number(num2) Step 4: Sum n u m 1 +num2 Step 5: Print Sum Step 6: Stop Sum = num1 + num2
P r og r am t o ac c ept t w o nu m be r s f r om the user a nd dis p l a y the sum using C langu a g e /* P r og r am to ac c ept t w o nu m be r s and dis p l a y the s um Programmer : --Your name-- R oll no: -- y our r oll nu m be r -- Date of compilation: 27Jan2021 Cla s s : B . T e c h I Se m „C S T' */
#include<stdio.h> // Main function begins int main() { int num1,num2,sum; printf("Enter first value:"); scanf("%d",&num1); pri n tf ("En ter Second v alue:"); scanf("%d",&num2); sum=num1+num2; printf (“Addition of %d and %d is: %d",num1,num2,sum); return 0; }
P r obl e m 2: Alg o rithm to find the a r e a of rectan g le I n put : 🞑 t w o nu m be r s . (le ng t h = 8 breadth = 4) Output: 🞑 Area of rect = 32 Alg orithm Step 1: Start Step 2: R ead fi r s t n u m b er(le n gth) Step 3: Read second number (breadth) Step 4: Area length * breadth Step 5: Pri n t “ Ar ea of rect ”, Ar ea Step 6: Stop Area = length * breadth
Ex3: P r oblem: Find greater of t w o no ‟ s Algorithm: 🞑 Step 1: Start 🞑 Step 2: Declare variables A, B 🞑 Step 3: Accept two values from user and store in A and B respectively. 🞑 Step 4: Ch e ck whether A > B; T r ue: 4.1; F alse: 4.2 Y es Pri n t A i s gre ater No Pri n t B i s g reater 🞑 Step5: Stop
Ex4: Find Lar g est of three num b ers S tep 1: S ta r t S tep 2: D e clar e v ar i able s a,b and c. S tep 3: R e ad v ar i able s a,b and c. S tep 4: I f a>b ; T r ue: 4.1; F al s e : 4.2 4.1 I f a>c T r ue : 4.1 . 1; F al s e : 4.1 . 2 D i sp l a y a i s the la r g e st numbe r . else D i sp l a y c i s the la r g e st numbe r . Else I f b>c T r ue: 4.2. 1; F al s e : 4.2. 2 D i sp l a y b i s the la r g e st numbe r . else D i sp l a y c i s the gr e ate s t numbe r . S tep 5: S top
Ex5: Calculate G r os s , Net Salary Problem: Accept the employee details such as empid and basic salary. Consider DA with 120% of basic, HRA with 1 % of b a sic. Calcula t e the g r oss s a la r y and net salary considering tax deduction of Rs. 2% of gross.
Example: G r os s , Net Empi d : 1 01 Basic: 10 00 D A: 1 2 0% of Ba s ic=1.20* 1 0000= 1 2 HRA: 10% of Basic=0.1*10000 = 1000 Gross=Basic+DA+HRA = 10000+12000+1000=23000 T ax: 2% of G r oss = 0.02*23 000=4 6 Net = G r os s - T ax = 23 - 4 6 = 2 2 5 4
Algorithm: G r os s , Net Step 1: Sta r t Step 2: Declare variables empid,basic,da,hra,tax,gross,net St e p 3: P r in t "E n ter E m pl o y ee I D " Step 4: Ac c ept empid St e p 5: P r in t "E n ter basic sa l ar y" St e p 6: Accept b as i c Step 7: Comp u te da = ( 1 2 /100 )* b a s ic Step 8: Compute hra=(10/100)*basic St e p 9: C o m p ute g r o s s=( ba s ic+d a+ h r a ) St e p 10: P r in t "G r o s s Sa l ar y" St e p 11: C o m p ute tax= ( 2/100) * g r oss St e p 12: net=g r o s s - t a x; St e p 13: P r in t " N et S alar y" Step 1 4 : Stop
#include<stdio.h> int main() { int empid; float basic,da,hra,tax,gross,net; pri n tf ("En ter Empl o y ee id:"); scanf("%d",&empid); pri n tf ("En ter Basic Sal a ry: "); scanf("%f",&basic); da=1.2*basic; hra=0.1*basic; gross=(basic+da+hra); printf("Gross Salary=%f",gross); tax=0.02*gross; net=gross-tax; printf("Net Salary=%f",net); retu r n 0; }
Ex 6: Calculate Simple Inte r est Si = (P * T * R) / 1
Flowchart A Flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or process. Each step in the process is represented by a different symbol and contains a short description of the process step. The flow chart symbols are linked together with arrows showing the process flow direction. A flowchart typically shows the flow of data in a process, detailing the operations/steps in a pictorial format which is easier to understand than reading it in a textual format.
Flowchart Flowchart is the pictorial representation of an algorithm
49 Identify What do ea c h of the f oll o wing symbols re p re s ent? Decision Terminal I n p u t / Out p ut Operation P ro cess Co n nector Module
Example 1: Algorithm & Flowchart Probl e m : Di spl a y the S u m, A v e r a g e , P r odu ct of three given numbers Algorithm Step1: Start Step 2: R ead X, Y , Z Step 3: Compute S u m ( S) X + Y + Z Step 4: Compute A v e r a g e (A) S / 3 Step 5: Compute Product (P) as X x Y x Z Step 6: Prin t S , A, P Step 7: Stop
Example 2: Algorithm & Flowchart Problem : Display the largest of two given numbers Algorithm Step1: Start Step 2: R ead A, B Step 3: I f A i s le s s than B 🞑 T r u e : Assign A to B I G an d B to S M A LL 🞑 F a l s e : Assign B to B I G a nd A to S M A LL Step 6: Pri n t S , A, P Step 7: Stop
Control Structures Sequence : A series of steps or statements that are executed in the order they are written in an algorithm. Sel e cti o n : Defines t w o cou r ses of a ction d epend i ng on the outcome of a condition. A condition is an expression that is, when computed, evaluated to either true or false. (ex: if, if els e , nested if) Repetition/Loop : Specifies a block of one or more statements that are repeatedly executed until a condition is satisfied. (Ex: f o r , w hile, do while)
Ex: Sequence Cont r ol S t r ucture A se r ie s of steps or state m ents that are e x ecuted i n the order they are written in an algorithm. T h e be g i nni ng a nd end of a blo c k of sta t ements can be optionally marked with the keywords begin and end. begin statement 1 sta t ement 2 statement n ..... end
Sequence Ex: Cal c ulate P er s o n ‟ s a g e
Sequence Exam p le int main() { int first, second, temp; printf("Enter first number: "); scanf("%d", &first); printf("Enter second number: "); scanf("%d", &second); temp = first; first = second; second = temp; printf("After swapping, firstno. = %d\n", first); printf("After swapping, secondno. = %d", second); } Swa p t w o numbers using temp var
Sequence Exam p le int main() { int a, b; printf("Enter a and b: "); scanf("%d %d", &a, &b); a = a - b; b = a + b; a = b - a; printf("After swapping, a = %d\n", a); printf("After swapping, b = %d", b); return 0; } Swa p t wo numbers without using temp var
Selection (Decision) Cont r ol st r ucture is condit i on Y N Print stmt1 Print stmt2
Syntax: if if (condition) stmt1 else stmt2 C programming if (a>b) printf(“a is greater than b”); else printf(“b is greater than a”); Selection (Decision) Cont r ol st r ucture
Selection Ex: Program to print the given number is n eg a t i v e or posit i v e using if else int main() { int num; printf("Enter a number to check.\n"); scanf("%d",&num); if (num<0) printf(“Given Number = %d is negative\n",num); else printf(“Given Number = %d is positive\n",num); return 0; }
Sel e ction Ex: Problem : Write an algorithm to determine a student‟s final grade and display pass or fail. The final grade is calculated as the average of four subject marks. Algorithm Step1: Start Step 2: Input M1,M2,M3,M4 Step 3: GRA D E (M1 + M2+M 3 +M4)/4 Step 4: if (GRADE > 60) then Print “Pass” else “Fail” Step 5: Stop
S T A R T Input M1,M2 , M3,M4 GRADE (M1+M2+M3+M4)/4 IS GRAD E> 60 S T O P Y N Print “Fail” Print “ P ass” Algorithm Ste p 1: St a r t Step 2: Input M1,M2,M3,M4 Step 3: GR A DE ( M 1+M2+M3+M 4 )/4 Step 4: i f (G RAD E > 6 0) th en Print “ P ass” else “ F ail” Step 5: end if Step 6: Stop Selectio n Ex:
Selectio n Ex: Program to check for odd or even int main() { int num; printf("Enter an integer: "); scanf("%d", &num); if (num % 2 == 0) printf("%d is even.", num); else printf("%d is odd.", num); return 0; }
Sel e ction Ex: P r og r am to c he c k o d d or e v en using te r nary ope r ator ? : int main() { int num; printf("Enter an integer: "); scanf("%d", &num); (num % 2 == 0) ? printf("%d is even.", num) : printf("%d is odd.", num); return 0; }
Selection Ex: P r oblem: Find greater of t w o no ‟ s Algorithm: 🞑 Step 1: Start 🞑 Step 2: Declare variables A, B 🞑 Step 3: Accept two values from user and store in A and B respectively. 🞑 Step 4: Ch e ck whether A > B; T r ue: 4.1; F alse: 4.2 Y es Pri n t A i s gre ater No Pri n t B i s g reater 🞑 Step5: Stop
Selection
Sel e ction Ex: Find Lar g est of three numb ers S tep 1: S ta r t S tep 2: D e clar e v ar i able s a,b and c. S tep 3: R e ad v ar i able s a,b and c. S tep 4: I f a>b ; T r ue: 4.1; F al s e : 4.2 4.1 I f a>c T r ue : 4.1 . 1; F al s e : 4.1 . 2 D i sp l a y a i s the la r g e st numbe r . else D i sp l a y c i s the la r g e st numbe r . Else I f b>c T r ue: 4.2. 1; F al s e : 4.2. 2 D i sp l a y b i s the la r g e st numbe r . else D i sp l a y c i s the gr e ate s t numbe r . S tep 5: S top
int main() { double n1, n2, n3; printf("Enter three different numbers: "); scanf("%lf %lf %lf", &n1, &n2, &n3); if (n1 >= n2 && n1 >= n3) printf("%.2f is the largest number.", n1); if (n2 >= n1 && n2 >= n3) printf("%.2f is the largest number.", n2); if (n3 >= n1 && n3 >= n2) printf("%.2f is the largest number.", n3); return 0; } Selection : if
int main() { double n1, n2, n3; printf("Enter three numbers: "); scanf("%lf %lf %lf", &n1, &n2, &n3); if (n1 >= n2 && n1 >= n3) printf("%.2lf is the largest number.", n1); else if (n2 >= n1 && n2 >= n3) printf("%.2lf is the largest number.", n2); else printf("%.2lf is the largest number.", n3); return 0; } Selection : i f els e if
int main() { double n1, n2, n3; printf("Enter three numbers: "); scanf("%lf %lf %lf", &n1, &n2, &n3); if (n1 >= n2) { if (n1 >= n3) else printf("%.2lf is the largest number.", n1); printf("%.2lf is the largest number.", n3); } else { if (n2 >= n3) else } return 0; printf("%.2lf is the largest number.", n2); printf("%.2lf is the largest number.", n3); } Selection : neste d if
Repetition: While condition
Loop: f or for(initialization, condition, incrementation) { code s ta t ements; } int main() { int i; for (i=0; i<10; i++) { printf("i=%d\n",i); } return 0; }
Loop Exam p le : Multipl i cation table int main() { int n, i; printf("Enter no. to print multiplication table: "); scanf("%d",&n); for(i=1;i<=10;++i) { printf("%d * %d = %d\n", n, i, n*i); } }
C basic elements Valid character set Identifiers Keywords Basic da t a types Constants Variables
C V alid c ha racter set up p ercase Engli s h alp ha b ets A to Z, l o w ercase lette r s a to z, digits to 9, ce r tain special c ha r acters as building blo c ks to f o r m basic program elements viz. constants, variables, operators, expressions and statements.
C Identifiers Identifiers are names given to various items in the program, such as v aria b le s , f u nctio n s and ar r a y s . An identifier consists of letters and digits, in any order, except that the fi r st c ha r ac t er m us t b e a lette r . Both upper a nd l ow ercase letter s are pe r mitte d . C is a case sensitive, the upper case and lower case considered different, for example code, Code, CODE etc. are different identifiers. Th e un d e rs core c ha r ac t er _ can also be incl u d e d. Keywords like if , else , int , float , etc., have special meaning and they cannot be used a s identifie r na m e s .
V alid a n d in v alid C identi f iers ANSI standard recognizes 31 characters valid identifiers: A, ab123, velocity, stud_name, cir c umfe r en c e , A v e r a g e , T O T AL. Invalid identifiers: 🞑 1st 🞑 "Jamshedpur" 🞑 stud-name 🞑 stu d name
C Data types
C Data types and sizes D a ta ty p e Description Size Range char single c ha r acter 1 byte - 255 int integer number 4 bytes -2147483648 to 2147483647 float single prec isio n floating poi n t number (number con t aining fraction & or an exponent) 4 bytes 3.4E-38 to 3.4E+38 double double precision floating point number 8 bytes 1.7E-308 to 1.7E+308
C Data types and sizes D a ta ty p e Size Range sho r t i nt 2 bytes -32768 to 32767 lo ng i nt 4 bytes -2147483648 to 2147483647 u n sig n ed sho r t int 2 bytes to 65535 u n sig n ed i nt 4 bytes to 4294967295 u n sig n ed lo ng int 4 bytes to 4294967295 long double (extended precision) 8 bytes 1.7E-308 to1.7E+308
C Co n stants C can be classified into four categories namely integer constants, floating point constants, character constants and string constants. A character constant is written as for example - 'A' A no r mal inte g er const a nt i s w ri t ten as 1 2 3 4 . A lon g in t uses L (up p ercase or l ow ercase) at the end of the const a nt, e . g . 2 7 4 8 7 2 3L C also suppo r ts octal and h e xadecimal da t a. Ex: 0xC
Escape sequenc e c ha r acte r s Character Escape Se q uen c e AS C II V alue Bell \a 007 Backspace \b 008 Null \0 000 Newline \n 010 Carriage return \r 013 Vertical tab \v 011 Hor i zon t al t a b \t 009 F o r m feed \f 012
Symbolic constants # d efine PI 3. 1 4 1 5 9 3 #de f in e TRUE 1 # d efine PRO M PT "Enter Y our Name :"
Accept n ame f r om the user Metho d 1 char name[20]; printf("Enter your name:"); scanf(" %s ",name); pri n tf (" Y our name i s : % s", nam e ); Metho d 2 char name[20] p r int f (“Enter y our name:”) gets(name) ; p r int f (“ Y our name is:” ) ; puts(name) ;
Accept n ame f r om the user M e th o d 3 #define MA X _LIMIT 2 int main() { char name[MAX_LIMIT]; printf("Enter your name:"); fgets(name,MAX_LIMIT,stdin); pri n tf (" Y our name i s : % s", name ); Metho d 4 char name[20]; printf("Enter your name:"); scanf("%[^\n]%*c",name) ; p r int f (" Y our name is : % s",n a m e );
Operators in C Arithmetic ope r a t ors R elational ope r ato r s Logical operators Bitwise ope r ato r s Assi g nment ope r a t ors Mi s c ope r ato r s
i n t a = 1 , b = 2 , c = 2 5 , d = 2 5; pri n tf (“ %d" (a + b ) ); pri n tf (“ %d" (a - b) ); printf (“ %d “ ( a * b) ); pri n tf (“ %d” (b / a ) ); printf ( “ %d” (b % a) ); pri n tf (“ %d” (c % a) ); printf (“%d“ pri n tf (“ %d “ pri n tf (“%d “ printf (“%d “ (a + +) ); (a --) ); (d + +) ); (++d) ); OUTPUT 30 -10 200 2 5 10 11 25 27
Example: Bitwise Oper ato r s int a = 60; int b = 13; in t c = 0; c = a & b ; c = a | b; c = a ^ b; c = ~ a; c = a << 2; pri n tf (“%d" + c ); printf (“% d " + c ); pri n tf (“%d" + c ); pri n t f (“%d" + c ); pri n tf (“%d" + c ); c = a >> 2; pri n tf (“%d" + c ); OUTPUT a= 60 = 0011 1100 b= 13 = 0000 1101 c = a & b ; 0000 1100 = 12 c = a | b; 0011 1101 = 61 c = a ^ b; 0011 0001 = 49 c = ~a; 1100 0011 = -61
Mi s c Ope r ators sizeo f () & : : : : R etu r ns the s iz e of the v a r ia b le R etu r ns the a d dres s of a v aria ble P ointer v a r ia b le Conditional / Ternary operator * ?:
Ope rator Precedence in t a = 20, b = 10 , c = 15, d = 5; e = (a + b) * c / d ; // Print value of e e = ((a + b) * c) / d; // Print value of e e = (a + b ) * (c / d ) ; // Print value of e e = a + (b * c) / d ; // Print value of e in t e; V alue of (a + b) * c / d i s : 90 V alue of ((a + b) * c) / d i s : 90 V alue of (a + b) * (c / d) i s : 90 Value of a + (b * c) / d is : 50 ( 30 * 15 ) / 5 (30 * 15 ) / 5 (30) * (15/5) 20 + (150/5) assoc i ativity of ope r at o rs de t e r mines the direction i n whi c h an expression is evaluated. Example, b = a; associa t iv i ty of the = o pe r at or i s f r om right t o lef t ( RL).
Operator Description Associativity () [ ] . P ar e nt h es e s (g r oup i ng) B r a c k ets ( a r r a y subscript) M e m b er s e l e c t i o n M e m b er s e l e c t i o n via po i nter LR ++ -- + - ! ~ ( typ e ) * & sizeof Unary pr e incr e ment / p r e d ec r e m ent Unary plus/minus Unary l o gical ne g ation / bi t wise complement Un a ry c a st ( c h a n g e t y pe ) D e r e feren c e Address Dete r m in e s i ze i n b ytes RL = Ass i gn m ent op e r ator
Arithmetic Operators Multiplication operator, Divide by, Modulus *, /, % LR Add, Subtract +, – LR Relational Operators Less Than < Greater than > Less than equal to <= Greater than equal to >= LR Equal to == Not equal != Logical Operators AND && LR OR || LR NOT ! RL 1 == 2 != 3 operators == and ! = ha v e the sa m e precedence, LR Henc e , 1 == 2 is executed first
Hungarian Notation Hungarian is a naming convention for identifiers. Each identifier would have two parts to it, a type and a qualifier . Ea c h a d dress stores one element of the m emory a r r a y. Ea c h element i s ty p icall y one b yt e . For example, suppose you have a 32-bit quantity written as 12345678 , w h i c h i s h e xad e c i ma l . Since each hex digit is four bits, eight hex digits are needed to represent the 32-bit value. The four bytes are: 12, 34, 56, and 78. There are two ways to store in memory: Bigendian and little endian
Endianness The endianness of a particular computer system is g ene r ally de s cri b ed b y whate v er con v ention or s e t o f conventions is followed by a particular processor or combination of processor/architecture and possibly o p e r ating s y st e m o r t r an s missi o n medium f or the a dd r e s sing of c on s tants and the r e p r e s e ntations of memory ad d r e ss e s . O f ten r e f e r r ed to as b yte ord e r
Big En d ia n sto r a g e Big-endian : Stores most significant byte in smallest address. The following shows how 12345678 is stored in big endian Big En d ian St o r a ge Address Value 1000 12 1001 34 1002 56 1003 78
Little En d ia n sto r a g e Little-endian : Stores least significant byte in smallest address. The following shows how 12345678 is stored in big endian Lit t le En d ian St o r a ge Address Value 1000 78 1001 56 1002 34 1003 12
F or e xample 4A3B2C1D at ad d ress 10 , th e y sto r e the bytes within the address range 100 through 103 in the following order:m
T ype Casting Type casting is a way to convert a variable from one da t a type to another da t a typ e . 🞑 Implicit Conversions 🞑 Explicit Conversions
Implicit Conversions int main() { int i = 17; c har c = ' c'; /* ascii v alue i s 99 */ int sum; sum = i + c ; printf("Value of sum : %d\n", sum ); }
Explicit Conversions General format / Syntax: (type_name) expression Example: main() { i n t s u m = 17, co u nt = 5; double mean; mean = (double) sum / coun t; printf("Value of mean : %lf\n", mean ); }
Examples: T ype Con v er s ions float a = 5.25; int b = (int)a; c har c = ‟ A ‟; int x = (int)c; int x=7, y=5 ; float z; z=x/y; int x=7, y=5; float z; z = (float)x/(float)y;
Loop Exam p le : Multipl i cation table int main() { int n, i; printf("Enter no. to print multiplication table: "); scanf("%d",&n); for(i=1;i<=10;++i) { printf("%d * %d = %d\n", n, i, n*i); } }
b r eak St a teme n t The break statement in C programming language has the following two usages: When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. It can be used t o te r m i nate a case in the s witch s t atement If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax: break;
int a = 10; while( a < 20 ) { printf("value of a: %d\n", a); a++; if( a > 15) { break; } } OUTPUT value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15
in t num =0 ; while ( num<=10 ) { printf (" v alue o f v ariable num is : % d \ n", num); if (num==2) { br e ak; } num++; } printf("Out of while-loop"); Ou t put: v alue of v ariab l e num is : v a l ue of v ariab l e num is : 1 v a l ue of v ariab l e num is : 2 Out of while-loop
int var; for (var =100; var>=10; var --) { printf("var: %d\n", var); if (var==99) { break; } } printf("Out of for-loop"); Ou t put: var: 100 var: 99 Out of for-loop
int a = 4; while( a < 10 ) { printf("value of a: %d\n", a); ++a; if( a > 8) { break; printf("Break\n"); } printf("Hello\n"); } printf("Out of While loop\n"); }
continue T h e cont i nue s t at e ment i n C p r og r amm i ng lang u a g e w o r ks som e w h at l i k e the b r eak statement. Instead of forcing termination, continue statement forces the next iteration of the loop to take place, skipping any code in between.
int a = 10; do { if( a == 15) { a = a + 1; continue; } printf("value of a: %d\n", a); a++; } while( a < 20 ); value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19
int counter=10; while (counter >=0) { if (counter==7) { coun t e r -- ; continue; } printf("%d ", counter); counter--; } Ou t put: 10 9 8 6 5 4 3 2 1
int a = 10; do { if( a == 15) { a = a + 1; continue; } printf("value of a: %d\n", a); a++; } while( a < 20 );
goto statement The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally. Syntax: goto label; Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. label : statement;
int w; printf("Enter the input 1 or 0:\n"); scanf("%d", &w); if (w == 1) goto CST; i f (w == 0) printf (" V alue en t er ed i s \ n"); return 0; CST : printf (" Y ou bel o ng t o C S T S e ctio n \ n"); goto end; end : printf("Have a nice Day\n"); return 0; }
Example: Nested Loop int i, j; for(i=2; i<10; i++) { for(j=2; j <= (i/j); j++) if(!(i%j)) break; if(j > (i/j)) printf("%d is prime\n", i); }
Program to check alphabet, digit or special character Alphabet: a to z (or) A to Z Digit : to 9 else it is special character if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) printf("'%c' is alphabet.", ch); else if(ch >= '0' && ch <= '9') printf("'%c' is digit.", ch); else printf("'%c' is special character.", ch);
P r ogr am to c he c k v o w el of consonant Vowel : a ( or) e ( or) i ( or) o ( or) u Consonant : a to z or A to Z else: not an alphabet if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') { pri n tf ("'%c' i s V o w el.", c h ); } else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) printf("'%c' is Consonant.", ch); els e pri n tf ("'%c' i s not an al p habe t ." , c h );
Sum of digits of given number using while s u m = ; // Accept n umber a nd store i n n n u m = n; w hile( n > ) { rem = n % 1 ; s u m += rem ; n /= 10; } pri n tf ("Sum of di g it s of %d i s %d", n u m, s u m); OUTPUT En ter a n u m b er: 4 5 6 Sum of di g it s of 4 5 6 i s 15
Sum of digits of given number using while s u m = ; // Accept n umber a nd store i n n n u m = n; w hile( n > ) { rem = n % 1 ; s u m += rem ; n /= 10; } pri n tf ("Sum of di g it s of %d i s %d", n u m, s u m); OUTPUT En ter a n u m b er: 4 5 6 Sum of di g it s of 4 5 6 i s 15
Pr i nt all OD D nu m be r s from 1 to N using w hi l e loo p . number=1; while(number<=n) { if(number%2 != 0) printf("%d ",number); number++; }
Print its multiplication table i=1; while(i<=10) { printf("%d\n",(num*i)); i++; }
count total digits in a given integer using loop do { count++; num /= 1 ; } while(num ! = 0); printf("Total digits: %d", count);
P r o g r am to p r in t numb e rs b et w e e n 1 a nd 1 whi c h a r e m ultiple of 3 using the do w hile lo o p int i = 1; do { if(i % 3 == 0) { printf("%d ", i); } i + + ; }while(i < 100);
find sum of o d d n um b ers from 1 to n for(i=1; i<=n; i+=2) { sum += i ; } p r int f ("Sum of odd nu m b e rs = %d", sum);
Exponential series int i, n; float x, sum=1, t=1; // Accept x // Accept n for(i=1;i<=n;i++) { t=t*x/i; sum = sum+ t ; } printf(“Exponential Value of %f = %.4f", x, sum);
Program to print its multiplication table i=1; while(i<=10) { p r intf("% d \ n",(num*i) ) ; i++; } i=1; do { printf("%d\n",(num*i)); i++; }while(i<=10); for(i=1;i<=10;i++) { pri n tf("%d \ n", (nu m*i)); }
k = 1; for(i=1; i<=rows; i++) { for( j=1; j<=cols; j++, k++) { printf("%-3d", k); } printf("\n"); } Print n u mber patte r n as sh o wn
int main() { int i; for ( i =0 ; i <10 ; i ++) { printf("i=%d\n",i); } return 0; }
F acto r ia l using f or loop fact=1; for(i=num; i>=1; i--) fact=fact*i; printf("Factorial of %d is = %ld",num,fact);
Sum of n natu r al no ‟ s us i ng f or su m = 0; for(i = 1; i <= n; i++) su m += i ; print f ("S u m is : % d \ n", sum);
Program to print its multiplication table i=1; while(i<=10) { i++; } i =1; do { printf("%d\n",(num*i)); printf("%d\n",(num*i)); i++; } while(i<=10); for(i=1;i<=10;i++) { printf("%d\n",(num*i)); }
Ex: 2: Nest e d f or loop for (int i=0; i<2; i++) { for (int j=0; j<4; j++) { printf("%d , %d \ n", i ,j); } }
Ex: 3: Nest e d f or loop k=1; for (i=0; i<2; i++) { for (j=0; j<4; j++,k++) { printf("%d, %d, %d\n",i ,j, k); } }
Print number patte r n as sh o wn Out p ut: 1 12 123 1234 for(i=1; i<=rows; i++) { for( j=1; j<=i; j++) printf("%d", j); printf("\n"); }
Stru c tu r ed vs Uns t ru c tu r ed Prog r a m m i ng St r uc tur e d P r og r a m ming i s a programming paradigm which divides the code int o module s or function. Unst r uc tur e d P r og r a m ming i s the pa r adigm i n w h i c h t h e code is cons i de r ed as one s i ngle bl o c k. Readability St r uc tur e d P r og r a m ming base d p rog r a m s are easy to r e a d . Unst r uc tur e d P r og r a m ming base d p rog r a m s are h a rd to r e a d . P u rpose St r u c t u r e d P r og r a m m in g i s to m a k e t h e code more e f f i ci e nt and ea s i e r to understand. Unst r u c t u r e d p rog r a m m in g i s jus t to p r og r am to s o l v e the p r ob l em. I t do e s not create a logical structure. Co m pl e xi t y St r uc tur e d P r og r a m ming i s ea s i e r because of module s . Unst r uc tur e d p r og r a m ming i s harder w h en compa r i ng with t he st r uc tur e d programming
Application Structured programming can be used for small and medi u m scale p r ojec t s . U n st r u c t u red p r og r a mming i s not applicable for medium and complex projects. Modification I t i s e a sy to do c han g es i n St r u c t u red Programming. It is hard to do modifications in Unstructured Programming. D a ta T y p es St r u c t u red p r og r ammi n g uses ma n y data types. U n st r u c t u red p r og r a mming has a limi t ed n u mber of da t a ty p e s . C o d e Dupli c a ti o n St r u c t u red p r og r ammi n g a v oids code duplication. U n st r u c t u red p r og r a mming can ha v e code duplication. T esting and De b ug I t i s e a sy to do tes t i ng and d e bugg i ng in St r uc t ured P r og r ammin g . I t i s h ard to do tes t i ng and d e bugg i ng in Unst r uc t ured p r og r a mmin g .
P alind r ome nu m ber rev=0 origin=n; while (n != 0) { rem = n % 10; rev = rev * 10 + rem; n /= 10; } if (orig == rev) printf("%d is a palindrome.“,orig); else printf("%d is not a palindrome.", orig);
int i, j; for(i = 2; i<100; i++) { for(j = 2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime\n", i); } Print Pr i me numbers upto 100
P alindr o me number rev=0 origin=n; while (n != 0) { rem = n % 10; rev = rev * 10 + rem; n /= 10; } if (origin == rev) printf("%d is a palindrome.“,orig); else printf("%d is not a palindrome.", orig);
goto statement: Unstructured programming The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally. Syntax: goto label; Control may be transferred to anywhere within the current function. The tar g et stat e ment m ust be labe le d , a nd a c o lo n m ust follow the label. label : statement;