SlideShare a Scribd company logo
Fundamental of C Programming Language
and
Basic Input/Output Function
1
Chapter 3: 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
2
C Development Environment
Principles of Programming - NI 2005 3
DiskPhase 2 :
Preprocessor
program
processes the
code.
DiskCompilerPhase 3 :
Compiler
creates object
code and stores
it on Disk.
Preprocessor
DiskLinkerPhase 4 :
EditorPhase 1 :
Program is
created using the
Editor and
stored on Disk.
Disk
Linker links object
code with libraries,
creates a.out and
stores it on Disk
C Development Environment cont
Principles of Programming - NI 2005 4
LoaderPhase 5 :
:
.
Primary
Memory
Loader puts
Program in
Memory
C P U (execute)Phase 6 :
:
.
Primary
Memory
CPU takes each
instruction and
executes it, storing
new data values as
the program executes.
Principles of Programming - NI 2005 5
Entering, translating, and running a High-Level Language
Program
C Program Structure
• An example of simple program in C
#include <stdio.h>
void main(void)
{
printf(“I love programmingn”);
printf(“You will love it too once ”);
printf(“you know the trickn”);
}
Principles of Programming - NI 2005 6
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
Principles of Programming - NI 2005 7
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().
Principles of Programming - NI 2005 8
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.
• 4 common ways of main declaration
Principles of Programming - NI 2005 9
int main(void)
{
return 0;
}
void main(void)
{
}
main(void)
{
}
main( )
{
}
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)
Principles of Programming - NI 2005 10
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>
void main(void)
{
printf(“I love programmingn”);
printf(“You will love it too once ”);
printf(“you know the trickn”);
}
Principles of Programming - NI 2005 11
statement
statement
statement
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
Principles of Programming - NI 2005 12
C program skeleton
• In short, the basic skeleton of a C program
looks like this:
#include <stdio.h>
void main(void)
{
statement(s);
}
Principles of Programming - NI 2005 13
Preprocessor directives
Function main
Start of segment
End of segment
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
Principles of Programming - NI 2005 14
Rules for naming identifiers
Principles of Programming - NI 2005 15
Rules Example
Can contain a mix of characters and numbers.
However it cannot start with a number
H2o
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
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;
Principles of Programming - NI 2005 16
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;
Principles of Programming - NI 2005 17
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;
Principles of Programming - NI 2005 18
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;
my_letter = 'U';
• In addition, there are void, short, long, etc.
Principles of Programming - NI 2005 19
The declared character must be
enclosed within a single quote!
Constants
• Entities that appear in the program code as fixed values.
• Any attempt to modify a CONSTANT will result in error.
• 4 types of constants:
– Integer constants
• Positive or negative whole numbers with no fractional part
• Example:
– const int MAX_NUM = 10;
– const int MIN_NUM = -90;
– Floating-point constants (float or double)
• Positive or negative decimal numbers with an integer part, a
decimal point and a fractional part
• Example:
– const double VAL = 0.5877e2; (stands for 0.5877
x 102
)
Principles of Programming - NI 2005 20
Constants cont…
– Character constants
• A character enclosed in a single quotation mark
• Example:
– const char letter = ‘n’;
– const char number = ‘1’;
– printf(“%c”, ‘S’);
» Output would be: S
– Enumeration
• Values are given as a list
• Example:
Principles of Programming - NI 2005 21
enum Language {
Malay,
English,
Arabic
};
Constant example – volume of a cone
#include <stdio.h>
void main(void)
{
const double pi = 3.412;
double height, radius, base, volume;
printf(“Enter the height and radius of the cone:”);
scanf(“%lf %lf”,&height, &radius);
base = pi * radius * radius;
volume = (1.0/3.0) * base * height;
printf(“nThe volume of a cone is %f ”, volume);
}
Principles of Programming - NI 2005 22
#define
• You may also associate constant using #define preprocessor directive
#include <stdio.h>
#define pi 3.412
void main(void)
{
double height, radius, base, volume;
printf(“Enter the height and radius of the cone:”);
scanf(“%lf %lf”,&height,&radius);
base = pi * radius * radius;
volume = (1.0/3.0) * base * height;
printf(“nThe volume of a cone is %f ”, volume);
}
Principles of Programming - NI 2005 23
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)
Principles of Programming - NI 2005 24
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()
Principles of Programming - NI 2005 25
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.
Principles of Programming - NI 2005 26
The printf function cont…
• Example:
– printf(“Thank you”);
– printf (“Total sum is: %dn”, 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
Principles of Programming - NI 2005 27
Escape Sequence
Principles of Programming - NI 2005 28
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
Placeholder / Conversion Specifier
Principles of Programming - NI 2005 29
No Conversion
Specifier
Output Type Output Example
1 %d Signed decimal integer 76
2 %i Signed decimal integer 76
3 %o Unsigned octal integer 134
4 %u Unsigned decimal integer 76
5 %x Unsigned hexadecimal (small letter) 9c
6 %X Unsigned hexadecimal (capital letter) 9C
7 %f Integer including decimal point 76.0000
8 %e Signed floating point (using e notation) 7.6000e+01
9 %E Signed floating point (using E notation) 7.6000E+01
10 %g The shorter between %f and %e 76
11 %G The shorter between %f and %E 76
12 %c Character ‘7’
13 %s String ‘76'
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
Principles of Programming - NI 2005 30
The scanf function cont…
• Example :
int age;
printf(“Enter your age: “);
scanf(“%d”, &age);
• Common Conversion Identifier used in printf and
scanf functions.
Principles of Programming - NI 2005 31
printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
string %s %s
The scanf function cont…
• 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);
Principles of Programming - NI 2005 32
getchar() and putchar()
• getchar() - read a character from standard
input
• putchar() - write a character to standard
output
• Example:
Principles of Programming - NI 2005 33
#include <stdio.h>
void main(void)
{
char my_char;
printf(“Please type a character: ”);
my_char = getchar();
printf(“nYou have typed this character: ”);
putchar(my_char);
}
getchar() and putchar() cont
• Alternatively, you can write the previous code
using normal scanf and %c placeholder.
• Example
Principles of Programming - NI 2005 34
#include <stdio.h>
void main(void)
{
char my_char;
printf(“Please type a character: ”);
scanf(“%c”,&my_char);
printf(“nYou have typed this character: %c ”, my_char);
}
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
Principles of Programming - NI 2005 35
Few notes on C program cont…
• 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..)
Principles of Programming - NI 2005 36
Few notes on C program cont…
• Punctuators (separators)
– Symbols used to separate different parts of the C
program.
– These punctuators include:
[ ] ( ) { } , ; “: * #
– Usage example:
Principles of Programming - NI 2005 37
void main (void)
{
int num = 10;
printf (“% d”,num);
}
Few notes on C program cont…
• 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;
Principles of Programming - NI 2005 38
Common Programming Errors
• Debugging  Process removing errors from a
program
• Three (3) kinds 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
Principles of Programming - NI 2005 39
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
Principles of Programming - NI 2005 40
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
Principles of Programming - NI 2005 41
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
Principles of Programming - NI 2005 42

More Related Content

What's hot

Concepts of C [Module 2]
Concepts of C [Module 2]Concepts of C [Module 2]
Concepts of C [Module 2]
Abhishek Sinha
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
Vivek chan
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
sachindane
 
Managing input and output operations in c
Managing input and output operations in cManaging input and output operations in c
Managing input and output operations in c
niyamathShariff
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
C program compiler presentation
C program compiler presentationC program compiler presentation
C program compiler presentation
Rigvendra Kumar Vardhan
 
Important C program of Balagurusamy Book
Important C program of Balagurusamy BookImportant C program of Balagurusamy Book
Important C program of Balagurusamy Book
Abir Hossain
 
C language basics
C language basicsC language basics
C language basics
Milind Deshkar
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
Open Gurukul
 
C language basics
C language basicsC language basics
C language basics
Nikshithas R
 
7. input and output functions
7. input and output functions7. input and output functions
7. input and output functions
Way2itech
 
C programming language
C programming languageC programming language
C programming language
Mahmoud Eladawi
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
Kamal Acharya
 
Programming in C [Module One]
Programming in C [Module One]Programming in C [Module One]
Programming in C [Module One]
Abhishek Sinha
 
Moving Average Filter in C
Moving Average Filter in CMoving Average Filter in C
Moving Average Filter in C
Colin
 
Input and output in c
Input and output in cInput and output in c
Input and output in cRachana Joshi
 
C programming
C programmingC programming
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
Sabik T S
 

What's hot (19)

Concepts of C [Module 2]
Concepts of C [Module 2]Concepts of C [Module 2]
Concepts of C [Module 2]
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Managing input and output operations in c
Managing input and output operations in cManaging input and output operations in c
Managing input and output operations in c
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Input And Output
 Input And Output Input And Output
Input And Output
 
C program compiler presentation
C program compiler presentationC program compiler presentation
C program compiler presentation
 
Important C program of Balagurusamy Book
Important C program of Balagurusamy BookImportant C program of Balagurusamy Book
Important C program of Balagurusamy Book
 
C language basics
C language basicsC language basics
C language basics
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
 
C language basics
C language basicsC language basics
C language basics
 
7. input and output functions
7. input and output functions7. input and output functions
7. input and output functions
 
C programming language
C programming languageC programming language
C programming language
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
Programming in C [Module One]
Programming in C [Module One]Programming in C [Module One]
Programming in C [Module One]
 
Moving Average Filter in C
Moving Average Filter in CMoving Average Filter in C
Moving Average Filter in C
 
Input and output in c
Input and output in cInput and output in c
Input and output in c
 
C programming
C programmingC programming
C programming
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
 

Viewers also liked

C progrmming
C progrmmingC progrmming
C progrmming
Shivam Singhal
 
Semiconductors summary
Semiconductors summarySemiconductors summary
Semiconductors summaryradebethapi
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
Bharat Kalia
 
Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Basic c programming and explanation PPT1
Basic c programming and explanation PPT1
Rumman Ansari
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
Cbasic
CbasicCbasic
Cbasic
rohitladdu
 

Viewers also liked (8)

C progrmming
C progrmmingC progrmming
C progrmming
 
Semiconductors summary
Semiconductors summarySemiconductors summary
Semiconductors summary
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
Semiconductors
SemiconductorsSemiconductors
Semiconductors
 
Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Basic c programming and explanation PPT1
Basic c programming and explanation PPT1
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Cbasic
CbasicCbasic
Cbasic
 

Similar to C fundamentals

Cpu
CpuCpu
c_pro_introduction.pptx
c_pro_introduction.pptxc_pro_introduction.pptx
c_pro_introduction.pptx
RohitRaj744272
 
cmp104 lec 8
cmp104 lec 8cmp104 lec 8
cmp104 lec 8kapil078
 
424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt
advRajatSharma
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
imtiazalijoono
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
vanshhans21102005
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
kiranrajat
 
C programming language
C programming languageC programming language
C programming language
Abin Rimal
 
c-programming
c-programmingc-programming
c-programming
Zulhazmi Harith
 
Cse115 lecture04introtoc programming
Cse115 lecture04introtoc programmingCse115 lecture04introtoc programming
Cse115 lecture04introtoc programming
Md. Ashikur Rahman
 
Introduction to C
Introduction to CIntroduction to C
Introduction to C
Janani Satheshkumar
 
Zaridah lecture2
Zaridah lecture2Zaridah lecture2
Zaridah lecture2Aziz Sahat
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
nTier Custom Solutions
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptx
Mangala R
 
Discussing Fundamentals of C
Discussing Fundamentals of CDiscussing Fundamentals of C
Discussing Fundamentals of C
educationfront
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
SREEVIDYAP10
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
JAYA
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
MOHAMAD NOH AHMAD
 

Similar to C fundamentals (20)

Cpu
CpuCpu
Cpu
 
c_pro_introduction.pptx
c_pro_introduction.pptxc_pro_introduction.pptx
c_pro_introduction.pptx
 
cmp104 lec 8
cmp104 lec 8cmp104 lec 8
cmp104 lec 8
 
424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
C programming language
C programming languageC programming language
C programming language
 
c-programming
c-programmingc-programming
c-programming
 
Cse115 lecture04introtoc programming
Cse115 lecture04introtoc programmingCse115 lecture04introtoc programming
Cse115 lecture04introtoc programming
 
Introduction to C
Introduction to CIntroduction to C
Introduction to C
 
Zaridah lecture2
Zaridah lecture2Zaridah lecture2
Zaridah lecture2
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptx
 
Discussing Fundamentals of C
Discussing Fundamentals of CDiscussing Fundamentals of C
Discussing Fundamentals of C
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Lec-1c.pdf
Lec-1c.pdfLec-1c.pdf
Lec-1c.pdf
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 

Recently uploaded

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 

Recently uploaded (20)

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 

C fundamentals

  • 1. Fundamental of C Programming Language and Basic Input/Output Function 1
  • 2. Chapter 3: 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 2
  • 3. C Development Environment Principles of Programming - NI 2005 3 DiskPhase 2 : Preprocessor program processes the code. DiskCompilerPhase 3 : Compiler creates object code and stores it on Disk. Preprocessor DiskLinkerPhase 4 : EditorPhase 1 : Program is created using the Editor and stored on Disk. Disk Linker links object code with libraries, creates a.out and stores it on Disk
  • 4. C Development Environment cont Principles of Programming - NI 2005 4 LoaderPhase 5 : : . Primary Memory Loader puts Program in Memory C P U (execute)Phase 6 : : . Primary Memory CPU takes each instruction and executes it, storing new data values as the program executes.
  • 5. Principles of Programming - NI 2005 5 Entering, translating, and running a High-Level Language Program
  • 6. C Program Structure • An example of simple program in C #include <stdio.h> void main(void) { printf(“I love programmingn”); printf(“You will love it too once ”); printf(“you know the trickn”); } Principles of Programming - NI 2005 6
  • 7. 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 Principles of Programming - NI 2005 7
  • 8. 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(). Principles of Programming - NI 2005 8
  • 9. 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. • 4 common ways of main declaration Principles of Programming - NI 2005 9 int main(void) { return 0; } void main(void) { } main(void) { } main( ) { }
  • 10. 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) Principles of Programming - NI 2005 10
  • 11. 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> void main(void) { printf(“I love programmingn”); printf(“You will love it too once ”); printf(“you know the trickn”); } Principles of Programming - NI 2005 11 statement statement statement
  • 12. 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 Principles of Programming - NI 2005 12
  • 13. C program skeleton • In short, the basic skeleton of a C program looks like this: #include <stdio.h> void main(void) { statement(s); } Principles of Programming - NI 2005 13 Preprocessor directives Function main Start of segment End of segment
  • 14. 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 Principles of Programming - NI 2005 14
  • 15. Rules for naming identifiers Principles of Programming - NI 2005 15 Rules Example Can contain a mix of characters and numbers. However it cannot start with a number H2o 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
  • 16. 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; Principles of Programming - NI 2005 16
  • 17. 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; Principles of Programming - NI 2005 17
  • 18. 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; Principles of Programming - NI 2005 18
  • 19. 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; my_letter = 'U'; • In addition, there are void, short, long, etc. Principles of Programming - NI 2005 19 The declared character must be enclosed within a single quote!
  • 20. Constants • Entities that appear in the program code as fixed values. • Any attempt to modify a CONSTANT will result in error. • 4 types of constants: – Integer constants • Positive or negative whole numbers with no fractional part • Example: – const int MAX_NUM = 10; – const int MIN_NUM = -90; – Floating-point constants (float or double) • Positive or negative decimal numbers with an integer part, a decimal point and a fractional part • Example: – const double VAL = 0.5877e2; (stands for 0.5877 x 102 ) Principles of Programming - NI 2005 20
  • 21. Constants cont… – Character constants • A character enclosed in a single quotation mark • Example: – const char letter = ‘n’; – const char number = ‘1’; – printf(“%c”, ‘S’); » Output would be: S – Enumeration • Values are given as a list • Example: Principles of Programming - NI 2005 21 enum Language { Malay, English, Arabic };
  • 22. Constant example – volume of a cone #include <stdio.h> void main(void) { const double pi = 3.412; double height, radius, base, volume; printf(“Enter the height and radius of the cone:”); scanf(“%lf %lf”,&height, &radius); base = pi * radius * radius; volume = (1.0/3.0) * base * height; printf(“nThe volume of a cone is %f ”, volume); } Principles of Programming - NI 2005 22
  • 23. #define • You may also associate constant using #define preprocessor directive #include <stdio.h> #define pi 3.412 void main(void) { double height, radius, base, volume; printf(“Enter the height and radius of the cone:”); scanf(“%lf %lf”,&height,&radius); base = pi * radius * radius; volume = (1.0/3.0) * base * height; printf(“nThe volume of a cone is %f ”, volume); } Principles of Programming - NI 2005 23
  • 24. 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) Principles of Programming - NI 2005 24
  • 25. 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() Principles of Programming - NI 2005 25
  • 26. 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. Principles of Programming - NI 2005 26
  • 27. The printf function cont… • Example: – printf(“Thank you”); – printf (“Total sum is: %dn”, 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 Principles of Programming - NI 2005 27
  • 28. Escape Sequence Principles of Programming - NI 2005 28 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
  • 29. Placeholder / Conversion Specifier Principles of Programming - NI 2005 29 No Conversion Specifier Output Type Output Example 1 %d Signed decimal integer 76 2 %i Signed decimal integer 76 3 %o Unsigned octal integer 134 4 %u Unsigned decimal integer 76 5 %x Unsigned hexadecimal (small letter) 9c 6 %X Unsigned hexadecimal (capital letter) 9C 7 %f Integer including decimal point 76.0000 8 %e Signed floating point (using e notation) 7.6000e+01 9 %E Signed floating point (using E notation) 7.6000E+01 10 %g The shorter between %f and %e 76 11 %G The shorter between %f and %E 76 12 %c Character ‘7’ 13 %s String ‘76'
  • 30. 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 Principles of Programming - NI 2005 30
  • 31. The scanf function cont… • Example : int age; printf(“Enter your age: “); scanf(“%d”, &age); • Common Conversion Identifier used in printf and scanf functions. Principles of Programming - NI 2005 31 printf scanf int %d %d float %f %f double %f %lf char %c %c string %s %s
  • 32. The scanf function cont… • 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); Principles of Programming - NI 2005 32
  • 33. getchar() and putchar() • getchar() - read a character from standard input • putchar() - write a character to standard output • Example: Principles of Programming - NI 2005 33 #include <stdio.h> void main(void) { char my_char; printf(“Please type a character: ”); my_char = getchar(); printf(“nYou have typed this character: ”); putchar(my_char); }
  • 34. getchar() and putchar() cont • Alternatively, you can write the previous code using normal scanf and %c placeholder. • Example Principles of Programming - NI 2005 34 #include <stdio.h> void main(void) { char my_char; printf(“Please type a character: ”); scanf(“%c”,&my_char); printf(“nYou have typed this character: %c ”, my_char); }
  • 35. 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 Principles of Programming - NI 2005 35
  • 36. Few notes on C program cont… • 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..) Principles of Programming - NI 2005 36
  • 37. Few notes on C program cont… • Punctuators (separators) – Symbols used to separate different parts of the C program. – These punctuators include: [ ] ( ) { } , ; “: * # – Usage example: Principles of Programming - NI 2005 37 void main (void) { int num = 10; printf (“% d”,num); }
  • 38. Few notes on C program cont… • 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; Principles of Programming - NI 2005 38
  • 39. Common Programming Errors • Debugging  Process removing errors from a program • Three (3) kinds 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 Principles of Programming - NI 2005 39
  • 40. 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 Principles of Programming - NI 2005 40
  • 41. 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 Principles of Programming - NI 2005 41
  • 42. 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 Principles of Programming - NI 2005 42