0% found this document useful (0 votes)
78 views41 pages

Ch3 Aiman PDF

The document discusses the fundamentals of C programming language and basic input/output functions. It covers C development environment, C program structure including preprocessor directives, function main, statements, identifiers, variables and basic data types like int, float, double, and char. It provides examples of simple C programs and explanations of key concepts.

Uploaded by

abdullah badawi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views41 pages

Ch3 Aiman PDF

The document discusses the fundamentals of C programming language and basic input/output functions. It covers C development environment, C program structure including preprocessor directives, function main, statements, identifiers, variables and basic data types like int, float, double, and char. It provides examples of simple C programs and explanations of key concepts.

Uploaded by

abdullah badawi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

EEEB114: Principle of

Programming
Topic 3: Fundamental of C Programming Language and Basic
Input / Output Function
Fundamental of C and Input /
Output
In this chapter you will learn about:
C Development Environment
C Program Structure
Basic Data Types
Input/Output function
Common Programming Error

prepared by NI, edited by MAF


C Development Environment

Phase 1 Editor
Disk
Program is created using the
Editor and stored on Disk.

Phase 2 Preprocessor
Disk
Pre-processor program
processes the code.

Phase 3 Compiler
Disk
Compiler creates object
code and stores it on Disk.

Phase 4 Linker Linker links object code with


Disk libraries, creates a.out and
stores it on Disk

Phase 5 Loader
Disk
Loader puts Program in
Memory

CPU takes each instruction


Phase 6 CPU (Execute)
Disk
and executes it, storing new
data values as the program
executes.

prepared by NI, edited by MAF


C Development Environment

Entering, translating, and running a High-Level Language


Program

prepared by NI, edited by MAF


C Program Structure
An example of simple program in C

#include <stdio.h>

int main(void)
{
printf(I love programming\n);
printf(You will love it too once );
printf(you know the trick\n);
return 0;
}

prepared by NI, edited by MAF


The output
The previous program will produce the following output
on your screen
I love programming
You will love it too once you know the trick
Press any key to continue

prepared by NI, edited by MAF


C Program Structure
An example of simple program in C
#include <stdio.h>
#define KMS_PER_MILE 1.609

int main(void)
{
double miles;
double kms;

printf (Enter the distance in miles>);


scanf (%lf, &miles);

kms = KMS_PER_MILE * miles;

printf(That equals %f kilometers,\n, kms);

return (0);
}
prepared by NI, edited by MAF
Preprocessor directives
a C program line begins with # provides an instruction to
the C preprocessor
It is executed before the actual compilation is done.
Two most common directives :
#include
#define
In our example
#include<stdio.h> identifies the header file for standard
input and output needed by the printf().
#define KMS_PER_MILE 1.609 informs the preprocessor
that KMS_PER_MILE means 1.609.

prepared by NI, edited by MAF


C Program Structure
An example of simple program in C
Directive #include notifies preprocessor that printf and scanf are found
#include <stdio.h> in standard header <stdio.h>
#define KMS_PER_MILE 1.609 Directive #define notifies preprocessor to replace
KMS_PER_MILE to 1.609
int
main(void)
{
double miles;
double kms;

printf (Enter the distance in miles>);


scanf (%lf, &miles);

kms = KMS_PER_MILE * miles;

printf(That equals %f kilometers,\n, kms);

return (0);
}

prepared by NI, edited by MAF


Function main
Identify the start of the program
Every C program has a main ( )
'main' is a C keyword. We must not use it for any
other variable.
2 common ways of main declaration

int main(void) void main(void) void main() int main()


{ { { {

return 0; return 0;
} } } }

prepared by NI, edited by MAF


C Program Structure
An example of simple program in C
#include <stdio.h>
#define KMS_PER_MILE 1.609

int main(void)
{
double miles;
double kms;

printf (Enter the distance in miles>);


scanf (%lf, &miles);

kms = KMS_PER_MILE * miles;

printf(That equals %f kilometers,\n, kms);

return (0);
}
prepared by NI, edited by MAF
The curly braces { }
Identify a segment / body of a program
The start and end of a function
The start and end of the selection or repetition
block.
Since the opening brace indicates the start of
a segment with the closing brace indicating the
end of a segment, there must be just as
many opening braces as closing braces
(this is a common mistake of beginners)

prepared by NI, edited by MAF


C program skeleton
In short, the basic skeleton of a C program looks like this:

#include <stdio.h> Preprocessor directives

int main(void) Function main


{ Start of segment
statement(s);
return 0;

} End of segment

prepared by NI, edited by MAF


Statement
A specification of an action to be taken by the computer as
the program executes.
Each statement in C needs to be terminated with semicolon
(;)
Example:
#include <stdio.h>
int main(void)
{
printf(I love programming\n); statement

printf(You will love it too once ); statement


printf(you know the trick\n); statement
return 0; statement
}

prepared by NI, edited by MAF


Statement cont
Statement has two parts:
Declaration
The part of the program that tells the
compiler the names of memory cells in a
program
Executable statements
Program lines that are converted to
machine language instructions and executed
by the computer

prepared by NI, edited by MAF


C Program Structure
An example of simple program in C
#include <stdio.h>
#define KMS_PER_MILE 1.609

int
main(void)
{
double miles; /*input distance in miles*/
Declarations Comments
double kms; //output distance in kms//

printf (Enter the distance in miles>); Executable statements


scanf (%lf, &miles); Executable statements

kms = KMS_PER_MILE * miles; Executable statements

printf(That equals %f kilometers,\n, kms); Executable statements

return (0); Executable statements


}

prepared by NI, edited by MAF


Identifiers
Words used to represent certain program
entities (variables, function names, etc).
Example:
int my_name;
my_name is an identifier used as a program
variable
void CalculateTotal(int value)
CalculateTotal is an identifier used as a function
name

prepared by NI, edited by MAF


Rules for naming identifiers
Rules Example
Can contain a mix of character and numbers. However it H2o
cannot start with a number
First character must be a letter or underscore Number1
_area
Can be of mixed cases including underscore character XsquAre
my_num
Cannot contain any arithmetic operators R*S+T
or any other punctuation marks #@x%!!
Cannot be a C keyword/reserved word struct; printf;

Cannot contain a space My height


identifiers are case sensitive Tax != tax

prepared by NI, edited by MAF


Variables
Variable a name associated with a
memory cell whose value can change
Variable Declaration: specifies the type of a
variable
Example: int num;
Variable Definition: assigning a value to the
declared variable
Example: num = 5;

prepared by NI, edited by MAF


Basic Data Types
There are 4 basic data types :
int
float
double
char

int
used to declare numeric program variables of integer
type
whole numbers, positive and negative
keyword: int
int number;
number = 12;
prepared by NI, edited by MAF
Basic Data Types cont
float
fractional parts, positive and negative
keyword: float
float height;
height = 1.72;
double
used to declare floating point variable of higher
precision or higher range of numbers
exponential numbers, positive and negative
keyword: double
double valuebig;
valuebig = 12E-3; (is equal to 12X10-3)

prepared by NI, edited by MAF


Basic Data Types cont
char
equivalent to letters in English language
Example of characters:
Numeric digits: 0 - 9
Lowercase/uppercase letters: a - z and A - Z
Space (blank)
Special characters: , . ; ? / ( ) [ ] { } * & % ^ < > etc
single character
keyword: char
char my_letter; The declared character must be
enclosed within a single quote!
my_letter = 'U';
In addition, there are void, short, long, etc.

prepared by NI, edited by MAF


Input/Output Operations
Input operation
an instruction that copies data from an input
device into memory
Output operation
an instruction that displays information
stored in memory to the output devices
(such as the monitor screen)

prepared by NI, edited by MAF


Input/Output Functions
A C function that performs an input or output operation
A few functions that are pre-defined in the header file
stdio.h such as :
printf()
scanf()
getchar() & putchar()

prepared by NI, edited by MAF


The printf function
Used to send data to the standard output (usually
the monitor) to be printed according to specific
format.
General format:
printf(string literal);
A sequence of any number of characters surrounded by double
quotation marks.
printf(format string, variables);
Format string is a combination of text, conversion specifier and
escape sequence.

prepared by NI, edited by MAF


The printf function
Example:
printf(Thank you);
printf (Total sum is: %d\n, sum);
%d is a placeholder (conversion specifier)
marks the display position for a type integer variable
\n is an escape sequence
moves the cursor to the new line

prepared by NI, edited by MAF


Common Variable Types Placeholders

Variable Type Placeholder


int %d
float %f
double %f
char %c
string %s

prepared by NI, edited by MAF


Escape Sequence
Escape Sequence Effect
\a Beep sound
\b Backspace
\f Formfeed (for printing)
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\\ Backslash
\ sign
\o Octal decimal
\x Hexadecimal
\O NULL

prepared by NI, edited by MAF


The scanf function
Read data from the standard input device (usually
keyboard) and store it in a variable.
General format:
scanf(Format string, &variable);
Notice ampersand (&) operator :
C address of operator
it passes the address of the variable instead of the variable
itself
tells the scanf() where to find the variable to store the new
value

prepared by NI, edited by MAF


The scanf function
Example :
int age;
printf(Enter your age: );
scanf(%d, &age);

Common Conversion Identifier used in printf and scanf


functions. printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
string %s %s

prepared by NI, edited by MAF


The scanf function
If you want the user to enter more than one value, you
serialise the inputs.
Example:
float height, weight;

printf(Please enter your height and weight:);


scanf(%f%f, &height, &weight);

prepared by NI, edited by MAF


getchar() and putchar()
getchar() - read a character from standard input
putchar() - write a character to standard output
Example: #include <stdio.h>
int main(void)
{
char my_char;
printf(Please type a character: );
my_char = getchar();
printf(\nYou have typed this character: );
putchar(my_char);
return 0;
}
prepared by NI, edited by MAF
getchar() and putchar() cont
Alternatively, you can write the previous code using
normal scanf and %c placeholder.
Example
#include <stdio.h>
int main(void)
{
char my_char;
printf(Please type a character: );
scanf(%c,&my_char);
printf(\nYou have typed this character: %c , my_char);
return 0;
}

prepared by NI, edited by MAF


Few notes on C program
C is case-sensitive
Word, word, WorD, WORD, WOrD, worD, etc are all different
variables / expressions
Eg. sum = 23 + 7
What is the value of Sum after this addition ?

Comments (remember 'Documentation'; Chapter 2)


are inserted into the code using /* to start and */ to end a
comment
Some compiler support comments starting with //
Provides supplementary information but is ignored by the
preprocessor and compiler
/* This is a comment */
// This program was written by Hanly Koffman

prepared by NI, edited by MAF


Few notes on C program
Reserved Words
Keywords that identify language entities such as statements,
data types, language attributes, etc.
Have special meaning to the compiler, cannot be used as
identifiers (variable, function name) in our program.
Should be typed in lowercase.
Example: const, double, int, main, void,printf, while, for, else
(etc..)

prepared by NI, edited by MAF


Few notes on C program
Punctuators (separators)
Symbols used to separate different parts of the C program.
These punctuators include:
[ ] ( ) { } , ; : * #
Usage example:
int main void()
{
int num = 10;
printf(%d, num);
return 0;
}

prepared by NI, edited by MAF


Few notes on C program
Operators
Tokens that result in some kind of computation or action when
applied to variables or other elements in an expression.
Example of operators:
*+=-/
Usage example:
result = total1 + total2;

prepared by NI, edited by MAF


Common Programming Errors
Debugging Process removing errors from a
program (called bugs)
Types of errors :
Syntax Error
a violation of the C grammar rules, detected during
program translation (compilation).
statement cannot be translated and program cannot
be executed

prepared by NI, edited by MAF


Common Programming Errors cont
Run-time errors
An attempt to perform an invalid operation, detected
during program execution.
Occurs when the program directs the computer to
perform an illegal operation, such as dividing a
number by zero.
The computer will stop executing the program, and
displays a diagnostic message indicates the line where
the error was detected

prepared by NI, edited by MAF


Common Programming Errors cont
Logic Error/Design Error
An error caused by following an incorrect
algorithm
Very difficult to detect - it does not cause run-time
error and does not display message errors.
The only sign of logic error incorrect program
output
Can be detected by testing the program thoroughly,
comparing its output to calculated results
To prevent carefully desk checking the algorithm
and written program before you actually type it

prepared by NI, edited by MAF


Summary
In this chapter, you have learned the following items:
environment of C language and C programming
C language elements
Preprocessor directives, curly braces, main (), semicolon, comments,
double quotes
4 basics data type and brief explanation on variable
6 tokens : reserved word, identifier, constant, string literal,
punctuators / separators and operators.
printf, scanf, getchar and putchar
Usage of modifiers : placeholder & escape sequence
Common programming errors : syntax error, run-time error and
logic error

prepared by NI, edited by MAF

You might also like