This document provides information about a course on programming for problem solving in C. It includes the course objectives, which are to give exposure to procedural programming principles in C, introduce computational thinking and develop C programs using basic constructs, and enable students to apply C fundamentals to solve engineering problems. The course outcomes cover various C programming concepts like data types, control structures, arrays, strings, pointers, structures, unions and files. The syllabus is divided into 5 units covering these topics. Textbooks for the course are also listed.
The document provides an introduction to the analysis of algorithms. It discusses key concepts like the definition of an algorithm, properties of algorithms, common computational problems, and basic issues related to algorithms. It also covers algorithm design strategies, fundamental data structures, and the fundamentals of analyzing algorithm efficiency. Examples of algorithms for computing the greatest common divisor and checking for prime numbers are provided to illustrate algorithm design and analysis.
Intermediate representations are used in compilers to represent programs between the source and target languages. Control flow graphs (CFG) are a common intermediate representation that represent a program as a directed graph with basic blocks as nodes and edges showing possible control transfers. CFGs are useful for optimizations and analyzing unreachable code. They are built by dividing a program into basic blocks - sections with no jumps in or out - and connecting them based on the control flow.
This document provides information about programming in C including:
1) An introduction to algorithms, data types, operators, expressions, input/output, and control flow statements in C like if/else and loops.
2) Details about variables, data types, operators, expressions, and program statements in C.
3) Explanations of selection statements like if/else and switch, iteration statements like for, while and do-while loops, and jump statements like break, continue and return in C programming.
This document provides an overview of compilers, including their history, components, and construction. It discusses the need for compilers to translate high-level programming languages into machine-readable code. The key phases of a compiler are described as scanning, parsing, semantic analysis, intermediate code generation, optimization, and code generation. Compiler construction relies on tools like scanner and parser generators.
This document provides an overview of programming language concepts including control structures, statements, functions, and functional programming. It covers topics like selection statements, iteration statements, subprograms, scoping, and paradigms like imperative, object-oriented, declarative, and functional programming. Examples are given in languages like Java, C++, Scheme, Haskell, and SQL.
The document provides an introduction to writing C programs. It discusses the basic structure of a C program, including preprocessor commands, global declarations, functions, and the main function. It then presents a simple example "greeting program" as a first C program. This program only prints a simple message without any preprocessor commands, global declarations, or local definitions, to keep it simple. It also discusses some key aspects of C programs like preprocessor commands starting with # and including header files, as well as the need for functions like main() and its syntax.
Chapter 12 Lecture: GUI Programming, Multithreading, and AnimationNicole Ryan
This chapter discusses event-driven GUI programming, multithreading, and animation. It covers the principles of event-driven programming, user-initiated actions and GUI components, designing graphical user interfaces, developing an event-driven application, threads and multithreading, and creating animation. The document provides details on each topic, including examples and figures to illustrate key concepts.
The document provides an introduction to the analysis of algorithms. It discusses key concepts like the definition of an algorithm, properties of algorithms, common computational problems, and basic issues related to algorithms. It also covers algorithm design strategies, fundamental data structures, and the fundamentals of analyzing algorithm efficiency. Examples of algorithms for computing the greatest common divisor and checking for prime numbers are provided to illustrate algorithm design and analysis.
Intermediate representations are used in compilers to represent programs between the source and target languages. Control flow graphs (CFG) are a common intermediate representation that represent a program as a directed graph with basic blocks as nodes and edges showing possible control transfers. CFGs are useful for optimizations and analyzing unreachable code. They are built by dividing a program into basic blocks - sections with no jumps in or out - and connecting them based on the control flow.
This document provides information about programming in C including:
1) An introduction to algorithms, data types, operators, expressions, input/output, and control flow statements in C like if/else and loops.
2) Details about variables, data types, operators, expressions, and program statements in C.
3) Explanations of selection statements like if/else and switch, iteration statements like for, while and do-while loops, and jump statements like break, continue and return in C programming.
This document provides an overview of compilers, including their history, components, and construction. It discusses the need for compilers to translate high-level programming languages into machine-readable code. The key phases of a compiler are described as scanning, parsing, semantic analysis, intermediate code generation, optimization, and code generation. Compiler construction relies on tools like scanner and parser generators.
This document provides an overview of programming language concepts including control structures, statements, functions, and functional programming. It covers topics like selection statements, iteration statements, subprograms, scoping, and paradigms like imperative, object-oriented, declarative, and functional programming. Examples are given in languages like Java, C++, Scheme, Haskell, and SQL.
The document provides an introduction to writing C programs. It discusses the basic structure of a C program, including preprocessor commands, global declarations, functions, and the main function. It then presents a simple example "greeting program" as a first C program. This program only prints a simple message without any preprocessor commands, global declarations, or local definitions, to keep it simple. It also discusses some key aspects of C programs like preprocessor commands starting with # and including header files, as well as the need for functions like main() and its syntax.
Chapter 12 Lecture: GUI Programming, Multithreading, and AnimationNicole Ryan
This chapter discusses event-driven GUI programming, multithreading, and animation. It covers the principles of event-driven programming, user-initiated actions and GUI components, designing graphical user interfaces, developing an event-driven application, threads and multithreading, and creating animation. The document provides details on each topic, including examples and figures to illustrate key concepts.
This chapter discusses object-oriented programming principles including classes, objects, encapsulation, inheritance, and polymorphism. It describes how to define classes, create objects, and use public and private access modifiers. It also explains how to organize classes and define instance and static methods.
This chapter discusses file handling and applications in programming logic and design. It covers topics such as computer files, the data hierarchy, performing file operations like reading, writing and sorting, control break logic for grouping data, merging files, master and transaction file processing, and random access files. The chapter includes objectives, explanations of key concepts, examples, and figures to illustrate file processing techniques.
The chapter introduces the basic components of a C++ program, including functions, data types, operators, and statements. It discusses simple data types like integers, characters, and floating-point numbers. The chapter also covers arithmetic operators, expressions, and the order of precedence. It explains variable declaration, assignment statements, and how to input and output data. The goal is for readers to understand the basic structure and syntax of a C++ program.
This document discusses system modeling using the Unified Modeling Language (UML). It introduces UML, explaining that UML allows modeling of systems with an object-oriented perspective using various diagram types. It focuses on UML use case diagrams, class diagrams, and object diagrams. It provides examples of how to construct and interpret these diagram types to model systems, classes, objects, and their relationships.
This chapter discusses relational databases and database design. It covers topics such as database fundamentals, creating tables, primary keys, relationships between tables, anomalies and normalization. The goal is to learn how to structure data to reduce redundancy and avoid problems. Specific techniques covered include first normal form to eliminate repeating groups, and second normal form to eliminate partial dependencies.
Programming Logic and Design: Working with DataNicole Ryan
This chapter discusses advanced data handling concepts such as sorting algorithms, multidimensional arrays, and non-sequential data structures. It covers bubble and insertion sort algorithms, how to sort records stored in parallel arrays or as whole structures, and using multidimensional arrays to organize data with multiple indexes. The chapter also explains indexed files and linked lists which allow accessing records in logical order rather than physical storage order through the use of indexes and linked record pointers.
The document discusses code generation and register allocation techniques. It begins by describing register allocation and assignment approaches and their advantages and disadvantages. It then discusses various issues in register allocation like which values reside in registers and which register. It describes register allocation as an NP-hard problem and common heuristics like graph coloring. The rest of the document discusses specific strategies for register allocation like global register allocation, usage counts, and register allocation via graph coloring and interference graphs. It also discusses techniques like register spilling when there are not enough registers.
1) The chapter discusses advanced modularization techniques in programming including methods with parameters, returning values from methods, passing arrays to methods, overloading methods, and recursion.
2) A key concept is implementation hiding which means the internal details of how a method operates are encapsulated and hidden from outside calls to the method.
3) Other important concepts covered include increasing cohesion so methods are functionally related, reducing coupling between methods, and understanding recursion where methods call themselves recursively.
Virtual Instrumentation With LabVIEW is a course that introduces students to LabVIEW and building virtual instruments (VIs). The course covers the components of VIs, creating simple applications, using loops and charts, and performing data acquisition and file input/output. Students will understand LabVIEW programming tools and terms, build interactive front panels, use functions and structures on block diagrams, create subVIs, and log sensor data to files. Exercises include converting temperatures, making a thermometer, using loops, and building a temperature data logger.
The document discusses code optimization techniques in compilers. It covers the following key points:
1. Code optimization aims to improve code performance by replacing high-level constructs with more efficient low-level code while preserving program semantics. It occurs at various compiler phases like source code, intermediate code, and target code.
2. Common optimization techniques include constant folding, propagation, algebraic simplification, strength reduction, copy propagation, and dead code elimination. Control and data flow analysis are required to perform many optimizations.
3. Optimizations can be local within basic blocks, global across blocks, or inter-procedural across procedures. Representations like flow graphs, basic blocks, and DAGs are used to apply optimizations at
This chapter discusses pointers, classes, virtual functions, and abstract classes in C++. Pointers contain the addresses of other variables and can be used to access dynamic memory. The address of and dereferencing operators are used to work with pointers. Classes and structs can have pointer member variables. Virtual functions allow dynamic binding at runtime rather than compile-time. Abstract classes define pure virtual functions that derived classes must implement.
Chapter 11: Object Oriented Programming Part 2Nicole Ryan
This chapter discusses object-oriented programming concepts like constructors, destructors, composition, inheritance, and exception handling. It explains that constructors initialize objects, destructors contain cleanup code, composition allows one class to contain objects of another class, and inheritance enables code reuse through a base class. The chapter provides examples of these concepts using an Employee class and its derived subclasses.
Machine-Independent Optimizations: The Principal Sources of Optimization, Introduction to Data-Flow Analysis, Foundations of Data-Flow Analysis, Constant Propagation, Partial Redundancy Elimination, Loops in Flow Graphs
M.G.Goman et al (1994) - PII package: Brief descriptionProject KRIT
М.Г.Гоман и другие, краткое описание пакета программ интерактивной идентификации PII, 1998 г., Центральный Аэрогидродинамический институт, г. Жуковский, 1998 г.
M.G.Goman et al, "PII - Programs of Interactive Identification. Brief description", Central Aerohydrodynamics Institute (TsAGI), Zhukovsky, Russia, 1998.
The document provides an introduction to algorithms and computer programming. It defines an algorithm as a step-by-step procedure for solving a problem. It also discusses key algorithm concepts like decomposition, abstraction, and problem solving techniques such as divide and conquer. The document presents examples of algorithms using pseudocode and flowcharts. It explains different representations of algorithms and how to trace an algorithm's execution using a trace table.
This document discusses stacks and queues. It describes their properties and common operations like push, pop, enqueue, and dequeue. It provides implementations of stacks and queues as both arrays and linked lists. Specific algorithms covered include using a stack to evaluate postfix expressions, and a non-recursive algorithm to print a linked list backwards using a stack. The key advantages of stacks (LIFO) and queues (FIFO) as data structures are explained.
The document discusses evaluation of expressions and the conversion between infix and postfix notations. It provides examples of:
1) Evaluating expressions using the order of operations and precedence of operators. Scenarios are worked through step-by-step.
2) Converting infix notation expressions to equivalent postfix notation expressions using a stack-based algorithm.
3) Evaluating postfix notation expressions using a stack to pop operands and operators in order.
This document provides an overview of structured programming and problem solving. It discusses computer programming basics like the programming life cycle, algorithms, and control structures. It also covers topics like data types, memory, compilers, flowcharts and programming languages. An example of calculating an employee's weekly wages is presented to illustrate developing an algorithm to solve a problem.
Computer Fundamentals & Intro to C Programming module iAjit Nayak
Introduction to Computers
Evolution of Computers
Computer Generations
Basic Computer Organization
Memory Hierarchy
I/O devices
Computer Software
Planning Computer Program
Introduction to C programming
Structure of C Programming
Datatype
Constant
Variable
Expression
Conditional Expression
Precede
The document discusses algorithms and flowcharts. It defines an algorithm as an ordered sequence of steps to solve a problem and notes that algorithms go through problem solving and implementation phases. Pseudocode is used to develop algorithms, which are then represented visually using flowcharts. The document outlines common flowchart symbols and provides examples of algorithms and corresponding flowcharts to calculate grades, convert between units of length, and calculate an area. It also discusses complexity analysis of algorithms in terms of time and space.
This chapter discusses object-oriented programming principles including classes, objects, encapsulation, inheritance, and polymorphism. It describes how to define classes, create objects, and use public and private access modifiers. It also explains how to organize classes and define instance and static methods.
This chapter discusses file handling and applications in programming logic and design. It covers topics such as computer files, the data hierarchy, performing file operations like reading, writing and sorting, control break logic for grouping data, merging files, master and transaction file processing, and random access files. The chapter includes objectives, explanations of key concepts, examples, and figures to illustrate file processing techniques.
The chapter introduces the basic components of a C++ program, including functions, data types, operators, and statements. It discusses simple data types like integers, characters, and floating-point numbers. The chapter also covers arithmetic operators, expressions, and the order of precedence. It explains variable declaration, assignment statements, and how to input and output data. The goal is for readers to understand the basic structure and syntax of a C++ program.
This document discusses system modeling using the Unified Modeling Language (UML). It introduces UML, explaining that UML allows modeling of systems with an object-oriented perspective using various diagram types. It focuses on UML use case diagrams, class diagrams, and object diagrams. It provides examples of how to construct and interpret these diagram types to model systems, classes, objects, and their relationships.
This chapter discusses relational databases and database design. It covers topics such as database fundamentals, creating tables, primary keys, relationships between tables, anomalies and normalization. The goal is to learn how to structure data to reduce redundancy and avoid problems. Specific techniques covered include first normal form to eliminate repeating groups, and second normal form to eliminate partial dependencies.
Programming Logic and Design: Working with DataNicole Ryan
This chapter discusses advanced data handling concepts such as sorting algorithms, multidimensional arrays, and non-sequential data structures. It covers bubble and insertion sort algorithms, how to sort records stored in parallel arrays or as whole structures, and using multidimensional arrays to organize data with multiple indexes. The chapter also explains indexed files and linked lists which allow accessing records in logical order rather than physical storage order through the use of indexes and linked record pointers.
The document discusses code generation and register allocation techniques. It begins by describing register allocation and assignment approaches and their advantages and disadvantages. It then discusses various issues in register allocation like which values reside in registers and which register. It describes register allocation as an NP-hard problem and common heuristics like graph coloring. The rest of the document discusses specific strategies for register allocation like global register allocation, usage counts, and register allocation via graph coloring and interference graphs. It also discusses techniques like register spilling when there are not enough registers.
1) The chapter discusses advanced modularization techniques in programming including methods with parameters, returning values from methods, passing arrays to methods, overloading methods, and recursion.
2) A key concept is implementation hiding which means the internal details of how a method operates are encapsulated and hidden from outside calls to the method.
3) Other important concepts covered include increasing cohesion so methods are functionally related, reducing coupling between methods, and understanding recursion where methods call themselves recursively.
Virtual Instrumentation With LabVIEW is a course that introduces students to LabVIEW and building virtual instruments (VIs). The course covers the components of VIs, creating simple applications, using loops and charts, and performing data acquisition and file input/output. Students will understand LabVIEW programming tools and terms, build interactive front panels, use functions and structures on block diagrams, create subVIs, and log sensor data to files. Exercises include converting temperatures, making a thermometer, using loops, and building a temperature data logger.
The document discusses code optimization techniques in compilers. It covers the following key points:
1. Code optimization aims to improve code performance by replacing high-level constructs with more efficient low-level code while preserving program semantics. It occurs at various compiler phases like source code, intermediate code, and target code.
2. Common optimization techniques include constant folding, propagation, algebraic simplification, strength reduction, copy propagation, and dead code elimination. Control and data flow analysis are required to perform many optimizations.
3. Optimizations can be local within basic blocks, global across blocks, or inter-procedural across procedures. Representations like flow graphs, basic blocks, and DAGs are used to apply optimizations at
This chapter discusses pointers, classes, virtual functions, and abstract classes in C++. Pointers contain the addresses of other variables and can be used to access dynamic memory. The address of and dereferencing operators are used to work with pointers. Classes and structs can have pointer member variables. Virtual functions allow dynamic binding at runtime rather than compile-time. Abstract classes define pure virtual functions that derived classes must implement.
Chapter 11: Object Oriented Programming Part 2Nicole Ryan
This chapter discusses object-oriented programming concepts like constructors, destructors, composition, inheritance, and exception handling. It explains that constructors initialize objects, destructors contain cleanup code, composition allows one class to contain objects of another class, and inheritance enables code reuse through a base class. The chapter provides examples of these concepts using an Employee class and its derived subclasses.
Machine-Independent Optimizations: The Principal Sources of Optimization, Introduction to Data-Flow Analysis, Foundations of Data-Flow Analysis, Constant Propagation, Partial Redundancy Elimination, Loops in Flow Graphs
M.G.Goman et al (1994) - PII package: Brief descriptionProject KRIT
М.Г.Гоман и другие, краткое описание пакета программ интерактивной идентификации PII, 1998 г., Центральный Аэрогидродинамический институт, г. Жуковский, 1998 г.
M.G.Goman et al, "PII - Programs of Interactive Identification. Brief description", Central Aerohydrodynamics Institute (TsAGI), Zhukovsky, Russia, 1998.
The document provides an introduction to algorithms and computer programming. It defines an algorithm as a step-by-step procedure for solving a problem. It also discusses key algorithm concepts like decomposition, abstraction, and problem solving techniques such as divide and conquer. The document presents examples of algorithms using pseudocode and flowcharts. It explains different representations of algorithms and how to trace an algorithm's execution using a trace table.
This document discusses stacks and queues. It describes their properties and common operations like push, pop, enqueue, and dequeue. It provides implementations of stacks and queues as both arrays and linked lists. Specific algorithms covered include using a stack to evaluate postfix expressions, and a non-recursive algorithm to print a linked list backwards using a stack. The key advantages of stacks (LIFO) and queues (FIFO) as data structures are explained.
The document discusses evaluation of expressions and the conversion between infix and postfix notations. It provides examples of:
1) Evaluating expressions using the order of operations and precedence of operators. Scenarios are worked through step-by-step.
2) Converting infix notation expressions to equivalent postfix notation expressions using a stack-based algorithm.
3) Evaluating postfix notation expressions using a stack to pop operands and operators in order.
This document provides an overview of structured programming and problem solving. It discusses computer programming basics like the programming life cycle, algorithms, and control structures. It also covers topics like data types, memory, compilers, flowcharts and programming languages. An example of calculating an employee's weekly wages is presented to illustrate developing an algorithm to solve a problem.
Computer Fundamentals & Intro to C Programming module iAjit Nayak
Introduction to Computers
Evolution of Computers
Computer Generations
Basic Computer Organization
Memory Hierarchy
I/O devices
Computer Software
Planning Computer Program
Introduction to C programming
Structure of C Programming
Datatype
Constant
Variable
Expression
Conditional Expression
Precede
The document discusses algorithms and flowcharts. It defines an algorithm as an ordered sequence of steps to solve a problem and notes that algorithms go through problem solving and implementation phases. Pseudocode is used to develop algorithms, which are then represented visually using flowcharts. The document outlines common flowchart symbols and provides examples of algorithms and corresponding flowcharts to calculate grades, convert between units of length, and calculate an area. It also discusses complexity analysis of algorithms in terms of time and space.
This document outlines the goals, topics, grading system, and textbook for the CC112 Structured Programming course. The course aims to introduce programming concepts and have students begin writing programs in C. Over the course, students will learn about program structure, data types, control flow statements, functions, arrays, and more. Assessment includes exams, assignments, and a final exam. The recommended textbook is C How To Program by Paul and Harvey Deitel. Lecture 1 provides an overview of computers, programming, and the programming lifecycle. It also gives examples of basic control structures and walks through solving a sample problem to find the area and circumference of a circle.
The document outlines the objectives and contents of the course GE3151 Problem Solving and Python Programming. The objectives include understanding algorithmic problem solving, solving problems using Python conditionals and loops, defining functions, and using data structures like lists, tuples and dictionaries. The course is divided into 5 units which cover topics like computational thinking, Python data types and expressions, control flow and functions, lists and tuples, files and modules. Some illustrative problems mentioned are finding the minimum in a list, solving towers of Hanoi problem, calculating distance between two points, checking voter eligibility, and preparing a retail bill.
object oriented programming part inheritance.pptxurvashipundir04
The document discusses the key concepts in C++ program development including the Program Development Life Cycle (PDLC), variables and data types, operators, control structures, functions, arrays, pointers, identifiers, and keywords. The PDLC follows an iterative process with phases like planning, analysis, design, implementation, testing, deployment and maintenance. Variables store data of built-in types like integers while functions perform tasks. Arrays store multiple elements in contiguous memory and pointers reference the memory locations of other variables. Identifiers name program elements and keywords are reserved words with special meanings.
This document provides an overview of problem solving and Python programming. It discusses computational thinking and problem solving, including identifying computational problems, algorithms, building blocks of algorithms, and illustrative problems. It also discusses algorithmic problem solving techniques like iteration and recursion. Finally, it briefly introduces the course titled "GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING".
The document provides information about the COMP 102 Programming I course for spring 2012. It includes the instructor's contact information, class meeting times, grading criteria, attendance policy, and academic honesty policy. It also lists the topics that will be covered in the course, such as programming concepts, flowcharts, pseudocode, and Java programming.
Introduction to Problem Solving Techniques- PythonPriyankaC44
This document provides an introduction to problem solving techniques and programming languages. It discusses algorithms, flowcharts, pseudocode, and program control structures. It then covers the four generations of programming languages:
1) First generation languages used machine code and assembly languages.
2) Second generation languages included compiled languages like FORTRAN and COBOL.
3) Third generation languages improved on previous generations with features like data abstraction and modular programming.
4) Fourth generation and beyond focused on visual and non-procedural languages.
This document provides an overview of algorithms, flowcharts, hardware, software structure in C programming, and C tokens. It defines algorithms and their properties. It describes flowcharts, their components and examples. It explains hardware components like CPU, memory. It outlines the typical sections of a C program like main(), functions. It defines different tokens in C like keywords, identifiers, operators and provides examples.
The document provides an agenda for an embedded C programming lecture that includes the following topics: definitions of embedded systems and the differences between C for embedded systems and embedded C, the code compilation process and types of errors, code compilation using the command line, and a quick revision of C language syntax. It concludes with assigning a task for students.
This document outlines the objectives and topics covered in the course EC8393 - Fundamentals of Data Structures in C. The course aims to teach students about linear and non-linear data structures and their applications using the C programming language. Key topics include implementing various data structure operations in C, choosing appropriate data structures, and modifying existing or designing new data structures for applications. Assessment includes continuous internal assessments, a university exam, and a minimum 80% attendance requirement.
This document outlines the grading structure, textbooks, and key concepts for an applied programming course in Python. It discusses the following main points:
- Grading is based on quizzes, assignments, a project, class participation, midterm, and final exam.
- The programming process involves 5 main steps: defining the problem, planning the solution, coding, testing, and documenting. Common planning tools include top-down design, algorithms, and flowcharts.
- Programming constructs allow for sequential, conditional, and repetitive control structures to structure program logic and flow. These include if/else statements, loops, and functions.
Machine Learning in Software EngineeringAlaa Hamouda
Software is nowadays a critical component of our lives and everyday-work working activities. However, as the technological infrastructure of the modern world evolves a great challenge arises for developing high quality software systems with increasing size and complexity. Software engineers and researchers are striving to meet this challenge by developing and implementing software engineering methodologies able to deliver software products of high quality, within budget and time constraints. The field of machine learning in software engineering has recently emerged to provide means for addressing, studying, analyzing, and understanding critical software development issues and at the same time to offer mature machine learning techniques such as artificial neural network, Bayesian networks, decision trees, fuzzy logic, genetic algorithms, and rule induction. Machine learning algorithms have proven to be of great practical value to software engineering. Not surprisingly, the field of software engineering turns out to be a fertile ground where many software development tasks could be formulated as learning problems and approached in terms of learning algorithms. In this paper, we first take a look at the characteristics and applicability of some frequently utilized machine learning algorithms. We then present the application of machine learning in the different phases of software engineering that include project planning, requirements analysis, design, implementation, testing and maintenance.
Morris Mano Chapter 08 (Register Transfer Logic).pdfMamunIslam20
The document discusses register transfer logic and instruction codes. It introduces register transfer logic as a way to describe digital systems using registers, operations on data in registers, and control. Instruction codes are discussed as groups of bits that tell a computer to perform operations. Instruction codes are usually divided into parts, with an operation code specifying operations like add, subtract, multiply, etc. Memory is also discussed for storing instruction codes to allow general purpose computers to execute various operations specified by programs.
This document provides an introduction to C++ programming including problem solving skills, software evolution, procedural and object oriented programming concepts, basic C++ programs, operators, header files, conditional statements, loops, functions, pointers, structures and arrays. It discusses topics such as analyzing problems, planning algorithms, coding solutions, evaluating results, procedural and object oriented paradigms, inheritance, polymorphism, flowcharts, basic syntax examples, and more. Various examples are provided to illustrate key concepts in C++.
This document provides an overview of the CSC204 module on computer architecture and assembly language. It covers the module description, assessment criteria, objectives, and content including computer components, the Von Neumann model, CPU organization, and functional units. The key topics are computer architecture, assembly language programming, computer organization, and how computers work at different levels of abstraction from the digital logic level to the user level.
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...shadow0702a
This document serves as a comprehensive step-by-step guide on how to effectively use PyCharm for remote debugging of the Windows Subsystem for Linux (WSL) on a local Windows machine. It meticulously outlines several critical steps in the process, starting with the crucial task of enabling permissions, followed by the installation and configuration of WSL.
The guide then proceeds to explain how to set up the SSH service within the WSL environment, an integral part of the process. Alongside this, it also provides detailed instructions on how to modify the inbound rules of the Windows firewall to facilitate the process, ensuring that there are no connectivity issues that could potentially hinder the debugging process.
The document further emphasizes on the importance of checking the connection between the Windows and WSL environments, providing instructions on how to ensure that the connection is optimal and ready for remote debugging.
It also offers an in-depth guide on how to configure the WSL interpreter and files within the PyCharm environment. This is essential for ensuring that the debugging process is set up correctly and that the program can be run effectively within the WSL terminal.
Additionally, the document provides guidance on how to set up breakpoints for debugging, a fundamental aspect of the debugging process which allows the developer to stop the execution of their code at certain points and inspect their program at those stages.
Finally, the document concludes by providing a link to a reference blog. This blog offers additional information and guidance on configuring the remote Python interpreter in PyCharm, providing the reader with a well-rounded understanding of the process.
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
Embedded machine learning-based road conditions and driving behavior monitoringIJECEIAES
Car accident rates have increased in recent years, resulting in losses in human lives, properties, and other financial costs. An embedded machine learning-based system is developed to address this critical issue. The system can monitor road conditions, detect driving patterns, and identify aggressive driving behaviors. The system is based on neural networks trained on a comprehensive dataset of driving events, driving styles, and road conditions. The system effectively detects potential risks and helps mitigate the frequency and impact of accidents. The primary goal is to ensure the safety of drivers and vehicles. Collecting data involved gathering information on three key road events: normal street and normal drive, speed bumps, circular yellow speed bumps, and three aggressive driving actions: sudden start, sudden stop, and sudden entry. The gathered data is processed and analyzed using a machine learning system designed for limited power and memory devices. The developed system resulted in 91.9% accuracy, 93.6% precision, and 92% recall. The achieved inference time on an Arduino Nano 33 BLE Sense with a 32-bit CPU running at 64 MHz is 34 ms and requires 2.6 kB peak RAM and 139.9 kB program flash memory, making it suitable for resource-constrained embedded systems.
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Sinan KOZAK
Sinan from the Delivery Hero mobile infrastructure engineering team shares a deep dive into performance acceleration with Gradle build cache optimizations. Sinan shares their journey into solving complex build-cache problems that affect Gradle builds. By understanding the challenges and solutions found in our journey, we aim to demonstrate the possibilities for faster builds. The case study reveals how overlapping outputs and cache misconfigurations led to significant increases in build times, especially as the project scaled up with numerous modules using Paparazzi tests. The journey from diagnosing to defeating cache issues offers invaluable lessons on maintaining cache integrity without sacrificing functionality.
1. VELAMMAL ENGINEERING COLLEGE
An Autonomous Institution, Affiliated to Anna University Chennai, &
Approved by AICTE Delhi
Course Title : PROGRAMMING FOR
PROBLEM SOLVING IN
C
Course Code : 19CS101T
1
UNIT I
2. COURSE OBJECTIVES
• This course aims at giving adequate exposure to students on the
principles of procedural programming language
• The course is intended to introduce the students to computational
thinking and make the students develop C Programs using basic
programming constructs.
• The course will enable the students to apply the fundamentals of C
programming to solve Engineering problems.
UNIT I 2
3. COURSE OUTCOMES
CO. No. Course Outcome
CO 1 Acquire knowledge on different problem solving techniques.
CO 2 Use appropriate data types and control structures for solving a given problem.
CO 3 Execute different array and string operations.
CO 4 Experiment with the usage of pointers and functions.
CO 5 Organize data using structures and unions.
CO 6 Demonstrate data persistency using files.
UNIT I 3
4. SYLLABUS
• UNIT-I INTRODUCTION TO PROBLEM SOLVING AND C PROGRAMMING
• Algorithms, building blocks of algorithms (Statements, State,
Control flow, Functions), notation (Pseudo code, Flow Chart,
Programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion).
Introduction to C Programming – Data types - Operators and
Expressions – Data Input and Output – Decision making and Looping
Statements.
UNIT I 4
5. SYLLABUS
• UNIT-II ARRAYS AND STRINGS
• Defining an array – Processing an Single and Two Dimensional array –
Multidimensional Arrays, Character Arithmetic – Defining a string – NULL
character – Initialization of Strings – Reading and Writing Strings – Processing
Strings –Searching and Sorting of Strings.
UNIT I 5
6. SYLLABUS
• UNIT-III FUNCTIONS AND STORAGE CLASSES
• Defining a function – Accessing a function – Function prototypes – Passing
arguments to a function – Passing arrays to functions – Function with string -
Recursion – Storage classes
UNIT I 6
7. SYLLABUS
• UNIT-IV POINTERS
• Pointer Fundamentals – Pointer Declaration – Passing Pointers to a Function –
Pointers and one dimensional arrays – operations on pointers– Dynamic memory
allocation.
UNIT I 7
8. SYLLABUS
• UNIT-V STRUCTURES, UNIONS AND FILES
• Structures and Unions: Defining a Structure – Processing a Structure – User
defined data types (Typedef) – Unions, Files: Opening and Closing a Data File –
Reading and writing a data file – Processing a data file – Unformatted data files –
Concept of binary files – Accessing a file randomly using fseek() & ftell().
UNIT I 8
9. TEXT BOOKS
• Sumitabha Das, “Computer Fundamentals & C Programming”, Mc
Fraw Hill, 2018.
• Pradip Dey and Manas Ghosh, “Programming in C”, Second Edition,
Oxford University Press, 2011.
UNIT I 9
10. Introduction
• Computer
• Device capable of performing computations and making logical decisions
• Computers process data under the control of sets of instructions called
computer programs
UNIT I 10
11. Computer Organization
• Five logical units in every computer:
• Input unit
• Obtains information from input devices (keyboard, mouse)
• Output unit
• Outputs information (to screen, to printer, to control other devices)
• Memory unit
• Rapid access, low capacity, stores input information
• Arithmetic and logic unit (ALU)
• Performs arithmetic calculations and logic decisions
• Control unit
• Supervises and coordinates the various components of the computer
13. Operation Steps:
• A : The type of operation that the ALU needs to perform is determined by signals from the control unit .
• B: The data can come either from the input unit, or
• C: from the memory unit.
• D: Results of the operation can either be transferred back to the memory unit or
• E: directly to the output unit .
• F : Control signal (a read or a write operation).
• G : A location in memory
• H : Input to memory data lines when the control signal J is enabled.
• I : Memory to the output unit when the control signal L is enabled.
• The instruction word(s) stored at the memory location specified by the address is then transferred to the control unit (K).
14. Storage Capacities
• bit – smallest capacity (0 or 1)
• nibble = 4 bits
• byte = 2 nibbles = 8 bits
• storage for one character
• 1 kilobyte (KB) = 1024 bytes
• 1 megabyte (MB) = 1024 KB
• 1 gigabyte (GB) = 1024 MB
15. Programming Language : Definition
• A vocabulary and set of grammatical rules for instructing a computer
to perform specific tasks.
• Programming – the creation of an ordered set of instructions to solve
a problem with a computer.
16. Evolution of Programming languages
• First Generation : Machine languages
• Strings of numbers giving machine specific instructions
• Example:
+1300042774
+1400593419
+1200274027
• Second Generation : Assembly languages
• English-like abbreviations representing elementary computer operations (translated via assemblers)
• Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY
• Third Generation : High-level languages
• Codes similar to everyday English
• Use mathematical notations (translated via compilers)
• Example: grossPay = basePay + overTimePay
18. UNIT-I INTRODUCTION TO PROBLEM
SOLVING AND C PROGRAMMING
Algorithms, building blocks of algorithms (Statements, State, Control flow,
Functions), notation (Pseudo code, Flow Chart, Programming language),
algorithmic problem solving, simple strategies for developing algorithms
(iteration, recursion). Introduction to C Programming – Data types - Operators
and Expressions – Data Input and Output – Decision making and Looping
Statements.
UNIT I 18
19. What is an Algorithm?
• Computer scientist Niklaus Wirth stated that
Program = Algorithms + Data
• Algorithm-
⮚part of the plan for the computer program
⮚
UNIT I 19
20. Example of an algorithm-step form :
Making a pot of Tea
1. If the kettle does not contain water, then fill the kettle.
2. Plug the kettle into the power point and switch it on.
3. If the teapot is not empty, then empty the teapot.
4. Place tea leaves in the teapot.
5. If the water in the kettle is not boiling, then go to step 5.
6. Switch off the kettle.
7. Pour water from the kettle into the teapot.
UNIT I 20
21. BUILDING BLOCK OF ALGORITHMS
Statements- A single action in a computer.
⮚ input data-information given to the program
⮚ process data-perform operation on a given input
⮚ output data-processed result
State
⮚Transition from one process to another process under specified condition within a time
UNIT I 21
22. BUILDING BLOCK OF ALGORITHMS
Control flow - Executing the individual statements in a given order
1. Sequence(Process)
2. Decision(Selection)
3. Repetition(Iteration or looping)
UNIT I 22
23. BUILDING BLOCK OF ALGORITHMS
Control flow
1. Sequence (Process)
▪ Each step or process in the algorithm is executed in
the specified order.
▪ All the instructions are executed one after another is
called sequence execution
Example
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
UNIT I 23
24. BUILDING BLOCK OF ALGORITHMS
Control flow
2.Decision(Selection)
▪ A selection statement causes the program control
to be transferred to a specific part of the program
based upon the condition.
▪ Outcome of a decision is either true or false
▪ Outcome is based on some conditions
▪ Decision Constructs: if ... then,
if ... then ... else ...
General form:
if proposition then process
(or)
if proposition
then process1
else process2
UNIT I 24
Example
Algorithm to check whether eligible to
vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18
print “Eligible to vote”
Step 4: else
print “Not eligible to vote”
Step 5: Stop
25. BUILDING BLOCK OF ALGORITHMS
Control flow
3. Repetition(Iteration or looping)
• Iterate or repeat a process or sequence of
processes until some condition becomes
true.
▪ Repetition Constructs: repeat loop
while loop
if.. then .. goto .. loop.
General form1 : Repeat loop
Repeat
Process1
Process2
……………
…………..
ProcessN
Until proposition
UNIT I 25
Example using repeat loop
Repeat
Fill water in kettle
Until kettle is full
Drawback: If the
kettle is already
full at the start of
the Repeat loop,
then filling more
water will lead to
an overflow
26. BUILDING BLOCK OF ALGORITHMS
General form 2 : while loop
while proposition
begin
Process 1
Process 2
………..
………...
Process N
end
UNIT I 26
Example for repetition using while
loop
while kettle is not full
fill water in kettle
Note :
1. Finds out whether some
condition is true before repeating a
process or a sequence
of processes.
2. If the condition is false, the
process or the sequence of
processes is not executed
27. BUILDING BLOCK OF ALGORITHMS
General form 3 : if .. then goto ..
Process1
Process2
……….
……….
ProcessN
if proposition then goto Process1
UNIT I 27
Example for repetition using
if .. then goto ..
In the kettle example, this construct
would be implemented as follows:
1. Fill some water in kettle
2. if kettle not full then goto 1
Note : used to repeat a process
or a sequence of processes until the
given proposition is false.
28. BUILDING BLOCK OF ALGORITHMS
Subroutines
• Method, procedure or function
• Sub program which consists of block of code(set of instructions) that
performs a particular task.
• For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.
• Can be called many times with a “CALL” Statement
UNIT I 28
29. BUILDING BLOCK OF ALGORITHMS
Subroutines-
Advantages:
• Reduction in line of code
• Code reuse
• Better readability
• Information hiding
• Easy to debug and test
• Improved maintainability
Disadvantages:
• Requires computational overhead
UNIT I 29
30. Questions
• Define an algorithm.
• Building blocks of an algorithm.
• Define subroutine or function.
UNIT I 30
33. Representation of Algorithm
• Step-form
⮚ Stated with written statements
⮚ Each statement solves a part of the problem and these together complete the solution
⮚ uses just normal language
• Pseudo-code
⮚ Also written form representation of the algorithm
⮚ Uses a restricted vocabulary (therefore precise)
• Flowchart & Nassi-Schneiderman
⮚ Graphically oriented representation forms.
⮚ Use symbols and language to represent sequence, decision, and repetition actions
UNIT I 33
34. What are data and variables ?
1.Data is a symbolic representation of value.
numeric data, e.g., 12, 11.45, 901, etc.
alphabetic or character data such as ‘A’, ‘Z’, or ‘This is alphabetic’
logical data, that is, propositions with true/false values
2. A variable, which has a name, is a container for a value that may vary during
the execution of the program.
Variable names are shorter than the original name(Ex:kettle_empty)
UNIT I 34
35. Ex 1: Write the algorithm for finding the sum of
any two numbers
Solution: Let the two variables be A and B and let their sum be equal to C.
Then, the desired algorithm is given as follows:
1. START
2. PRINT “ENTER TWO NUMBERS”
3. INPUT A, B
4. C A+B
5. PRINT C
6. STOP
UNIT I 35
36. Ex 2:Construct the algorithm for interchanging the numeric values of two
variables.
Solution :Let the two variables be A and B. Consider C to be a third variable that is used to
store the value of one of the variables during the process of interchanging the values.
1. START
2. PRINT “ENTER THE VALUE OF A & B”
3. INPUT A, B
4. C A
5. A B
6. B C
7. PRINT A, B
8. END
UNIT I 36
37. Ex 3:Write an algorithm that compares two numbers and prints
either the message identifying the greater number or the message
stating that both numbers are equal.
1. START
2. PRINT “ENTER TWO NUMBERS”
3. INPUT A, B
4. IF A > B THEN
5. PRINT “A IS GREATER THAN B”
6. IF B > A THEN
7. PRINT “B IS GREATER THAN A”
8. IF A = B THEN
9. PRINT “BOTH ARE EQUAL”
10.
UNIT I 37
38. Ex 4:Write an algorithm for calculating the
factorial of a given number N.
1. START
2. PRINT “ENTER THE NUMBER”
3. INPUT N
4. F 1
5. C 1
6. WHILE C <= N
7. BEGIN
8. F F * C
9. C C + 1
10. END
11. PRINT F
UNIT I 38
39. FLOWCHARTS
It is a graphical representation of a computer
program in relation to its sequence of
UNIT I 39
40. FLOWCHARTS
• Program design tool
• Developed in the early stages of formulating computer solutions.
• Set of various standard shaped boxes that are interconnected by flow
lines.
• Flow lines have arrows to indicate the direction of the flow of control
between the boxes.
• Besides flowlines, connector symbols that are used to indicate that the
flow of control continues elsewhere, for example, the next page.
• Better documentation of a complex program
UNIT I 40
42. ADVANTAGES
• Communication
• Effective analysis
• Proper documentation
• Efficient coding
• Proper debugging:
• Flowcharts help in the debugging process.
• Efficient program maintenance: UNIT I 42
45. FLOWCHART TO FIND SUM OF TWO NUMBERS(SEQUENCE)
START
STOP
COMPUTE
C A+B
PRINT
C
UNIT I 45
INPUT
A,B
46. FLOWCHART TO FIND MAXIMUM OF TWO
NUMBERS(DECISION)
START
IS
A>B
UNIT I 46
READ A,B
PRINT A PRINT B
STOP
Y N
DECLARE
VARIABLES A,B
47. FLOWCHART TO FIND SUM OF FIRST N 50 NUMBERS
.
START
STOP
SUM=0
N=0
N=N+1
SUM=SUM+N
IS
N=50?
PRINT
N
Y
N
UNIT I 47
48. PSEUDOCODE
Pseudocode is an informal way of programming
description that does not require any strict
programming language syntax.
UNIT I 48
49. Guidelines for writing pseudo code:
❖ Write one statement per line
❖ Capitalize initial keyword
❖ Indent to hierarchy
❖ End multiline structure
❖ Keep statements language independent
UNIT I 49
50. Common keywords used in pseudocode
1. //: This keyword used to represent a comment.
2. BEGIN,END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.▪
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.
UNIT I 50
52. • Solution:
• BEGIN
• INPUT a,b
• ADD c=a+b
• PRINT c
• END
EXAMPLE: PSEUDO CODE
UNIT I 52
53. Write a pseudocode for the following:
• Greatest of two numbers
• Factorial of a given number
UNIT I 53
54. STRATEGY FOR DESIGNING
ALGORITHM
• INVESTIGATION STEP
Determines the requirements for the problem solution
• TOP DEVELOPMENT STEP
• plans out the way the solution has to be done by breaking it into smaller
modules and establishing a logical connection among them.
• STEPWISE REFINEMENT
• decomposes the modules, defines the procedure in it and verifies the
correctness of it.
UNIT I 54
55. RECURSION
A recursive function is one that calls itself directly
or indirectly to solve a smaller version of its task
until a final call which does not require a self-
call.
UNIT I 55
56. RECURSION
• Top–down approach to problem solving
• Divides the problem into pieces or selects one key step, postponing the rest.
• Decomposition into smaller problems of same type
• Recursive calls must diminish problem size
• Necessity of base case(An instance of a problem the solution of which requires no further recursive calls)
• Base case must be reached
• It acts as a terminating condition. Without an explicitly defined base case, a recursive function would call itself
indefinitely.
• It is the building block to the complete solution.
UNIT I 56
57. SYNTAX FOR RECURSION
if(this is a base case) then
solve it directly
else
redefine the problem using recursion.
UNIT I 57
58. Questions
• What is mean by flowchart?
• What is mean by pseudocode?
UNIT I 58
60. What is C?
•Programming language
•Written by Dennis Ritchie
•Developed at AT & T’s Bell Lab
•Country : USA
•Year :
61. Features of C
•General purpose language
•Portability
•Code re-usability & ability to customize and extend
•Limited number of keyword
•Structured language
62. What is C used for?
Systems programming:
• OSes, like Linux
• microcontrollers: automobiles and airplanes
• embedded processors: phones, portable electronics, etc.
• DSP processors: digital audio and TV systems
63. Version of C:
Year Version
1972 Invention of C
1978 K & R C
1983 ANSI established a committee to standardize the C language
1989 ANSI C / C89
1990 ANSI or ISO C90
1999 ANSI or ISO C99
2011 *ANSI or ISO C11
UNIT I 63
*ANSI (American National Standard Institute)
ISO (International Organization for standardization)
64. Writing C programs
• Save c program with .c extension (Ex: add.c)
• C program must be created in two stages:
• Run your program
Source Code : the program is written in the form of text files
Note: A computer cannot execute source code directly (aaa.c)
Executable code (Object file) : the completed source code is processed with a compiler.
(aaa.obj)
Stage 1
Stage 2
Compiler
a=b+c;
101001110…
65. Errors
• Errors are mistakes that programmers make in their code.
• Two kinds of errors:
• Compile-time errors
• caught by compiler
• Syntax errors
• Ex: missing semicolon
• run-time errors
• Errors that occur in a compiled and running program
• Ex: division by zero error
Syntax refers to the protocols to be
followed while writing a program.
66. Questions
• Author of C programming language?
• What is a compiler?
• What are the kinds of error that can occur in a program?
• If you had some C source code that you wished to call “addition”,
under what name would you save it?
• What would be the name of the executable file for the program in the
last question?
67. KEY WORDS
• ASCII : It is a standard code for representing characters as numbers that is used on most microcomputers,
computer terminals, and printers. In addition to printable characters, the ASCII code includes control characters to
indicate carriage return, backspace, etc. Ex: A -> 65 -> 0100 0001
• Assembler :The assembler creates the object code.
• Associativity :The associativity of operators determines the order in which operators of equal precedence are
evaluated when they occur in the same expression. Most operators have a left-to-right associativity, but some have
right-to-left associativity. Ex: 10 + 20 * 30
100 / 10 * 10
UNIT I 67
69. KEY WORDS
• Compiler: A system software that translates the source code to assembly code.
• Constant :A constant is an entity that doesn’t change. Ex: pi = 3.14
• Data type: The type, or data type, of a variable determines a set of values that the
variable might take and a set of operations that can be applied to those values.
• Ex: integer, float, char
• Debugger: A debugger is a program that enables you to run another program step-
by-step and examine the value of that program’s variables.
• Identifier: An identifier is a symbolic name used in a program and defined by the
programmer. Ex: mark = 90
UNIT I 69
70. KEY WORDS
• IDE :An Integrated Development Environment or IDE is an editor which offers a
complete environment for writing, developing, modifying, deploying, testing, and
debugging the programs. Ex: Dec
• Identifier: An identifier or name is a sequence of characters invented by the programmer
to identify or name a specific object.
• Keyword: Keywords are explicitly reserved words that have a strict meaning as
individual tokens to the compiler. They cannot be redefined or used in other contexts. Ex:
if, else, for, while, …
UNIT I 70
71. KEY WORDS
• Linker: If a source file references library functions or functions defined in other
source files, the linker combines these functions to create an executable file.
• Precedence :The precedence of operators determines the order in which different
operators are evaluated when they occur in the same expression. Operators of
higher precedence are applied before operators of lower precedence.
• Pre processor :The C pre processor is used to modify the source program before
compilation according to the pre processor directives specified.
Ex: #include<stdio.h>
UNIT I 71
72. KEY WORDS
• Lvalue: An lvalue is an expression to which a value can be assigned. Ex: x = y + z
• Rvalue: An rvalue can be defined as an expression that can be assigned to an lvalue.
• Token: A token is one or more symbols understood by the compiler that help it
interpret your code.
• Word: A word is the natural unit of memory for a given computer design. The word
size is the computer’s preferred size for moving units of information around;
technically it’s the width of the processor’s registers. (32 or 64)
UNIT I 72
73. KEY WORDS
• Whitespace Space, newline, tab character and comment are collectively known as whitespace.
• Variable: A variable is a named memory location. Every variable has a type, which defines the possible
values that the variable can take, and an identifier, which is the name by which the variable is referred.
Ex: int mark = 90;
• Bug:Any type of error in a program is known as bug. There are three types of errors that may occur:
⮚ Compile errors,
⮚ Linking errors,
⮚ Runtime errors
UNIT I 73
74. Steps in learning in C
• Steps in learning English language:
• Steps in learning C:
Alphabets Words Sentences Paragraphs
Alphabets
Digits
Special Symbols
Constants
Variables
Keywords
Instructions Program
75. C Character Set
• A character denotes any alphabet, digit, or special symbol used to
represent information.
76. Constants
• A constant is an entity that does not change.
• Examples:
• 100
• 3.14
• ‘A’
• “welcome”
77. Variables
• A variable is an entity that may change during execution of the
program.
• Example:
• X=10;
•
Address Data Name of the
variable
100
101
102
103
104
….
Address Data Name of the
variable
100
101
102 10 X
103
104
….
Address Data Name of the
variable
100
101
102 20 X
103
104
….
78. Variable names
Naming rules:
• Variable names can contain letters, digits and _
• Variable names should start with letters or underscore.
• Keywords (e.g.,for, while etc.) cannot be used as variable names
• Variable names are case sensitive. int x; int X declares two different variables.
• Total$marks – incorrect
• Total_marks - correct
79. Declaration of variables
• Must declare variables before use
• Syntax:
Example:
int mark;
char grade;
flat average;
int a, b, c;
datatype_name variable_name1, variable_name2,…,variable_name n;
80. Initialization
• Variables initialized via assignment operator
• Syntax:
Example:
int mark = 80;
char grade = ‘A’;
flat average = 75.8;
int a, b, c=10, d=5;
datatype_name variable_name = value;
81. Keywords
• Keywords are the words whose meaning has already been explained to
the C compiler.
• 32 keywords available in C.
• Reserved words
84. Basic Structure of C program
1. /*
2. Documentation section
3. C programming structure
4. Author: XYZ
5. */
6. #include <stdio.h> // Link section
7. int subtract = 0; // Global declaration, definition section
8. void main () // Main function
9. {
10. int a=20, b=10; // Declaration part
11. subtract= a – b; // Executable part
12. printf ("Subtraction of the two numbers : %d n", subtract);
13. }
88. • The header files, usually incorporate data types, function declarations and macros,
resolves this issue. The file with .h extension is called header file, because it’s usually
included at the head of a program.
• Every C compiler that conforms to the international standard (ISO/IEC 9899) for the
language will have a set of standard header files supplied with it.
• The header files primarily contain declarations relating to standard library functions
and macros that are available with C.
Header File
UNIT I 88
89. • During compilation, the compilers perform type checking to ensure that the calls to
the library and other user-defined functions are correct. This form of checking helps
to ensure the semantic correctness of the program.
STANDARD HEADER FILES
UNIT I 89
90. • main() is a user defined function. main() is the first function in the program which gets called when the
program executes. The start up code c calls main() function. We can’t change the name of the main()
function.
• main() is must.
• According to ANSI/ISO/IEC 9899:1990 International Standard for C, the function called at program start
up is named main. The implementation declares no prototype for this function. It can be defined with no
parameters:
int main(void) { /* ... */ }
• or with two parameters (referred to here as argc and argv) :
• int main(int argc, char *argv[ ]) { /* ... */ }
PHILOSOPHY : MAIN
UNIT I 90
92. • Declaration means describing the type of a data object to the compiler but not allocating any
space for it.
⮚ A declaration announces the properties of a data object or a function. If a variable or function is declared
and then later make reference to it with data objects that do not match the types in the declaration, the
compiler will complain.
⮚ data_type variable_name_1,
• Definition means declaration of a data object and also allocating space to hold the data object.
⮚ A definition, on the other hand, actually sets aside storage space (in the case of a data object) or
indicates the sequence of statements to be carried out (in the case of a function).
DECLARATION & DEFINITION
UNIT I 92
93. • All variables have three important attributes:
⮚A data type that is established when the variable is defined, e.g., integer, real,
character. Once defined , the type of a C variable cannot be changed.
⮚ A name of the variable.
⮚ A value that can be changed by assigning a new value to the variable. The
kind of values a variable can assume depends on its type. For example, an
integer variable can only take integer values, e.g., 2, 100, –12.
VARIABLES:ATTRIBUTES
UNIT I 93
96. Primary Data Types in C
• int: It is responsible for storing integers. In general, int data type occupies 4 bytes of memory
when working with a 32-bit compiler.
Ex: 1324, +500
• float: It is responsible for storing fractions or digits up to 7 decimal places. It occupies 4 bytes of
memory. Ex: 35.78
• char: It can be used to store a set of all characters which may include alphabets, numbers and
special characters. It occupies 1 byte of memory. Ex: ‘A’, ‘a’
• double: It is responsible for storing fractions or digits up to 15-16 decimal places. It occupies 8
bytes of memory. Ex: 4.1e8
• void (Null) data type: It indicates zero or no return value. It is generally used to assign the null
value while declaring a function.
97. • 16 bit computer:
• 32 bit computer:
BASIC DATA TYPES:SIZE & RANGE
UNIT I 97
98. • In addition, C has four type specifiers or modifiers and three type qualifiers.
⮚Each of these type modifiers can be applied to the base type int.
⮚The modifiers signed and unsigned can also be applied to the base type char.
⮚In addition, long can be applied to double.
⮚When the base type is omitted from a declaration, int is assumed.
⮚The type void does not have these modifiers.
SPECIFIER OR MODIFIERS
UNIT I 98
99. Questions
• What are the basic data types in C?
• How many bytes are occupied by basic data types in C?
UNIT I 99
100. • The specifiers and qualifiers for the data types can be broadly classified into three types:
⮚ Size specifiers— short and long
⮚ Sign specifiers— signed and unsigned
⮚ Type qualifiers— const, volatile and restrict
SPECIFIERS : DATA TYPES
UNIT I 100
102. • A statement is a syntactic constructions that performs an action when a program is
executed. All C program statements are terminated with a semi-colon (;).
PROGRAM STATEMENTS
UNIT I 102
103. • Declaration :It is a program statement that serves to communicate to the language
translator information about the name and type of the data objects needed during
program execution. Ex: int x;
• Expression statement: It is the simplest kind of statement which is no more than an
expression followed by a semicolon. An expression is a sequence of operators and
operands that specifies computation of a value . Example : x = 10 + 20;
• Compound statement is a sequence of statements that may be treated as a single
statement in the construction of larger statements.
• Labelled statements can be used to mark any statement so that control may be
transferred to the statement by switch statement.
Cont.
UNIT I 103
104. • Control statement is a statement whose execution results in a choice being made as
to which of two or more paths should be followed. In other words, the control
statements determine the ‘flow of control’ in a program.
⮚Selection statements allow a program to select a particular execution path from a set of one
or more alternatives. Various forms of the if..else statement belong to this category.
⮚Iteration statements are used to execute a group of one or more statements repeatedly. “while,
for, and do..while” statements falls under this group.
⮚Jump statements cause an unconditional jump to some other place in the program. Goto
statement falls in this group
Cont.
UNIT I 104
105. • Storing unsigned integers is a straightforward process . The number is changed to the
corresponding binary form & the binary representation is stored.
HOW THE INTEGERS ARE STORED IN
MEMORY
UNIT I 105
106. • For signed integer types, the bits of the object representation shall be divided into three
groups: value bits, padding bits, and the sign bit. There need not be any padding bits;
there shall be exactly one sign bit (if there are M value bits in the signed type and N in the
unsigned type, then M ≤ N). If the sign bit is zero, it shall not affect the resulting value. If
the sign bit is one, the value shall be modified in one of the following ways:
⮚ the corresponding value with sign bit 0 is negated(sign and magnitude);
⮚ the sign bit has the value −(2N) (2’s complement);
⮚ the sign bit has the value −(2N − 1) (1’s complement).
HOW THE INTEGERS ARE STORED IN
MEMORY
UNIT I 106
108. • Compiler vendors (like Microsoft, Borland ,etc.) provide their own keywords apart from
the ones mentioned below. These include extended keywords like near, far, asm, etc.
KEY WORDS
UNIT I 108
109. • A constant is an explicit data value written by the programmer. Thus, it is a value
known to the compiler at compiling time.
• In ANSI C, a decimal integer constant is treated as an unsigned long if its
magnitude exceeds that of the signed long. An octal or hexadecimal integer that
exceeds the limit of int is taken to be unsigned; if it exceeds this limit, it is taken to
be long; and if it exceeds this limit, it is treated as an unsigned long.
• An integer constant is regarded as unsigned if its value is followed by the letter
‘u’ or ‘U’, e.g.,0x9999u; it is regarded as unsigned long if its value is followed by
CONSTANT
UNIT I 109
114. • There are three types of arithmetic operators in C:binary,unary, and ternary.
• Binary operators: C provides five basic arithmetic binary operators.
⮚Arithmetic binary operators:
ARITHMETIC OPERATOR
UNIT I 114
115. • Unary operators: The unary ‘–’ operator negates the value of its operand (clearly, a
signed number). A numeric constant is assumed positive unless it is preceded by the
negative operator. That is, there is no unary ‘+’. It is implicit. Remember that -x does not
change the value of x at the location where it permanently resides in memory.
• Unary increment and decrement operators ‘++’ and ‘--’ operators increment or
decrement the value in a variable by 1.
• Basic rules for using ++ and – – operators:
⮚The operand must be a variable but not a constant or an expression.
⮚ The operator ++ and -- may precede or succeed the operand.
UNARY OPERATION
UNIT I 115
116. Postfix:
• (a) x = a++;
⮚ First action: store value of a in memory location for variable x.
⮚ Second action: increment value of a by 1 and store result in memory location for variable a.
• (b) y = b––;
⮚ First action: put value of b in memory location for variable y.
⮚ Second action: decrement value of b by 1 and put result in memory location for variable b.
POSTFIX
UNIT I 116
117. Prefix :
• (a) x = ++a;
⮚ First action: increment value of a by 1 and store result in memory location for variable a.
⮚ Second action: store value of a in memory location for variable x.
• (b) y = ––b;
⮚ First action: decrement value of b by 1 and put result in memory location for variable b.
⮚ Second action: put value of b in memory location for variable y
PREFIX
UNIT I 117
118. • C provides six relational operators for comparing numeric quantities. Relational operators evaluate to 1, representing the true outcome, or 0, representing the
false outcome.
RELATIONAL OPERATORS
UNIT I 118
119. • C provides three logical operators for forming logical expressions. Like the
relational operators, logical operators evaluate to 1 or 0.
⮚Logical negation is a unary operator that negates the logical value of its single operand. If its
operand is non-zero, it produces 0, and if it is 0, it produces 1.
⮚Logical AND produces 0 if one or both its operands evaluate to 0. Otherwise, it produces 1.
⮚Logical OR produces 0 if both its operands evaluate to 0. Otherwise , it produces 1.
LOGICAL OPERATORS
UNIT I 119
120. • C provides six bitwise operators for manipulating the individual bits in an integer
quantity . Bitwise operators expect their operands to be integer quantities and treat
them as bit sequences.
⮚Bitwise negation is a unary operator that complements the bits in its operands.
⮚Bitwise AND compares the corresponding bits of its operands and produces a 1 when both bits are
1, and 0 otherwise.
⮚ Bitwise OR compares the corresponding bits of its operands and produces a 0 when both bits are 0,
and 1 otherwise.
⮚Bitwise exclusive or compares the corresponding bits of its operands and produces a 0 when both
bits are 1 or both bits are 0, and 1 otherwise.
BIT WISE OPERATORS
UNIT I 120
122. • The conditional operator has three expressions.
⮚ It has the general form expression1 ? expression2 : expression3
⮚First, expression1 is evaluated; it is treated as a logical condition.
⮚If the result is non-zero, then expression2 is evaluated and its value is the final result. Otherwise,
expression3 is evaluated and its value is the final result.
• For example,int m = 1, n = 2, min;
min = (m < n ? m : n); /* min is assigned a value 1 */
• In the above example, because m is less than n, m<n expression evaluates to be true,
therefore, min is assigned the value m, i.e., 1.
CONDITIONAL OPERATOR
UNIT I 122
123. • This operator allows the evaluation of multiple expressions, separated by the comma,
from left to right in order and the evaluated value of the rightmost expression is
accepted as the final result. The general form of an expression using a comma
operator is
• Expression M = (expression1, expression2, …,expression N);
• where the expressions are evaluated strictly from left to right and their values
discarded, except for the last one, whose type and value determine the result of the
overall expression.
COMMA OPERATOR
UNIT I 123
124. • C provides a useful operator, sizeof, for calculating the size of any data item or type. It takes a single operand that may be a type name (e.g., int) or an expression (e.g.,100) and returns the size of the specified
entity in bytes .The outcome is totally machine-dependent.
⮚ For example:
SIZEOF OPERATOR
UNIT I 124
125. • Evaluation of an expression in C is very
important to understand. Unfortunately there is
no ‘BODMAS’ rule in C language as found in
algebra.
• The precedence of operators determines the
order in which different operators are evaluated
when they occur in the same expression.
Operators of higher precedence are applied
before operators of lower precedence.
EXPRESSION EVOLUATION: PRECEDENCE &
ASSOCIATIVITY
UNIT I 125
127. • An lvalue is an expression to which a value can be assigned .
• An rvalue can be defined as an expression that can be assigned to an lvalue.
• The lvalue expression is located on the left side of an assignment statement, whereas an
rvalue is located on the right side of an assignment statement.
• The address associated with a program variable in C is called its lvalue; the contents of
that location are its rvalue, the quantity that is supposed to be the value of the variable.
• The rvalue of a variable may change as program execution proceeds; but never its lvalue.
The distinction between lvalues and rvalues becomes sharper if one considers the
assignment operation with variables a and b.
LVALUES AND RVALUES
UNIT I 127
128. • For example :
⮚a = b;
⮚b, on the right-hand side of the assignment
operator, is the quantity to be found at the
address associated with b, i.e., an rvalue. a is
assigned the value stored in the address
associated with b. a, on the left-hand side, is
the address at which the contents are altered as
a result of the assignment. a is an lvalue. The
assignment operation deposits b’s rvalue at a’s
LVALUES AND RVALUES
UNIT I 128
129. • Though the C compiler performs automatic type conversions, the programmer should be aware of
what is going on so as to understand how C evaluates expressions.
⮚ When a C expression is evaluated, the resulting value has a particular data type. If all the variables in the expression
are of the same type, the resulting type is of the same type as well. For example, if x and y are both of int type , the
expression x +y is of int type as well.
⮚ The smallest to the largest data types conversion with respect to size is along the arrow as shown below:
TYPE CONVERSION
UNIT I 129
130. ⮚float operands are converted to double.
⮚ char or short (signed or unsigned) are converted to int
(signed or unsigned).
⮚ If any one operand is double, the other operand is also
converted to double, and that is the type of the result; or
⮚If any one operand is long, the other operand is treated as
long, and that is the type of the result;
⮚ If any one operand is of type unsigned, the other operand is
converted to unsigned, or the only remaining possibility is
that Both operands must be int, and that is also the type of
the result.
RULE:TYPE CONVERSION
UNIT I 130
131. • A complex number is a number with a real part and an imaginary part. It is of the form a + bi where i is the square
root of minus one, and a and b are real numbers. a is the real part, and bi is the imaginary part of the complex
number. A complex number can also be regarded as an ordered pair of real numbers (a, b).
• According to C99, three complex types are supported:
⮚ float complex
⮚ double complex
⮚ long double complex
• C99 implementations support three imaginary types also :
⮚ float imaginary
⮚ double imaginary
⮚ long double imaginary
COMPLEX NUMBERS
UNIT I 131
132. • To use the complex types, the complex.h header file must be included. The
complex.h header file defines some macros and several functions that accept
complex numbers and return complex numbers.
• To use the complex types, the complex.h header file must be included. The
complex.h header file defines some macros and several functions that accept
complex numbers and return complex numbers. In particular, the macro I represents
the square root of –1. It enables to do the following:
⮚double complex c1 = 3.2 + 2.0 * I;
⮚float imaginary c2= -5.0 * I;
COMPLEX NUMBERS
UNIT I 132
134. Input and Output
• C has no built-in statements for input or output.
• A library of functions is supplied to perform these operations. The I/O
library functions are listed the “header” file <stdio.h>.
• You do not need to memorize them, just be familiar with them.
UNIT I 134
135. Streams
• All input and output is performed with streams.
• A "stream" is a sequence of characters organized into lines.
• Each line consists of zero or more characters and ends with the "newline"
character.
• ANSI C standards specify that the system must support lines that are at
least 254 characters in length (including the newline character).
UNIT I 135
136. Types of Streams in C
• Standard input stream is called "stdin" and is normally connected to the
keyboard
• Standard output stream is called "stdout" and is normally connected to
the display screen.
• Standard error stream is called "stderr" and is also normally connected to
the screen.
UNIT I 136
137. Input/Output in C
getchar ( ) ;
• This function provides for getting exactly one character from the
keyboard.
• Example:
char ch;
ch = getchar ( ) ;
UNIT I 137
138. Input/Output in C
putchar (char) ;
• This function provides for printing exactly one character to the screen.
• Example:
char ch;
ch = getchar ( ) ; /* input a character from kbd*/
putchar (ch) ; /* display it on the screen */
UNIT I 138
139. Formatted Input with scanf()
scanf ( ) ;
• This function provides for formatted input from the keyboard. The syntax is:
scanf ( “format” , &var1, &var2, …) ;
• The “format” is a listing of the data types of the variables to be input and the & in front
of each variable name tells the system WHERE to store the value that is input. It
provides the address for the variable.
• Example:
float a; int b;
scanf (“%f%d”, &a, &b); UNIT I 139
140. Formatted Output with printf
printf ( ) ;
• This function provides for formatted output to the screen. The syntax is:
printf ( “format”, var1, var2, … ) ;
• The “format” includes a listing of the data types of the variables to be output and, optionally, some
text and control character(s).
• Example:
float a ; int b ;
scanf ( “%f%d”, &a, &b ) ;
printf ( “You entered %f and %d n”, a, b ) ;
UNIT I 140
141. Formatted Output with printf
• Format Conversion Specifiers:
d -- displays a decimal (base 10) integer
l -- used with other specifiers to indicate a "long"
e -- displays a floating point value in exponential
notation
f -- displays a floating point value
g -- displays a number in either "e" or "f" format
c -- displays a single character
s -- displays a string of characters
UNIT I 141
144. PROGRAM CONTROL
STATEMENTS/CONSTRUCTS IN ‘C’
Program Control
Statements/Constructs
Selection/Branching
Conditional Type
if if-else if-else-if switch
Unconditional Type
break continue goto
Iteration/Looping
for while
do-
while
UNIT I 144
146. SELECTION STATEMENTS
One-way decisions using if statement
Two-way decisions using if-else statement
Multi-way decisions
Dangling else Problem
UNIT I 146
147. ONE-WAY DECISIONS USING IF STATEMENT
Flowchart for if construct
if(TestExpr)
stmtT TestExpr
stmtT
UNIT I 147
148. WRITE A PROGRAM THAT PRINTS THE LARGEST AMONG
THREE NUMBERS.
Algorithm C Program
1. START #include <stdio.h>
int main()
{
int a, b, c, max;
printf(“nEnter 3 numbers”);
scanf(“%d %d %d”, &a, &b, &c);
max=a;
if(b>max)
max=b;
if(c>max)
max=c;
printf(“Largest No is %d”, max);
return 0;
}
2. PRINT “ENTER THREE
NUMBERS”
3. INPUT A, B, C
4. MAX=A
5. IF B>MAX THEN MAX=B
6. IF C>MAX THEN MAX=C
7. PRINT “LARGEST
NUMBER IS”, MAX
8. STOP
UNIT I 148
149. TWO-WAY DECISIONS USING IF-ELSE STATEMENT
Flowchart of if-else construct
The form of a two-way
decision is as follows:
if(TestExpr)
stmtT;
else
stmtF;
TestExpr
stmtT stmtF
UNIT I 149
150. WRITE A PROGRAM THAT PRINTS THE LARGEST AMONG
THREE NUMBERS.
Algorithm C Program
1. START #include <stdio.h>
int main()
{
int a, b, c, max;
printf(“nEnter 3 numbers”);
scanf(“%d %d %d”, &a, &b, &c);
max=a;
if(b>max)
max=b;
if(c>max)
max=c;
printf(“Largest No is %d”, max);
return 0;
}
2. PRINT “ENTER THREE
NUMBERS”
3. INPUT A, B, C
4. MAX=A
5. IF B>MAX THEN MAX=B
6. IF C>MAX THEN MAX=C
7. PRINT “LARGEST
NUMBER IS”, MAX
8. STOP
UNIT I 150
151. MULTI-WAY DECISIONS
if-else-if ladder
if(TestExpr1)
stmtT1;
else if(TestExpr2)
stmtT2;
else if(TestExpr3)
stmtT3;
.. .
else if(TestExprN)
stmtTN;
else
stmtF; General format of switch
statements
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}
UNIT I 151
152. FLOWCHART OF AN IF-ELSE-IF
CONSTRUCT
TestExpr
TestExpr
2
TestExpr
N
TestExpr3
stmtT2
stmtTN
stmtT3
stmtTF
stmtT1
UNIT I 152
153. THE FOLLOWING PROGRAM CHECKS WHETHER A NUMBER GIVEN BY THE
USER IS ZERO, POSITIVE, OR NEGATIVE
#include <stdio.h>
int main()
{
int x;
printf(“n ENTER THE NUMBER:”);
scanf(“%d”, &x);
if(x > 0)
printf(“x is positive n”);
else if(x == 0)
printf(“x is zero n”);
else
printf(“x is negative n”);
return 0;
}
UNIT I 153
154. NESTED IF
• When any if statement is
written under another if
statement, this cluster is
called a nested if.
• The syntax for the
nested is given here:
Construct 1 Construct 2
if(TestExprA)
if(TestExprB)
stmtBT;
else
stmtBF;
else
stmtAF;
if(TestExprA)
if(TestExprB)
stmtBT;
else
stmtBF;
else
if(TestExprC)
stmtCT;
else
stmtCF;
UNIT I 154
155. A PROGRAM TO FIND THE LARGEST AMONG THREE
NUMBERS USING THE NESTED LOOP
#include <stdio.h>
int main()
{
int a, b, c;
printf(“nEnter the three numbers”);
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
UNIT I 155
156. SOLUTIONS TO DANGLING ELSE PROBLEM
• Use of null else
• Use of braces to enclose the
true action of the second if
With null
else
With braces
if(TestExprA
)
if(TestExprB
)
stmtBT;
else
;
else
stmtAF;
if(TestExprA
)
{
if(TestExprB
)
stmtBT;
}
else
stmtAF;
UNIT I 156
157. THE CONDITIONAL OPERATOR
An Example
• It has the following simple format:
expr1 ? expr2 : expr3
It executes by first evaluating expr1,
which is normally a relational
expression, and then evaluates either
expr2, if the first result was true, or
expr3, if the first result was false.
#include <stdio.h>
int main()
{
int a,b,c;
printf(“n ENTER THE TWO
NUMBERS:”);
scanf(“%d %d”, &a, &b);
c=a>b? a : b>a ? b :-1;
if(c==-1)
printf(“n BOTH NUMBERS ARE
EQUAL”);
else
printf(“n LARGER NUMBER IS %d”,c);
return 0;
}
UNIT I 157
158. THE SWITCH STATEMENT
The C switch construct
The general format of a switch
statement is
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}
UNIT I 158
159. SWITCH VS NESTED IF
⮚The switch differs from the else-if in that switch can test only for
equality, whereas the if conditional expression can be of a test
expression involving any type of relational operators and/or logical
operators.
⮚A switch statement is usually more efficient than nested ifs.
⮚The switch statement can always be replaced with a series of else-if
statements.
UNIT I 159
160. ITERATION AND REPETITIVE EXECUTION
• A loop allows one to execute a
statement or block of statements
repeatedly. There are mainly two
types of iterations or loops –
unbounded iteration or unbounded
loop and bounded iteration or
bounded loop.
• A loop can either be a pre-test
loop or be a post-test loop as
illustrated in the diagram.
UNIT I 160
161. “WHILE” CONSTRUCT
Expanded Syntax of “while” and its
Flowchart Representation
while statement is a pretest
loop. The basic syntax of the
while statement is shown
below:
UNIT I 161
162. AN EXAMPLE
#include <stdio.h>
int main()
{
int c;
c=5; // Initialization
while(c>0)
{ // Test Expression
printf(“ n %d”,c);
c=c-1; // Updating
}
return 0;
}
This loop contains all the parts of a
while loop. When executed in a
program, this loop will output
5
4
3
2
UNIT I 162
163. TESTING FOR FLOATING-POINT
‘EQUALITY’
float x;
x = 0.0;
while(x != 1.1)
{
x = x + 0.1;
printf(“1.1 minus %f equals %.20gn”, x, 1.1 -x);
}
The above loop never terminates on many computers, because 0.1 cannot
be accurately represented using binary numbers.
Never test floating point numbers for exact equality, especially in
loops.
The correct way to make the test is to see if the two numbers are
‘approximately equal’. UNIT I 163
164. “FOR” CONSTRUCT
• The general form of the for statement is as follows:
for(initialization; TestExpr; updating)
stmT;
for construct
flow chart
UNIT I 164
165. EXAMPLE
#include <stdio.h>
int main()
{
int n, s=0, r;
printf(“n Enter the Number”);
scanf(“%d”, &n);
for(;n>0;n/=10)
{
r=n%10;
s=s+r;
}
printf(“n Sum of digits %d”, s);
return 0;
}
UNIT I 165
166. 8.3 “DO-WHILE” CONSTRUCT
The C do-while loop
The form of this loop construct is
as follows:
do
{
stmT; /* body of statements would be
placed here*/
}while(TestExpr);
UNIT I 166
167. POINT TO NOTE
With a do-while statement, the body of the loop is executed first and the
test expression is checked after the loop body is executed. Thus, the do-
while statement always executes the loop body at least once.
UNIT I 167
168. AN EXAMPLE
#include <stdio.h>
int main()
{
int x = 1;
int count = 0;
do {
scanf(“%d”, &x);
if(x >= 0) count += 1;
} while(x >= 0);
return 0;
} UNIT I 168
169. GOTO STATEMENT
The control is unconditionally
transferred to the statement
associated with the label specified
in the goto statement. The form of
a goto statement is
goto label_name;
The following program is used to find the factorial of a
number.
#include <stdio.h>
int main()
{
int n, c;
long int f=1;
printf(“n Enter the number:”);
scanf(“%d”,&n);
if(n<0)
goto end;
for(c=1; c<=n; c++)
f*=c;
printf(“n FACTORIAL IS %ld”, f);
end:
return 0;
}
UNIT I 169
171. “BREAK” AND “CONTINUE”
STATEMENTS
break continue
1. It helps to make an early
exit from the block where it
appears.
1. It helps in avoiding the
remaining statements in a
current iteration of the loop
and continuing with the next
Iteration
2. It can be used in all control
statements including switch
construct.
2. It can be used only in loop
constructs.
UNIT I 171
172. NESTED LOOPS
⮚A nested loop refers to a loop
that is contained within another
loop.
⮚If the following output has to be
obtained on the screen
1
2 2
3 3 3
4 4 4 4
then the corresponding program
will be
#include <stdio.h>
int main()
{
int row, col;
for(row=1;row<=4;++row)
{
for(col=1;col<=row;++col)
printf(“%d t”, row);
printf(“n”);
}
return 0;
}
UNIT I 172
173. COMMON PROGRAMMING ERRORS
⮚Writing expressions like a<b<c or a==b==c etc.
⮚Use of = instead of ==
⮚Forgetting to use braces for compound statement
⮚Dangling else
⮚Use of semicolon in loop
⮚Floating point equality UNIT I 173