CTSD_SLM_Book updated PDF

Summary

This document provides an introduction to structured programming, discussing algorithmic thinking, design, and flowcharts. It explores concepts such as modular programming, data types, operators, and conditional statements. Ideal for an undergraduate course introducing programming.

Full Transcript

23SC1101-Computational Thinking for Structured Design Chapter 1 Structured Programming Paradigm In this chapter, we delve into the fundamentals of structured programming, equipping readers with essential skills in algorithmic thinking and problem-solving. The chap...

23SC1101-Computational Thinking for Structured Design Chapter 1 Structured Programming Paradigm In this chapter, we delve into the fundamentals of structured programming, equipping readers with essential skills in algorithmic thinking and problem-solving. The chapter commences with a thorough exploration of Algorithmic Thinking: A Step-by-Step Guide to Problem Solving. Readers will be introduced to the art of dissecting complex problems into manageable steps, fostering a systematic approach to finding effective solutions. Building upon this foundation, the narrative progresses to the transformation of abstract ideas into concrete solutions through the process of Designing Effective Algorithms for Real-World Problems. This segment underscores the significance of crafting algorithms that not only solve problems but also address real-world challenges. Continuing the journey, the chapter takes a closer look at Designing Flowcharts for Problem Solving. Flowcharts emerge as indispensable tools for visually representing the algorithmic process, enhancing understanding and communication. The chapter proceeds to Modularization - Functions, elucidating the advantages of breaking down complex tasks into modular, reusable functions. By doing so, readers gain insight into crafting organized and efficient code structures. Furthermore, the discussion turns to Data Types, encompassing int, int pointer, float, float pointer, char, and char pointer, along with their respective roles in program development. Console I/O operations are explored within the context of these data types, enabling readers to interact with their programs and users effectively. The narrative deepens with an exploration of array data types, including int array, float array, and char array, alongside the integration of Console I/O operations with these arrays. Basic Operators, ranging from arithmetic to relational and logical operators, are examined in detail. The chapter unveils the mechanics of constructing expressions, evaluating them, and understanding operator precedence for accurate computation. To complete the comprehensive understanding of structured programming, the chapter culminates in a discussion of Storage Classes. By delving into concepts like if-else constructs, else if ladders, conditional operators, nested if-else statements, and switch statements, readers emerge equipped to make informed decisions and implement branching logic effectively. In essence, this chapter serves as a holistic introduction to the structured programming paradigm, guiding readers from the core principles of algorithmic thinking and problem solving to the practical implementation of modularized code structures, data types, operators, and conditional statements. The mastery of these topics equips readers with the essential skills to craft organized, efficient, and logically sound programs, serving as the foundation for their journey into the world of programming. 1 23SC1101-Computational Thinking for Structured Design 1.1 STRUCTURED PROGRAMMING Structured programming is a way of writing code that aims to make it easy to read, efficient, and simple to maintain. In this approach, the code is organized into clear structures, which makes it easier to understand. We use smaller sections of code called subroutines, as well as control structures like loops and conditionals, to help us write better code. It's like breaking down a big problem into smaller, manageable pieces. When we follow these principles, our code becomes easier to work with, and the overall quality of our programs improves. Many programmers like to use structured programming because it helps them write code that is easier to understand, test, and change. Fig 1.1 1.1.1 TOP-DOWN ANALYSIS Top-down analysis is an approach in structured programming. It breaks down a problem or task into smaller, manageable sub-problems or modules. The analysis starts at a high-level view and gradually drills down into finer details. It emphasizes decomposing a problem into smaller parts. Each part is addressed individually before integrating them into a complete solution. Benefits of Top-Down Analysis: Simplifies problem-solving by breaking it into manageable pieces. Helps in organizing and structuring code development. Promotes code reusability and modularity. It reduces the complexity of problem solving. Not limited to type of problem Steps in Top-Down Analysis: 1. Start with a high-level problem statement. 2. Break down the problem into smaller sub-problems or modules. 3. Address each sub-problem individually, focusing on its implementation. Gradually integrate the solutions of each sub-problem to create a complete solution 2 23SC1101-Computational Thinking for Structured Design 1.1.2 MODULAR PROGRAMMING Modular programming is a software development approach that emphasizes breaking a program into self-contained, reusable modules. It promotes code organization, maintainability, and reusability by encapsulating related functionality within separate modules. Benefits of Modular Programming: Code Reusability - Modules can be reused in different parts of a program or in future projects. - Saves development time and effort by avoiding code duplication. Improved Maintainability - Modules are self-contained and can be easily maintained and updated without affecting other parts of the program. - Easier debugging, error isolation, and code modifications. Enhances Readability and Comprehension - Modular programs are structured, making it easier to understand the logic and flow of the code. - Encapsulated modules have well-defined interfaces, promoting code readability. Encourages Team Collaboration - Developers can work on different modules simultaneously, fostering collaboration and parallel development. - Each team member can focus on their assigned module without interfering with others. Creating Modular Programs Identify Functionalities and Subtasks - Break down the program into distinct functionalities or subtasks that can been capsulated in separate modules. - Each module should have a specific purpose and be responsible for a well-defined portion of the program's functionality. Define Module Interfaces - Establish clear interfaces for each module, specifying the inputs, outputs, and expected behavior. - This allows modules to interact with each other while maintaining separation and modularity. Implement Modules - Develop individual modules, implementing the logic and functionality within each module. - Modules should have minimal dependencies on other modules, promoting independence and reusability. Integrate Modules - Combine the modular components by linking modules together according to the program's flow. - Ensure proper communication and data exchange between modules through their defined interfaces. 3 23SC1101-Computational Thinking for Structured Design 1.1.3 STRUCTURED CODE Structured code in structured programming refers to well-organized and disciplined code. It follows specific rules and principles to improve readability, maintainability, and efficiency. Principles of Structured Code Single Entry and Single Exit (SESE) - Each code block or subroutine has one entry and one exit point. - Reduces complexity and improves code clarity. Block Structures - Code is organized into logical blocks. - Examples: if-else statements, loops, functions. Control Structures - Control the flow of execution in code. - Examples: if-else statements, loops, switch-case statements. Minimization of GOTO Statements - Avoid excessive use of unstructured GOTO statements. - GOTO statements can make code harder to understand and maintain. - Advantages of Structured Code Readability and Understandability - Well-structured code is easier to read and understand. - Clear organization and indentation improve comprehension. Maintainability and Debugging - Structured code simplifies debugging and error correction. - Well-defined structures facilitate locating and fixing issues. Code Reusability and Modularity - Modular code promotes code reuse and modularity. - Encapsulation of functionality allows for easier integration and maintenance. Scalability and Extensibility - Structured code is easily extendable and adaptable. - Code can be modified without affecting the entire program. Drawbacks of Structured Programming Structured programming has its drawbacks, including limitations in flexibility, handling real- time systems, code duplication, limited code reusability, lack of encapsulation, scalability challenges, and potential inefficiencies in specific scenarios. 4 23SC1101-Computational Thinking for Structured Design E.1.1 Examples: Examples of structured programming concepts in everyday life Homework or Assignment Completion: o Break down assignments into smaller tasks like researching, outlining, and writing. o By tackling each task systematically, students can complete assignments more efficiently. Study Planning: o Divide study material into topics or chapters. o Allocate specific time slots for each topic to study in a structured manner. Planning a Trip or Vacation: o Break down the planning process into steps like researching, booking, and creating an itinerary. o Approach each step systematically for a well-organized trip. Review Questions 1. What is the main objective of structured programming? 2. Name some key features of structured programming. 3. What are the benefits of using top-down analysis in software development? 4. List the steps involved in the top-down analysis approach. 5. Explain the concept of modular programming. 6. How does modular programming promote code organization and reusability? 7. Name some drawbacks or limitations of structured programming. Web Links: 1. https://www.codingninjas.com/codestudio/library/structured-programming 2. https://press.rebus.community/programmingfundamentals/chapter/structure d- programming/ 3. https://www.techtarget.com/searchsoftwarequality/definition/structur ed- programming-modular-programming 5 23SC1101-Computational Thinking for Structured Design 1.2 ALGORITHMS Algorithms are step-by-step procedures designed to solve specific problems and perform tasks efficiently. They are like recipes that guide you through a series of instructions to achieve a desired outcome. How to approach problem solving with algorithms?Devise a Plan: Identify the problem and understand what is being asked. Determine the level of problem-solving required. Decide if you need to translate a provided algorithm into code or apply a known algorithm pattern. If you need to generate an algorithm, keep reading. Identify Inputs and Outputs: Determine what information is given (inputs) and what you need to produce (outputs). Consider any constraints or limitations on the inputs and outputs. Develop a High-Level Algorithm: Create a plan for solving the problem. Start with a high-level algorithm, which is a general outline of the steps you will take. Refine the Algorithm: Break down the high-level algorithm into smaller, more detailed steps. Add any necessary conditions or loops to handle different scenarios. Test the Algorithm: Test the algorithm with different inputs to ensure it produces the correct outputs. Review your code to make sure it makes sense and is logically sound. Properties of an Algorithm Input: An algorithm can work with zero or more inputs. These are the things it needs to know to solve the problem. Output: For every input given, the algorithm must produce one clear answer or result. Definiteness: Each instruction in the algorithm must be easy to understand and follow. There should be no confusion about what to do next. Finiteness: The algorithm will always finish after a limited number of steps. It won't go on forever. Effectiveness: All the steps in the algorithm should be simple enough that you can solve them using basic tools like pencil and paper. 6 23SC1101-Computational Thinking for Structured Design Example of an algorithm Let us consider an example of Automatic teller Machine used for cash Withdrawal system. The following steps should be followed for easy and convenient cash withdrawal. Step-1: SWIPE the ATM card Step-2: Enter your PIN Number. Step-3 Enter the amount to be Withdrawn. Step-4 Withdraw the amount. Step5: Check available balance. Step6: Cancel the Transaction. Step7: STOP. Ex-1: Let us consider an example to find the area of a Circle. The algorithm shows the step-by-step procedure to solve the problem. step1. Start step2. Enter the value of radius r. step3. Define PI=3.14. step4. Find Area=PI*r*r. step5. Display Area step6. Stop Ex-2. Let us consider another example to find a number is positive, negative or zero. The algorithm shows the step-by-step procedure to solve the problem. Step 1. Enter a number from the user end. Step 2. If number is less than zero, then it is a negative integer. Step 3. If number is greater than zero, then it is a positive integer. Step 4. Otherwise, the number is equal to zero. Step 5. STOP Ex-3. Write an algorithm to find the factorial of a number. 1. Start 2. Declare the variable N, FACT, and I. 3. Read the input number N from the user. 4. Set FACT = 1 and I = 1. 5. Repeat the following steps until I 5. How are multi-line comments represented in C? a) // comment b) c) d) { comment } 15 23SC1101-Computational Thinking for Structured Design 2. VARIABLES Constants and variables are invariably used to setup and solve mathematical equations. Variables are the opposite of constants. In C, a variable is a value that can change during program execution. A variable is a distinct memory area that can hold a broad variety of values. The variable name is the nameof the location (an identifier). A variable is distinguished by a distinct name. The value of the variable is the value stored in the location. Variables can be visualized as boxes, each with a name and a value. A variable is a quantity whose value can change during program execution. RULES FOR CONSTRUCTING VARIABLE NAMES Variables should be named so as to distinguish one from the other. The following are the rules for naming a variable. 1. A variable name can be any combination of letters, figures, and underscores (—). 2. A variable may not contain any special characters other than underscore. 3. The variable name's initial character must be a letter. 4. A variable name should not be more than 8 characters long. Some compilers allow variable names to be up to 31 characters long. 5. Uppercase and lowercase letters differ. So the labels sum, Sum, and SUM refer to three distinct variables. Although uppercase characters are permitted, variables are typically expressed in lowercase. 6. No commas or blanks are permitted within a variable name (i.e. no white space). 7. A variable name may not contain a keyword. However, keywords can be included in a variable name.Here are some examples of valid variable names: Here are some instances of invalid variable names: (i) 2root (first character is not a letter) (ii) stud add (Embedded blanks are not allowed) (iii) double (double is a keyword) (iv) x*y (special character is not permitted) (v) city$ (special character is not permitted) It is always advisable to construct variable names in a meaningful way so as to reflect its nature in the program. TYPES OF VARIABLES In general, the types of variables that a computer language can provide are determined by the sorts of constants that it can handle. This is due to the fact that a constant stored in a memory location with a specific type of variable name can only carry that type of constant. A constant stored in a memory location with an integer variable name, for example, must be an integer constant, one stored in a memory location with a real variable name, and one stored in a location with a character variable name must be a character constant. A question naturally 16 23SC1101-Computational Thinking for Structured Design emerges. How does the C compiler distinguish between these variables? The C compiler can distinguish between variable names by making it. DECLARATION OF VARIABLES A declaration links a set of variables to a specified data type. It comprises of a data type, one or more variable names, and a semi-colon at the end. Unlike other programming languages, C requires all variables to be declared before they may be used. The declaration of a variable serves a vital purpose. It informs the C compiler about the type of variable being used. This is due to the fact that different sorts of values necessitate different sized memory locations; the compiler must know the type of data to be stored in order to calculate how much memory to allocate to the variable. Another benefit of variable declaration is that the programmer can use appropriate operators for each type of data. PRIMARY TYPE DECLARATION In memory of the computer, the data types are stored differently. So, you have to tell the computer whether your variable will be an integer, real, or character variable. Each type is represented in a different way inside the machine and needs space of a different size. For this reason, it is necessary to declare the type of all variables before they can appear in executable statements. In C all this is done by using the declarations of the form given below to declare variables, use the following general form type v1, v2,..vn; 3. DATA TYPES Data is used in a program to get information. For example, in a program used to find out the largest of three numbers, the numbers are data and the output which says which number is largest, is information. Constants and variables are fundamental data types. The data type describes the sort of data that variables in a programming language can carry. The "C"language has a large number of data types and supports a variety of data kinds. Each of which may be represented differently in the computer's main memory. The following categories can be used to categorize data types: 1. Primary (or fundamental) data types 2. User-defined data types 3. Derived data types PRIMARY (Basic) DATA TYPES All C compilers support the following four primary (basic) data types: integer constants - written as int character constants - written as char floating point numbers (real numbers) - written as float double precision floating point numbers - written as double Many of them also offer extended data types such as long int and long double 17 23SC1101-Computational Thinking for Structured Design DATA TYPE MODIFIERS (Qualifiers) There is a capability in 'C' to modify the meaning of data types. Modifiers are the keywords that are utilized for this purpose. To more exactly match your individual need, the basic datatypes int, char, float and double can be adjusted using C's type modifiers (qualifiers). Modifiers are classified as follows: signed unsigned short long The default modifier used with int is signed. (A signed number means that it can be positive or negative). The signed modifier is used with char to create a small signed integer. In some implementations, char is unsigned. The long modifier may be applied to int or double. When applied to int, it essentially doubles the length, in bits, of the base type that it modifies. A double data type gives a precision of 14 digits. The double type represents the same data type that float represents, but with a greater precision. To extend the precision further, we may use long double. When long is applied to double it roughly doubles the precision. The short modifier halves the size of an int. That means, it requires half the amount of storage as a regular int number uses. Type Data Type Range Primary Short int -32,768 to 32,767 unsigned short int 0 to 65,535 unsigned int 0 to 4,294,967,295 int -2,147,483,648 to 2,147,483,647 long int -2,147,483,648 to 2,147,483,647 unsigned long int 0 to 4,294,967,295 long long int -(263) to (263)-1 unsigned long long int 0 to 18,446,744,073,709,551,615 float 12 × 10-39 to 3.4 × 1038 double 1.7 × 10-308 to 1.7 × 10308 long double 3.4 x 10-4932 to 1.1 x 104932 char 0 to 255 Void does not refer to any value of any type where type is a C data type and Ili, are the names of the variables. C, a variable declaration is a statement and it must end with a semicolon. This declaration statement is usually written at the beginning of the C program. 3. 3 DECLARATION OF THE INTEGER VARIABLES: For instance, the declaration statements below declare the variables a, b, and c as integers. int a; int b; int c; 18 23SC1101-Computational Thinking for Structured Design By separating the variable names with commas, C allows the definition of several variables of the same type in a single declaration. a, b, and c can therefore also be proclaimed by int a, b, c; If you need to save integer numbers that are either larger than 32.767 or less than 32.768. Use long, long int., or just long. Use short int or just short if you need to store integer values between 32767 and 32767. To declare the variables a and b as a short int and c as a long int. you would write short int a, b; long int c; DECLARATION OF THE FLOATING-POINT VARIABLES: To declare a variable capable of holding real values, you use the keyword float, or double. For example, float rootl, root2; double area; The word double stands for double-precision. It is capable of representing a ' value which is about twice as much precision as that of a float. The precision , refers to the number of decimal places that can be represented. Declaration of the Character Variables: To declare the variables capable of holding character constants, you use the keyword char. For example, char x, y; char c; A variable of type char is 8 bits long and is used to store a single character of information Review Questions 1. Define and identifier and mention the rules to form it. 2. Define an identifier and write two valid identifiers. 3. List any three data types of C language. 4. Describe the different categories of data in C and provide examples. 5. Describe constants. What kinds of constants are there in C? 6. Describe the four fundamental categories of constants in "C" in detail. List the primary data types 7. List and explain the four basic (primary) data types in 'C'. 8. Explain data types in C with examples along with their sizes. 9. Explain the different fundamental data types in C language. 10. Classify the data types in C and explain with example. 11. Explain the data types in C with examples. 12. What is an identifier in C? List the rules for naming an identifier. 19 23SC1101-Computational Thinking for Structured Design Web Links 1. GeeksforGeeks - C Data Types: https://www.geeksforgeeks.org/c-data-types/ 2. Tutorialspoint - C Data Types: https://www.tutorialspoint.com/cprogramming/c_data_types.htm 3. Learn C.org - C Data Types: https://www.learn-c.org/datatypes 4. Programiz - C Variables: https://www.programiz.com/c-programming/c-variables- constants 5. Cprogramming.com - C Data Types and Variables: https://www.cprogramming.com/tutorial/c/lesson2.html 6. C Tutorials Point - Data Types in C: https://www.ctutorialspoint.com/cprogramming/c_data_types.htm 7. StudyTonight - C Variables: https://www.studytonight.com/c/variables-in-c.php 20 23SC1101-Computational Thinking for Structured Design 4. Storage Class Storage class determine the scope, visibility and lifetime of a variable. There are four types of storage class 1. Automatic 2. External 3. Static 4. Register Automatic Variable The variable scopes is within the block are known as automatic or local variable. For example int main(void) { for (int i = 0; i < 5; ++i) { printf("C programming"); } // Error: i is not declared at this point printf("%d", i); return 0; } The above program will display the error for i variable because i is declared inside the for loop , but if we print outside the block, so error is raised External Variable Variable that are declared outside of all functions are identified as external or global variable. for example #include C you can write A > B && A > C. Hierarchy of Logical Operators The logical NOT operator (!) gets priority over the other operators. In comparison to the OR operator (| |), the logical AND operator (&&) has higher precedence. The relational and arithmetic operators have higher precedence than the logical AND and OR operators. Logical Expressions By combining two or more relational expressions with logical operators, logical expressions are created. A compound relational expression is another name for a logical expression. A logical expression,like a relational expression, yields either true (1) or false (0) results, as demonstrated. below Only when both expressions are true does the logical AND operator yield true. If each expression is true, the logical OR operator returns true. When the operand is false, the result of the logical NOToperator (!) is true; otherwise, the result is false. Any nonzero value, not simply 1, is taken to be true inthis situation. Value of the expression Operand 1 Operand 2 Operand 1 && Operand | | ! Operand 1 Operand 2 Operand 2 True (non zero) True (non zero) 1 1 0 True (non zero) False (zero) 0 1 0 False (zero) True (non zero) 0 1 1 False (zero) False (zero) 0 0 1 some examples of logical expressions are: a> 25 && b < 50 i> 10 11 k which are lower than + and —. The operator && is higher than the operator | | The compiler evaluates the logical expression (3 > 4) (4 > 5)) && ((3 < 4) | | (4 > 5)) as follows: Step1: ((3b) { printf(“a is greater”); } printf(“outside if block”); return 0; } Here we see that the program will execute the if block because the condition is true (mean a is greater than b) as well as the outside the if block also print in the output screen. Output: a is greater outside if block In order to segregate the true and false statement in the flow of program we need to add else keyword. IF….ELSE STATEMENT int main() { int a,b; printf(“enter a and b values”); scanf(“%d %d”, &a, &b); if(a>b) { printf(“a is greater”); } else { printf(“b is greater”) 37 COMPUTATIONAL THINKING FOR STRUCTURED DESIGN } printf(“outside if block”); return 0; } Here we see that we are adding else block compare to the previous program so based on the decision program will execute the either if block or else block Output8 4 a is greater outside if blockanother output 14 b is greater outside if block IF ELSE IF… STATEMENT when we have to check and execute the multiple conditions, we have to use if else if statement Example #include int main() { int num; printf("Enter a number between 1 and 5: "); scanf("%d", &num); if (num == 1) { printf("You entered One.\n"); } else if (num == 2) { printf("You entered Two.\n"); } else if (num == 3) { printf("You entered Three.\n"); } else if (num == 4) { printf("You entered Four.\n"); } else if (num == 5) { printf("You entered Five.\n"); } else { printf("Invalid input! Please enter a number between 1 and 5.\n"); } return 0; } 38 COMPUTATIONAL THINKING FOR STRUCTURED DESIGN In this example, the program takes input from the user and uses an `if-else if` ladder to check which number was entered. Depending on the value of `num`, it prints the corresponding message. If the input is not within the range of 1 to 5, it displays an "Invalid input" message. This way, the program handles multiple cases and provides appropriate responses based on the user's input. Here for printing the 5th condition we have to check 4 previous conditions. for that we are going for switch statement. NESTED IF STATEMENT A nested if is an if statement that is the target of another if statement. In other words, it is an if statement that is inside another if statement. int age = 18; if (age >= 18) { if (age

Use Quizgecko on...
Browser
Browser