introduction to c - angelfire · web viewexamples using arrays . example 1: initialize the...
TRANSCRIPT
Introduction to C
King Saud University
Computer Applications DepartmentCourse CSC150
Programming with C
Notes
Extracted from the text book:
C: HOW TO PROGRAM
Third Edition
By H.M. DEITEL
P.J. DEITEL
Publisher: Prentice Hill
(second semester 1423-1424)
The notes are prepared by Samira Lahmar
Chapter 1
Introduction
1. The history of C
Bell Labs first developed the C language in the early 1970s by Dennis Ritchie from two previous programming languages, BCPL and B.
The C language was used to develop the UNIX operating system. Until that time, operating systems were written in assembly language, which is tedious, time consuming, and difficult to maintain.
The rapid expansion of C over various types of computers led to many variations. These were similar, but often incompatible.
This was a serious problem for program developers who needed to develop code that would run on several platforms.
It became clear that a standard version of C was needed.
By 1989, the ANSI C standard has been approved and first copies becoming available and updated in 1999.
The ANSI C standard specifies the form of programs written in C and establishes how these programs are to be interpreted.
The purpose of the standard is to promote portability, reliability and maintainability.
ANSI : American National Standard Institute.
ANSI C standard is the foundation upon which C++ is built.
Because C is a hardware-independent, widely available language, applications written in C can run with little or no modifications on wide range of different computer systems.
2. The C standard libraryC programs consist of modules or pieces called functions.
You can program all the functions you need to form a c program but most C programmers take advantage of a rich collection of existing functions called the C standard library.
There are two pieces to learning the C World:
The first is learning the C language itself.
And the second is learning how to use the functions in the C standard library.
3. The basics of the C EnvironmentAll C systems generally consist of three parts: the environment, the language, and the C standard library.
C programs typically go through six phases to be executed.
These are editing, preprocess, compile, link, load and execute.
Editor
The programmer types a C program with the editor and makes corrections if necessary. The program is then stored on a secondary storage device such a disk. The file name should end with the .c extension.
Compiler
The programmer gives the command to compile the program. The compiler translates the C program into machine language code (object code).
A preprocessor program automatically executes before the translation phase begins. The C preprocessor obeys special commands called preprocessor directives which indicate that certain manipulations are to be performed on the program before compilation.
These manipulations usually consist of including other files in the file to be compiled and replacing special symbols with program text.
Then the compiler converts the program into machine language.
Linker
C programs typically contain references to functions defined elsewhere such as in the standard libraries or in the libraries of a group of programmers working on a particular project.
A linker links the object code with the code for the missing functions to produce an executable image.
Execution (CPU)
Before a program can be executed, the program must first be placed in memory. This is done by the
loader which takes the executable image from disk and transfers it to memory.
Finally, the computer, under the control of its CPU, executes the program one instruction at a time.
Good Programming Practice
Read the manuals for the version of C you are using.
Your computer and compiler are good teachers. If you are not sure how a feature of C works, write a sample program with that feature, compile and run the program, and see what happens.
Chapter 2
Introduction to
C programming
The C language facilitates a structured and disciplined approach to computer program design.
1. A Simple C program: Printing a line of text
/* A first program in C */
#include
int main()
{
printf (Welcome to C !\n);
return 0;
}
Welcome to C !
- Comments: do not cause the computer to perform any action when the program is run.
Text surrounded by /* and */ is ignored by the computer.
Its used to describe program and improve program readability.
Comments also help other people read and understand your program, but too many comments can make a program difficult to read.
- Preprocessor directive: tells computer to load contents of a certain file.
- #include is a directive to C preprocessor.
Lines beginning with # are processed by the preprocessor before the program is compiled.
This specific line tells the preprocessor to include the contents of the standard input/output header file stdio.h in the program.
This header file contains information and declarations that helps the compiler determine if calls to library functions have been written correctly.
Good programming practice:
Although the inclusion of is optional, it should be done on every C program that uses Input/Output standard library functions.
- int main() is a part of every program.
C programs contain one or more functions, exactly one of which must be main.
The parentheses after main indicate that main is a function.
Every program in C begins executing at the function main.
Int means that main returns an integer value.
- Braces: indicate a block
{ left brace must begin the body of every function.
A corresponding } right brace must end each function.
- Printf(Welcome to C!\n);
Instructs the computer to perform an action namely to print on the screen the string of characters marked between the quotation marks.
The entire line is called a statement.
Every statement must end with a semicolon (;).
\ backslash is called an escape character. It indicates the printf is supposed to do something out of ordinary.
When encountering a backslash, printf looks ahead at the next character and combines it with the backslash to form an escape sequence.
- \ :Double quotes: Print a double quote character in a printf statement.
-\n :Newline: Position the cursor at the beginning of the next line.
-\a :Alert: Sound the system bell.
\\ :backslash: Print a backslash character in a printf statement.
\t : tab.
The printf function can print Welcome to C! several different ways.
a. /* Printing on one line with two printf statement */
printf(Welcome );
printf(to C!\n);
(Welcome to C!
b. /* Printing multiple lines with a single printf */
printf (Welcome\nto\n\C!\n);
(
Welcome
To
C!
Good programming practice:
- The last character printed by a function that does any printing should be a newline (\n).
- Indent the entire body of each function one level of indentation (3 spaces) within the braces. This helps make program easier to read.
- return 0;
A way to exit a function.
Return 0; passes the value 0 back to the operating system environment in which the program is being executed. This indicates to the operating system that the program executed successfully.
2. Another simple C program: Adding two integers
- int integer1, integer2, sum; : is a declaration of variables.
- A variable is a location in memory where a value can be stored for use by a program.
All variables must be declared with a name and a data type.
Type int means that the variables can hold integers (-1, 3, 0, 47 )
There are other data types besides int in C (see later).
A variable name in C is any valid identifier.
An identifier is a series of characters consisting of letters, digits and underscores, that does not begin with a digit.
An identifier can be any length, but only the first 31 characters are required to be recognized by C compliers according to ANSI C standard.
C is case sensitive. Uppercase and lowercase letters are different in C, so a1 and A1 are different identifiers.
Declarations appear before executable statements. If not, syntax error occurs (Complier error / compile-time error).
An identifier defined by the programmer should not be the same as one already defined in the library ex: printf().
Good programming practice:
Choosing meaningful variable names helps make a program self documenting.
Separate the declarations and executable statements in a function with one blank line to emphasize where the declarations end and the executable statements begin.
- scanf (%d, &integer1);
This statement uses scanf to obtain a value from a user.
The scanf function takes input from the keyboard.
This scanf has two arguments
%d: format control string indicates the type of data that should be input by the user.
%d conversion specifier: data should be an integer.
d: stands for decimal integer.
&integer1: indicates the location in memory to store variable.
&: ampersand called the address operator in C.
User responds to scanf by typing in number, then pressing the Enter .
- = (assignment operator)
Assigns value to a variable.
Binary operator (has two operands):
sum = integer1 + integer2;
Variable receiving value on left.
- Printf (Sum is %d \n, sum);
Similar to scanf %d means decimal integer will be printed
Sum specifies what integer will be printed.
Calculation can be performed inside printf statements
printf (Sum is %d\n, integer1 + integer2);
3. Memory ConceptsVariables
Variable names correspond to locations in the computers memory.
Every variable has a name, a size and a value.
Whenever a new value is placed into a variable (Through scanf for example), it replaces (and destroys) previous value.
Reading variables from memory does not change them.
Sum = integer1 + integer2;
Sum is changed but integer1 and integer2 remain with the same value.
A visual representation:
C operation
Arithmetic
operator
Algebraic
expression
C expression
Addition
+
f + 7
f + 7
Subtraction
-
p
c
p
-
c
Multiplication
*
bm
b * m
Division
/
x / y
x / y
Modulus
%
r mod s
r % s
integer1
Keywords
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
const
float
short
unsigned
continue
for
signed
void
default
goto
sizeof
volatile
do
if
static
while
integer2
Defining variables
There are two places where you can define a variable.
After the opening brace of a block of code (usually at the top of a function).
Before a function name (such as before main () in the program).
4. Keywords
Keywords: Cant be used as identifier: variables
Standard algebraic equality
operator or
relational operator
C++ equality
or relational
operator
Example
of C++
condition
Meaning of
C++ condition
Relational operators
>
>
x > y
x
is greater than
y
p /p
p/p
p /p
px < y/p
p /p
px/p
p is less than /p
py/p
p /p
p /p
p=/p
p /p
px >= y
x
is greate
r than or equal to
y
=60)
printf( "D\n");
else
printf(Failed);
Once condition is met, rest of statements skipped
Deep indentation usually not used in practice
Compound statement:
- The if selection structure expects only one statement in its body.
To include several statements in the body of an if, enclose the set of statements in braces.
A set of statement contained within a pair of braces is called a compound statement.
Example:
if ( grade >= 60 )
printf( "Passed.\n" );
else {
printf( "Failed.\n" );
printf( "You must take this course again.\n" );
}
Without the braces, the statement :
printf( "You must take this course again.\n" );
would be outside the body of the else-part of the if, and would be automatically executed regardless of whether the grade is less than 60.
A statement is a command to the computer:
- Simple statement
- Compound statement
a. simple statement
1. declaration statements
char toto, x;
2. assignment statement
x = A;
3. function call statements
printf(%d , x);
4. Control statement
while (I