Docsity

C Programming Fundamentals: Statements, Expressions, Control Flow, and Functions, Study notes of Computer Science

Partial preview of the text

Download C Programming Fundamentals: Statements, Expressions, Control Flow, and Functions and more Study notes Computer Science in PDF only on Docsity!

MOMBASA TECHNICAL TRAINING

INSTITUTE

DEPARTMENT OF INFORMATION AND

COMMUNICATION TECHNOLOGY

STRUCTURED PROGRAMMING

P.O. BOX 81220, TEL 041-2226458, MOMBASA

STRUCTURED PROGRAMMING

DEFINITION OF TERMS

  1. HEADER FILE - A header file is a file with extension .h which contains C function declarations to be shared between several source files. A header file is used in a program by including it with the use of the preprocessing directive #include , which comes along with the compiler. #include<stdio .h>
  2. EXPRESSION – These are statements that return a value. Expressions combine variables and constants to create new values or logical conditions which are either true or false e.g. x + y, x <= y etc
  3. KEYWORD - A keyword is a reserved word in C. Reserved words may not be used as constants or variables or any other identifier names. Examples include auto, else, Long, switch, typedef ,break etc
  4. IDENTIFIER - A C identifier is a name used to identify a variable, function, or any other user- defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers. 5. COMMENT - These are non-executable program statements meant to enhance program readability and maintenance- they document the program. 6. FUNCTION - A function is a group of statements, enclosed within curly braces, which together perform a task.
  5. STATEMENT- Statements are expressions, assignments, function calls, or control flow statements which make up C programs. Statements are terminated using a semicolon. 8. SOURCE CODE – Program instructions in their original form. C source code files have an extension .c
  6. OBJECT CODE – Code produced by a compiler from source code and exists in machine readable language.
  7. EXECUTABLE FILE – Refers to a file in a format that a computer can directly execute and is created by a compiler.
  8. STANDARD LIBRARY – Refers to a collection of precompiled functions/routines that a program can use. The routines are stored in object format and contain descriptions of functions to perform I/O, string manipulations, mathematics etc.
  9. SIGNED INTEGER – This is an integer that can hold either positive or negative numbers.
  10. COMPILER – This is a program that translates source code into object code. 14. PREPROCESSOR COMMAND - The C preprocessor modifies a source file before handing it over to the compiler for instance by including header files with #include as I #include <stdio.h> 15. LINKER/Binder/Link Editor – This is a program that combines object modules to form an executable program. The linker combines the object code, the start up code and the code for

library routines used in the program (all in machine language) into a single file- the executable file.

  1. OPERATOR - A symbol that represents a specific action. For example, a plus sign (+) is an operator that represents addition. The basic mathematic operators are + addition, - subtraction,* multiplication,/ division
  2. OPERAND - Operands are the objects that are manipulated by operators in expressions. For example, in the expression 5 + x , x and 5 are operands and + is an operator. All expressions have at least one operand.
  3. EXPRESSION – This is a statement that returns a value. For example, when you add two numbers together or test to see whether one value is equal to another.
  4. VARIABLE - A variable is a memory location whose value can change during program execution. Variable declaration must have a type, which defines what values that variable can hold.
  5. Data type – The data type of a variable etc determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. 21. CONSTANT - a constant is a value that never changes during program execution.
  6. WHITESPACE - A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement: int age;

There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement

Assembly Code Machine Code

LDA A ADD # STA A JMP #

-> Assembler ->

Such languages are sometimes still used for kernels and device drivers , i.e. the core of the operating system and for specific machine parts. More often, such languages are used in areas of intense processing, like graphics programming , when the code needs to be optimized for performance.

Almost every CPU architecture has a companion assembly language. Most commonly used are the assembly languages today like Autocoder for IBM mainframe systems, Linoreum, MACRO -11,etc.

Third-Generation Languages (3GL) – High-Level Languages

Third generation languages are the primary languages used in general purpose programming today. They each vary quite widely in terms of their particular abstractions and syntax. However, they all share great enhancements in logical structure over assembly languages.

  • Introduced in the 1950s
  • Designed around ease of use for the programmer (Programmer friendly)
  • Driven by desire for reduction in bugs, increases in code reuse
  • Based on natural language
  • Often designed with structured programming in mind
  • The languages are architecture independent e.g. C, Java etc.

Examples:

Most Modern General Purpose Languages such as C, C++, C#, Java, Basic, COBOL, Lisp and ML.

Fourth Generation Languages

Fourth-generation programming languages are high-level languages built around database systems. They are generally used in commercial environments.

  • Improves on 3GL and their development methods with higher abstraction and statement power , to reduce errors and increase development speed by reducing programming effort. They result in a reduction in the cost of software development.
  • A 4GL is designed with a specific purpose in mind. For example languages to query databases (SQL), languages to make reports (Oracle Reports) etc.
  • 4GL are more oriented towards problem solving and systems engineering.

Examples: Progress 4GL, PL/SQL, Oracle Reports, Revolution language, SAS, SPSS, SQ

Fifth Generation Languages

Improves on the previous generations by skipping algorithm writing and instead provide constraints/conditions.

While 4GL are designed to build specific programs, 5GL are designed to make the computer solve a

given problem without the programmer. The programmer only needs to worry about what problems needed to be solved and only inputs a set of logical constraints , with no specified algorithm, and the Artificial Intelligence (AI)-based compiler builds the program based on these constraints

Examples: Prolog, OPS5, Mercury

Low-Level Languages Versus High-Level Languages

Low-level languages such as machine language and assembly language are closer to the hardware than are the high-level programming languages, which are closer to human languages. Low-level languages are converted to machine code without using a compiler or interpreter, and the resulting code runs directly on the processor. A program written in a low-level language runs very quickly , and with a very small memory footprint ; an equivalent program in a high-level language will be more heavyweight. Low-level languages are simple , but are considered difficult to use , due to the numerous technical details which must be remembered.

High-level languages are closer to human languages and further from machine languages.

The main advantage of high-level languages over low-level languages is that they are easier to read , write, and maintain. Ultimately, programs written in a high-level language must be translated into machine language by a compiler or interpreter.

The first high-level programming languages were designed in the 1950s. Now there are dozens of different languages, including Ada, Algol, BASIC, COBOL, C, C++, FORTRAN, LISP, Pascal, and Prolog.

PROGRAMMING PARADIGMS

A programming paradigm is a fundamental style of computer programming, a way of building the structure and elements of computer programs. There are four main paradigms:

a) Unstructured Programming

In unstructured programs, the statements are executed in sequence (one after the other) as written. This type of programming uses the GoTo statement which allows control to be passed to any other section in the program. When a GoTo statement is executed, the sequence continues from the target of the GoTo. Thus, to understand how a program works, you have to execute it. This often makes it difficult to understand the logic of such a program.

b) Structured Programming

The approach was developed as a solution to the challenges posed by unstructured/procedural programming. Structured programming frequently employs a top-down design model , in which developers break the overall program structure into separate subsections. A defined function or set of similar functions is coded in a separate module or sub-module, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. After a module has been tested individually, it is then integrated with other modules into the overall program structure.

Disk space required

ADVANTAGES C LANGUAGE

  1. Modularity: modularity is one of the important characteristics of C. we can split the C program into no. of modules instead of repeating the same logic statements (sequentially). It allows reusability of modules.
  2. General purpose programming language: C can be used to implement any kind of applications such as math’s oriented, graphics, business oriented applications.
  3. Portability: we can compile or execute C program in any operating system (UNIX, dos, windows).
  4. Powerful and efficient programming language: C is very efficient and powerful programming language; it is best used for data structures and designing system software. Efficient in that it is a modular programming language and thus makes efficient use of memory and system resources.

CHAPTER 2

PROGRAM DESIGN AND DEVELOPMENT

Program/System design is the process of defining the software structure (components/ modules, interfaces, and data) to satisfy/realize specified requirements. Program development refers to all the activities and processes involved between the conception of the desired software through to the final manifestation of the software, in a planned and structured process.

PROGRAM DEVELOPMENT CYCLE

This refers to the stages that form the framework for planning and controlling the creation of an information system. Several approaches to program development have been devised and the System Development Life Cycle (SDLC) is one of the most popular. The SDLC is a methodology that aims at producing a high quality system that meets or exceeds customer expectations , reaches completion within times and cost estimates , works efficiently and is inexpensive to maintain and cost-effective to enhance.

  1. Project planning, feasibility study: The fundamental process of understanding why a system should be built and determining how the project team will go about building it. It should also establish a clear understanding of the current system. It involves a. Technical feasibility study: can the system be built b. Economic feasibility study: will the system provide business value, and what are the risks? c. Organizational feasibility study: if built, will it be used.
  2. Systems analysis, requirements definition: the phase identifies the users of the system, what the system will do. It involves a. Analysis of the old system and ways to design the new system b. Requirement gathering. Various tools for collecting information are used. These include interviews, questionnaires, observation etc. c. Development of the new system proposal document.
  3. Systems design: describes how the system will operate, in terms of hardware, software, network infrastructure, user interface, forms and reports that will be used, the specific programs, databases and files that will be needed. Design phase steps include; a. Design strategy: method of development, in-house, outsourced, or purchased b. Architecture design – hardware , software, internet infrastructure, and user interface c. Database and file specification d. Program design: defines the program that needs to be done and exactly what each will do.
  4. System Implementation: The real code is written here.
  5. Integration and testing: Brings all the pieces of the project together into a special testing environment, then checks for errors, bugs and interoperability.
  6. Acceptance, installation, deployment: The final stage of initial development, where the software is put into use and runs actual business.
  7. Maintenance: What happens during the rest of the software's life: changes, correction, additions, and moves to a different computing platforms etc. This step, perhaps most important of all, goes on seemingly forever. The SDLC is a cycle i.e. iterative in that a new requirement might initiate the whole process again.

Begin If A is greater than B And if A is greater than C, A is the Biggest Otherwise C is the Biggest Otherwise If B is greater than C B is the Biggest Otherwise C is the Biggest End

Pseudo-code cannot be compiled nor executed, and there are no real formatting or syntax rules. It is simply one step - an important one - in producing the final code

2. Algorithm

This refers to an established, computational procedure for solving a problem in a finite number of steps. Algorithms can be expressed in any language including natural languages such as English. Algorithm means a method/ logic for solving a given problem.

An algorithm to find the largest among three different numbers entered by user. Step 1: Start Step 2: Declare variables a, b and c. Step 3: Read variables a, b and c. Step 4: If a>b If a>c Display a is the largest number. Else Display c is the largest number. Else If b>c Display b is the largest number. Else Display c is the greatest number. Step 5: Stop

3. Flowchart

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic representation illustrates a solution to a given problem. Flowcharts are used in designing and documenting complex processes or programs. Like other types of diagrams, they help to visualize what is going on and thereby help the viewer to understand a process, and perhaps also find flaws/errors, bottlenecks, and other less-obvious features within it.

SYMBOLS USED IN FLOWCHART

Different symbols are used for different states in flowcharts. The table below describes all the symbols that are used in making flowchart

Symbol Purpose Description

Flow line Used to indicate the flow of logic by connecting symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Symbol Purpose Description

Processing Used for arithmetic operations and data- manipulations.

Decision Used to represent the operation in which there are two alternatives, true and false.

On-page Connector Used to join different flow lines

Off-page Connector Used to connect flowchart portion on different pages.

Comment

Used to add comments or clarification

Predefined Process/Function

Used to represent a group of statements performing one processing task.

Draw flowchart to find the largest among three different numbers entered by user.

Or a flowchart to ask for a number from user and multiply with another number and print result as follows:

Examples of flowcharts include Activity diagram, Data flow diagram and sequence diagrams etc.

table has a rule to cover every combination. Rules are made of selectors symbolized by Y (Yes), N (No) and – (for redundant or irrelevant rules).

COMPLETING THE TABLE  If the number of conditions identified is n, then the number of possible rules is found by applying the formula; Number of rules = 2n^ i.e. 2 number of conditions  Entries opposite the lowest condition should be completed first using Y an N alternately until all the vertical rules have been dealt with.  Entries opposite the second lowest condition should be completed using Y an N in pairs until all the vertical rules have been dealt with.  Entries for the next condition are then completed next using Ys and Ns in fours.  This process continues using twice the number of Ys and Ns each time until all conditions are completed.  Once entered, the rules are read vertically in each column and an X entered at the action that appropriately completes that rule. Actions which are mutually exclusive can be combined on a single line.

EXAMPLE A student who passes the examinations and completes the coursework and project satisfactorily is awarded a pass. If the course work and the project are unsatisfactory, the student is asked to resubmit the unsatisfactory work, as long as the exams have been passed. A student who fails the examinations is deemed to have failed the whole course unless both the course work and the project are satisfactory, in which case the student is allowed to re-sit the examination.

SOLUTION

Before an overall pass

Rules Exams Passed? Y Y Y Y N N N N

Conditions Completed Course work? Y Y N N Y Y N N

Completed Project? Y N Y N Y N Y N Pass X Re-sit Exam X Resubmit Coursework X X Resubmit Project X X

Actions

Failed X X X

ASSIGNMENT 1

Candidates are accepted for employment if they pass the interview and their qualifications and reference are satisfactory. If they pass the interview and the qualifications or references (but not both) are unsatisfactory, a job for probationary period is offered. In all other circumstances, the candidate’s application is rejected.

Assignment 2

  • Design the business logic (at least three conditions) that is applicable when a customer is applying for a bank loan.
  • Draw a decision table to represent the business logic.

CHAPTER 3

3. PROGRAM STRUCTURE

STRUCTURE OF A C PROGRAM

The C programming language was designed by Dennis Ritchie as a systems programming language for Unix.

A C program basically has the following structure:  Preprocessor Commands  Functions  Variable declarations  Statements & Expressions  Comments

Example: #include <stdio.h>

int main() { /* My first program*/ printf("Hello, World! \n");

return 0; }

Preprocessor Commands

These commands tell the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. The standard input and output header file (stdio.h) allows the program to interact with the screen, keyboard and file system of the computer.

NB/ Preprocessor directives are not actually part of the C language, but rather instructions from you to the compiler.

Functions

These are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. When this function is prefixed with keyword int , it means this function returns an integer value when it exits. This integer value is retuned using return statement. The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen. A function is a group of statements that together perform a task. A C program can be divide up into separate functions but logically the division usually is so each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The general form of a function definition in C programming language is as follows:

\” Double quote \0 Null

Note the following

  • C is a case sensitive programming language. It means in C printf and Printf will have different meanings.
  • End of each C statement must be marked with a semicolon.
  • Multiple statements can be on the same line.
  • Any combination of spaces, tabs or newlines is called a white space. C is a free-form language as the C compiler chooses to ignore whitespaces. Whitespaces are allowed in any format to improve readability of the code. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
  • Statements can continue over multiple lines.
  • A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers.
  • A keyword is a reserved word in C. Reserved words may not be used as constants or variables or any other identifier names

SAMPLE PROGRAM

//First program

#include<stdio.h>

main()

int num; // Declaration

num =1; // Assignment statement

printf(" My favorite number is %d because", num);

printf(" it is first.\n");

return 0;

The program will output (print on screen) the statement “ My favorite number is 1 because it is first ”. The %d instructs the computer where and in what form to print the value. %d is a type specifier used to specify the output format for integer numbers.

Keywords

The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names.

auto else Long switch break enum register typedef

case extern return union char float short unsigned const for signed void continue goto sizeof volatile default if static while do int struct _packed double

SOURCE CODE FILES

When you write a program in C language, your instructions form the source code/file. C files have an extension .c. The part of the name before the period is called the extension.

Object Code, Executable Code and Libraries

An executable file is a file containing ready to run machine code. C accomplishes this in two steps.  Compiling –The compiler converts the source code to produce the intermediate object code.  The linker combines the intermediate code with other code to produce the executable file. You can compile individual modules and then combine modules later.

Linking is the process where the object code, the start up code and the code for library routines used in the program (all in machine language) are combined into a single file- the executable file.

 NB/ An interpreter unlike a compiler is a computer program that directly executes, i.e. performs, instructions written in a programming, without previously compiling them into a machine language program.

 If the compiled program can run on a computer whose CPU or operating system is different from the one on which the compiler runs, the compiler is known as a cross- compiler.

 A program that translates from a low level language to a higher level one is a decompiler.

 A program that translates between high-level languages is usually called a source- to-source compiler or transpiler.

Library Functions

There is a minimal set of library functions that should be supplied by all C compilers, which your program may use. This collection of functions is called the C standard library. The standard library contains functions to perform disk I/O (input/ output), string manipulations, mathematics and much more. When your program is compiled, the code for library functions is automatically added to your program. One of the most common library functions is called printf() which is a general purpose output function. The quoted string between the parenthesis of the printf() function is called an argument.

Printf(“This is a C program\n”)

The \n at the end of the text is an escape sequence tells the program to print a new line as part of the output.