Chapter 5 Preparing C Programs Chapter 5: Preparing C Programs 1

Download Report

Transcript Chapter 5 Preparing C Programs Chapter 5: Preparing C Programs 1

Chapter 5
Preparing C Programs
Chapter 5: Preparing C Programs
1
Program development
Understanding
the problem
EDIT
Writing an
algorithm
Chapter 5
errors
COMPILE
Verifying the
algorithm
RUN
Converting to
code
Result
Program development
2
Program development
Source code
pico prog.c
EDIT
errors
cc prog.c
a.out
COMPILE
RUN
Result
Chapter 5
Program development
3
High-level languages
Machine language: computer’s native
language.
Add two numbers: 00100111 1010 0101
Assembly language: uses mnemonics.
Add two numbers: ADD R1 R2
An assembly code needs to be translated to
machine code.
Chapter 5
High-level languages
4
High-level languages
High-level programming languages:
bridging the gap between machine language
and natural languages.
Examples: COBOL, Fortran, Algol, C
Add two numbers (in C): Z = A + B;
Compilation: translation to machine code.
Chapter 5
High-level languages
5
A C program
A sample C program
/* A simple C program to read a number & compute and display
its square by using the multiplication (*) operator. */
#include <stdio.h>
main ()
/* a C program always has a main function */
{
int n;
/* this declares an integer variable 'n' */
printf ("\nEnter the number to be squared: ");
scanf ("%d", &n);
printf ("Using the * operator, the square of %d is %d.\n\n",
n, n*n);
}
Chapter 5
A C program
6
Compilation in C
Use the cc or gcc compiler:
cc prog.c
Produces executable file a.out if no errors
To specify name of executable file, use -o
option:
cc -o prog prog.c
Name of executable file becomes ‘prog’.
Chapter 5
Compilation in C
7
Errors
Compilation errors: occur during compilation.
 Reason: syntax errors.
 Easy to rectify.
Run-time errors: occur during execution.
 Reasons: logic errors, data errors, computation
errors.
 Harder to rectify.
Chapter 5
Errors
8
Homework
Try exercises in chapter 5.
Chapter 5
Homework
9