SlideShare a Scribd company logo
1 of 41
1
Chapter 3
Fundamental of C Programming
Language
and
Basic Input/Output Function
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
3
C Development Environment
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
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
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”);
}
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().
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
int main(void)
{
return 0;
}
void main(void)
{
}
main(void)
{
}
main( )
{
}
9
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)
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”);
}
statement
statement
statement
11
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
12
C program skeleton
In short, the basic skeleton of a C program
looks like this:
#include <stdio.h>
void main(void)
{
statement(s);
}
Preprocessor directives
Function main
Start of segment
End of segment
13
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
14
Rules for naming identifiers
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
15
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;
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;
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;
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.
The declared character must be
enclosed within a single quote!
19
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)
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: enum Language {
Malay,
English,
Arabic
};
21
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);
}
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);
}
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)
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()
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.
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
27
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
28
Placeholder / Conversion Specifier
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'
29
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
30
The scanf function cont…
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
31
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);
32
getchar() and putchar()
getchar() - read a character from standard
input
putchar() - write a character to standard
output
Example: #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);
}
33
getchar() and putchar() cont
Alternatively, you can write the previous code
using normal scanf and %c placeholder.
Example
#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);
}
34
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
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..)
36
Few notes on C program cont…
Punctuators (separators)
Symbols used to separate different parts of
the C program.
These punctuators include:
[ ] ( ) { } , ; “: * #
Usage example:
void main (void)
{
int num = 10;
printf (“% d”,num);
}
37
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;
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
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
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
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

More Related Content

What's hot

C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1Vikram Nandini
 
C fundamental
C fundamentalC fundamental
C fundamentalSelvam Edwin
 
Features of c
Features of cFeatures of c
Features of cHitesh Kumar
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic conceptsAbhinav Vatsa
 
Structure of C program
Structure of C programStructure of C program
Structure of C programPavan prasad
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CAshim Lamichhane
 
Unix - Filters
Unix - FiltersUnix - Filters
Unix - FiltersDr. Girish GS
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
Type conversion
Type conversionType conversion
Type conversionFrijo Francis
 
Pointers
PointersPointers
Pointerssanya6900
 
File Management in C
File Management in CFile Management in C
File Management in CPaurav Shah
 
Constant, variables, data types
Constant, variables, data typesConstant, variables, data types
Constant, variables, data typesPratik Devmurari
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAlpana Gupta
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
Memory management
Memory managementMemory management
Memory managementcpjcollege
 

What's hot (20)

C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
C fundamental
C fundamentalC fundamental
C fundamental
 
Features of c
Features of cFeatures of c
Features of c
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 
Structure of C program
Structure of C programStructure of C program
Structure of C program
 
Clanguage
ClanguageClanguage
Clanguage
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
Unix - Filters
Unix - FiltersUnix - Filters
Unix - Filters
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Type conversion
Type conversionType conversion
Type conversion
 
Pointers
PointersPointers
Pointers
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Constant, variables, data types
Constant, variables, data typesConstant, variables, data types
Constant, variables, data types
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Structures
StructuresStructures
Structures
 
Memory management
Memory managementMemory management
Memory management
 

Similar to Fundamental of C Programming Language and Basic Input/Output Function

Chapter3
Chapter3Chapter3
Chapter3Kamran
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)indrasir
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdfSergiuMatei7
 
C Basics
C BasicsC Basics
C BasicsSunil OS
 
c_pro_introduction.pptx
c_pro_introduction.pptxc_pro_introduction.pptx
c_pro_introduction.pptxRohitRaj744272
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5REHAN IJAZ
 
Cse115 lecture04introtoc programming
Cse115 lecture04introtoc programmingCse115 lecture04introtoc programming
Cse115 lecture04introtoc programmingMd. Ashikur Rahman
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdfDurga Padma
 
C programming
C programmingC programming
C programmingsaniabhalla
 
CP Handout#2
CP Handout#2CP Handout#2
CP Handout#2trupti1976
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingMOHAMAD NOH AHMAD
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
 
UNIT-II CP DOC.docx
UNIT-II CP DOC.docxUNIT-II CP DOC.docx
UNIT-II CP DOC.docxJavvajiVenkat
 
(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.pptatulchaudhary821
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C LanguageAdnan Khan
 
Unit-IV.pptx
Unit-IV.pptxUnit-IV.pptx
Unit-IV.pptxMehul Desai
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and OutputSabik T S
 

Similar to Fundamental of C Programming Language and Basic Input/Output Function (20)

Chapter3
Chapter3Chapter3
Chapter3
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
 
Unit 2- Module 2.pptx
Unit 2- Module 2.pptxUnit 2- Module 2.pptx
Unit 2- Module 2.pptx
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdf
 
C Basics
C BasicsC Basics
C Basics
 
c_pro_introduction.pptx
c_pro_introduction.pptxc_pro_introduction.pptx
c_pro_introduction.pptx
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
 
Introduction to Input/Output Functions in C
Introduction to Input/Output Functions in CIntroduction to Input/Output Functions in C
Introduction to Input/Output Functions in C
 
Cse115 lecture04introtoc programming
Cse115 lecture04introtoc programmingCse115 lecture04introtoc programming
Cse115 lecture04introtoc programming
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C programming
C programmingC programming
C programming
 
CP Handout#2
CP Handout#2CP Handout#2
CP Handout#2
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
UNIT-II CP DOC.docx
UNIT-II CP DOC.docxUNIT-II CP DOC.docx
UNIT-II CP DOC.docx
 
(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
 
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. AnsariBasic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
 
Unit-IV.pptx
Unit-IV.pptxUnit-IV.pptx
Unit-IV.pptx
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
 

More from imtiazalijoono

Embedded systems io programming
Embedded systems   io programmingEmbedded systems   io programming
Embedded systems io programmingimtiazalijoono
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripheralsimtiazalijoono
 
Importance of reading and its types.
Importance of reading and its types.Importance of reading and its types.
Importance of reading and its types.imtiazalijoono
 
Negative amplifiers and its types Positive feedback and Negative feedback
Negative amplifiers and its types Positive feedback  and Negative feedbackNegative amplifiers and its types Positive feedback  and Negative feedback
Negative amplifiers and its types Positive feedback and Negative feedbackimtiazalijoono
 
Multistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifierMultistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifierimtiazalijoono
 
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...
Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...imtiazalijoono
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge imtiazalijoono
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
Software Development Software development process
Software Development Software development processSoftware Development Software development process
Software Development Software development processimtiazalijoono
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions imtiazalijoono
 
C Building Blocks
C Building Blocks C Building Blocks
C Building Blocks imtiazalijoono
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
Programming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts TranslatorsProgramming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts Translatorsimtiazalijoono
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Conceptsimtiazalijoono
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variableimtiazalijoono
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayimtiazalijoono
 
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,imtiazalijoono
 
Arithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsArithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsimtiazalijoono
 
INTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGINTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGimtiazalijoono
 
COMPUTER PROGRAMMING
COMPUTER PROGRAMMINGCOMPUTER PROGRAMMING
COMPUTER PROGRAMMINGimtiazalijoono
 

More from imtiazalijoono (20)

Embedded systems io programming
Embedded systems   io programmingEmbedded systems   io programming
Embedded systems io programming
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripherals
 
Importance of reading and its types.
Importance of reading and its types.Importance of reading and its types.
Importance of reading and its types.
 
Negative amplifiers and its types Positive feedback and Negative feedback
Negative amplifiers and its types Positive feedback  and Negative feedbackNegative amplifiers and its types Positive feedback  and Negative feedback
Negative amplifiers and its types Positive feedback and Negative feedback
 
Multistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifierMultistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifier
 
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...
Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Software Development Software development process
Software Development Software development processSoftware Development Software development process
Software Development Software development process
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
C Building Blocks
C Building Blocks C Building Blocks
C Building Blocks
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Programming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts TranslatorsProgramming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts Translators
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Concepts
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variable
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
 
Arithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsArithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operators
 
INTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGINTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMING
 
COMPUTER PROGRAMMING
COMPUTER PROGRAMMINGCOMPUTER PROGRAMMING
COMPUTER PROGRAMMING
 

Recently uploaded

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)Dr. Mazin Mohamed alkathiri
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 

Recently uploaded (20)

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

Fundamental of C Programming Language and Basic Input/Output Function

  • 1. 1 Chapter 3 Fundamental of C Programming Language and Basic Input/Output Function
  • 2. 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
  • 3. 3 C Development Environment 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. 4 C Development Environment cont 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. 5 Entering, translating, and running a High-Level Language Program
  • 6. 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”); }
  • 7. 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().
  • 8. 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 int main(void) { return 0; } void main(void) { } main(void) { } main( ) { }
  • 9. 9 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)
  • 10. 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”); } statement statement statement
  • 11. 11 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
  • 12. 12 C program skeleton In short, the basic skeleton of a C program looks like this: #include <stdio.h> void main(void) { statement(s); } Preprocessor directives Function main Start of segment End of segment
  • 13. 13 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
  • 14. 14 Rules for naming identifiers 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
  • 15. 15 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;
  • 16. 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;
  • 17. 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;
  • 18. 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. The declared character must be enclosed within a single quote!
  • 19. 19 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)
  • 20. 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: enum Language { Malay, English, Arabic };
  • 21. 21 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); }
  • 22. 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); }
  • 23. 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)
  • 24. 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()
  • 25. 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.
  • 26. 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
  • 27. 27 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
  • 28. 28 Placeholder / Conversion Specifier 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'
  • 29. 29 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
  • 30. 30 The scanf function cont… 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
  • 31. 31 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);
  • 32. 32 getchar() and putchar() getchar() - read a character from standard input putchar() - write a character to standard output Example: #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); }
  • 33. 33 getchar() and putchar() cont Alternatively, you can write the previous code using normal scanf and %c placeholder. Example #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); }
  • 34. 34 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
  • 35. 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..)
  • 36. 36 Few notes on C program cont… Punctuators (separators) Symbols used to separate different parts of the C program. These punctuators include: [ ] ( ) { } , ; “: * # Usage example: void main (void) { int num = 10; printf (“% d”,num); }
  • 37. 37 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;
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. 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