Session 16
Session 16: Select a small portion of any program written by you. Check if the portion of code selected by you is having constructs that violate the structured programming paradigm. If yes, then rewrite the code to conform to structured programming paradigm. If no, check another portion of code.
Structured Programming Paradigm
Structured programming is a programming
paradigm aimed at improving the clarity, quality, and development time of
a computer program by making extensive use of the structured control
flow constructs of selection (if/then/else) and repetition (while and for), block
structures, and subroutines.
Popular Programming Paradigms:
Imperative Programming
Procedural Programming
Functional Programming
Declarative Programming
Object-Oriented Programming
Our imperative code:
const nums = [1,4,3,6,7,8,9,2];
const result = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] > 5) result.push(nums[i])
}
console.log(result) // Output: [ 6, 7, 8, 9 ]
Program to check programming paradigm:
#include<stdio.h>
#include<stdlib.h>
int main(){
int ch=65;
int i,j,k,m;
// system("cls");
for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
printf("
");
for(k=1;k<=i;k++)
printf("%c",ch++);
ch--;
for(m=1;m<i;m++)
printf("%c",--ch);
printf("\n");
ch=65;
}
return 0;
}
1. There are no comments in the program to understand
another developer
2. Not properly calling the condition in second loop
Printing numbers without loop:
// C++ program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop
#include <iostream>
using namespace std;
// Recursive function to print the pattern.
// n indicates input value
// m indicates current value to be printed
// flag indicates whether we need to add 5 or
// subtract 5. Initially flag is true.
void printPattern(int n, int m, bool flag)
{
//
Print m.
cout
<< m << " ";
//
If we are moving back toward the n and
//
we have reached there, then we are done
if
(flag == false && n ==m)
return;
//
If we are moving toward 0 or negative.
if
(flag)
{
//
If m is greater, then 5, recur with true flag
if
(m-5 > 0)
printPattern(n,
m-5, true);
else
// recur with false flag
printPattern(n,
m-5, false);
}
else
// If flag is false.
printPattern(n,
m+5, false);
}
// Recursive function to print the pattern
// variance where m is the input int32 value
void PrintPattern(int m)
{
if
(m > 0)
{
cout
<< m << '\n';
PrintPattern(m
- 5);
}
cout
<< m << '\n';
}
// Driver Program
int main()
{
int
n = 16;
//printPattern(n,
n, true);
PrintPattern(n);
return
0;
}
There recursion should be used else we can use for loop
or do-while loop to shorten and optimize the code
Comments
Post a Comment