Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Input Output
Key board Storage Program Storage Area
Storage Monitor
Mouse Area Area Printer
Working Storage Area
Input Devices Output Devices
Primary or Main Memory (RAM)
Register 1
Register 2 Arithmetic
and
Register N
Logic Unit
Micro Processor
#include<stdio.h> start
#include<conio.h> Flow chart:
main() read num
{
int num;
printf(Enter any number); If No
Yes
scanf(%d,&num); num%2=0
if(num%2==0)
printf(%d is even,num);
else print num print num
printf(%d is odd,num); is odd
is even
}
(Program in C language) stop
Flow chart symbols
Oval Terminal
Parallegram Input/output
Rectangle Process
Diamond Decision
Circle Connector
Hexagon Iteration
1 #include<stdio.h>
2 int main(void)
The only language the computer can understand is machine
3 { language (binary language).
4 int n1, n2,product;
5 printf(Enter two numbers : ); A high level language is an English like language where one
6 scanf(%d %d,&n1,&n2); instruction typically translates into a series of machine-
7 product = n1 * n2; language instructions.
8 printf(%d,product);
9 return 0;
A low level language corresponds closely to machine code
1 }
0
so that a single low-level language instruction translates to a
single machine language instruction.
Language Translation
Translator Assembler
is a computer program that reads a Assembler is a software or a tool
program written in one language, that translates Assembly language
which is called the source to machine code.
language, and translates it in to
another language, which is called
the target language.
Assembler Compiler
Compiler is a program that
Compiler translates High level language
such as programs written in C,
C++ to machine code
Difference between Compiler and
Interpreter
No Compiler Interpreter
Interpreter Takes Single instruction as
1 Compiler Takes Entire program as input
input .
Errors are displayed after entire Errors are displayed for every
6
program is checked instruction interpreted (if any)
Example : C Compiler [Eg. cc, gcc, Example : Python Interpreter (Eg. IDLE,
7
ANSI C, Borland C, etc.] etc.)
Structure of C program
/*Program to find
Documentation/Comment Section
area and perimeter of Circle */
#include<stdio.h> Linkage/header file Section
#define PI 3.1415 Definition Section
float radius;
float area(); Global Declaration Section
float perimeter();
int main()
{
float a, p; Main Function Section
printf(Enter radius : );
scanf(%f,&radius); Local Declaration Part
a = area(); Executable Code Part
p = perimeter();
printf(Area of Circle : %f,a);
printf(Perimeter : %f,p);
}
float area()
Sub Program Section
{
return (PI * radius * radius);
Function1()
}
Function2()
float perimeter()
{
FunctionN()
return (2 * PI * radius);
}
Preprocessor Directives
Compilation & Linking
header file
source file stdio.h
helloworld.c
#include <stdio.h>
compiler
executable file
Helloworld.exe
9
Program Development Steps
1)Statement of Problem 4.a)Compilation
a) Working with existing system and using proper Translate the program into machine code. This
questionnaire, the problem should be explained process is called as Compilation. Syntactic errors are
clearly. found quickly at the time of compiling the program.
b) What inputs are available, outputs are required These errors occur due to the usage of wrong syntaxes
and what is needed for creating workable solution for the statements.
should be understood clearly. Eg: x=a*y+b
2)Analysis There is a syntax error in this statement, since, each
a) The method of solutions to solve the problem can and every statement in C language ends with a
be identified. semicolon (;).
b) We also judge that which method gives best
results among different methods of solution. 4.b)Execution
3)Designing The next step is Program execution. In this phase, we
a) Algorithms and flow charts will be prepared. may encounter two types of errors.
b) Keep focus on data, architecture, user interfaces Runtime Errors: these errors occur during the
and program components. execution of the program and terminates the program
4)Implementation abnormally.
The algorithms and flow charts developed in the Logical Errors: these errors occur due to incorrect
previous steps are converted into actual programs in usage of the instructions in the program. These errors
the high level languages like C. are neither detected during compilation or execution
nor cause any stoppage to the program execution but
produces incorrect ouz
Executing a C program
#include<stdio.h>
Text int main()
{ Translators are system software
Editor . prog1.c used to convert high-level
language program into
C-compiler compiles
machine-language code.
Compiler : Coverts the entire
010110 100 Syntax Yes source program at a time
. Errors?
01011 101 into object code file, and
No saves it in secondary storage
Object machine code permanently. The same
adds prog1.obj object machine code file will
Linker
be executed several times,
00101010
Executable whenever needed.
.
01010101 machine code Interpreter : Each statement of
prog1.exe source program is translated
machine code of
library file into machine code and
Executes executed immediately.
C-Runtime
Translation and execution of
Feeds
Runtime
each and every statement is
Input Yes repeated till the end of the
or Logic
Errors ? program. No object code is
saved. Translation is
repeated for every execution
Output of the source program.
Character Set of C-Language
Alphabets : A-Z and a-z
Digits : 0-9
Special Symbols : ~ ! @ # $ % ^ & ( ) _ - + = | \ { } [ ] : ;
<>,.?/
White Spaces : space , Horizontal tab, Vertical tab, New Line
Form Feed.
C-Language Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
inline
C-Tokens
Tokens : The smallest individual units of a C- program are called Tokens.
Key words, Identifiers, Constants, Operators, Delimiters.
Key words : have a predefined meaning and these meanings cannot be
changed. All keywords must be written in small letters.
Identifiers : names of variables, functions, structures, unions, macros, labels,
arrays etc.,
Rules for define identifiers :
a) First character must be alphabetic character or under score
b) Second character onwards alphabetic character of digit or under
score.
c) First 63 characters of an identifier are significant.
d) Cannot duplicate a key word.
e) May not have a space or any other special symbol except under
score.
f) C language is Case-sensitive.
C-Tokens
Constants : fixed values that do not change during execution of a program.
Boolean constants : 0 ( false) and 1 (true)
Character constants :
only one character enclosed between two single quotes
( except escape characters ).
Integer constants : +123, -3454 , 0235 (octal value),
0x43d98 ( hexa - decimal value)
54764U, 124356578L, 124567856UL
Float constants : 0.2 , 876.345, .345623 , 23.4E+8, 47.45e+6
String Constants : Hello world , Have a nice day!
Complex Constants : real part + imaginary part * I ex : 12.3 + 3.45 * I
Operators : a symbol, which indicates an operation to be performed.
Operators are used to manipulate data in program.
Delimiters : Language Pattern of c-language uses special kind of symbols
: (colon, used for labels) ; (semicolon terminates statement ) ( ) parameter list
[ ] ( array declaration and subscript ), { } ( block statement )
# ( hash for preprocessor directive ) , (comma variable separator )
printf() & scanf() functions
Returned values of printf() and scanf()
In C,
printf() returns the number of characters successfully written on the output
scanf() returns number of items successfully read.
int main()
int main ( ) {
{ char a;
printf(" %d", printf("%s", welcome")); printf("%d",scanf("%c",&a));
return 0 ; return 0;
} }
Code Meaning
\b Backspace/non-erase
\f Form feed
\n New line
\r Carriage return/clear screen
\t Horizontal tab
\" Double quote
\' Single quote
\\ Backslash
\v Vertical tab
\a Alert/bell sound (speaker beeps)
\? Question mark
Data Types ( pre-defined )
Type Typical Size in Bits Minimal Range
char 8 127 to 127
unsigned char 8 0 to 255
signed char 8 127 to 127
int 16 or 32 32,767 to 32,767
unsigned int 16 or 32 0 to 65,535
signed int 16 or 32 Same as int
short int 16 32,767 to 32,767
unsigned short int 16 0 to 65,535
signed short int 16 Same as short int
long int 32 2,147,483,647 to 2,147,483,647
long long int 64 (263) to 263 1 (Added by C99)
signed long int 32 Same as long int
unsigned long int 32 0 to 4,294,967,295
unsigned long long int 64 264 1 (Added by C99)
float 32 3.4e-38 to 3.4e+38
double 64 1.7e-308 to 1.7e+308
long double 80 3.4e-4932 to 1.1e+4932
void -- data type that not return any value
Value range of different types
Type Storage size Value range
Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable.
For example, storage space for int data type is 4 byte for 32 bit processor.
We can increase the range by using long int which is 8 byte. We can
decrease the range by using short int which is 2 byte.
Precedence and Associativity of Operators
Precdence Group Operators Associativity
(Highest to Lowest )
(param) subscript etc., ( ) [ ] >. LR
Unary operators - + ! ~ ++ (type) * & sizeof RL
Multiplicative */% LR
Additive + LR
Bitwise shift << >> LR
Relational < <= > >= LR
Equality = = != LR
Bitwise AND & LR
Bitwise exclusive OR ^ LR
Bitwise OR | LR
Logical AND && LR
Logical OR || LR
Conditional ?: RL
Assignment = += = *= /= %= &= ^= RL
|= <<= >>=
Comma , LR
Pre vs. Post Increment /
Decrement
#include <stdio.h>
int main()
{
int count=10;
printf("\n\n %d",count++);
printf("\n\n %d",++count);
printf("\n\n %d", --count);
printf("\n\n %d",count--);
printf("\n\n %d",count);
return 0;
}
Conditional/Decision Control
Statements
Simple if
if else
nested if else
If else ladder
if else if else
simple if: Entry if-else: Entry
Syntax:
(Condition) ? stmt 1 : stmt 2
Loop Control/ Iterative
Statements
while loop
for loop
do-while loop
Loop Statements
while (Entry controlled ) do-while (Exit controlled )
Entry
Entry
Test False
Condition Body of The loop
?
true Test False
Body of The loop Condition
?
Following Statement True Following Statement
/* average of 5 numbers */
/* sum of 1 to 10 numbers */
#include<stdio.h>
#include<stdio.h>
int main() {
int main() {
int count = 1;
int i = 1,sum = 0;
float x, sum = 0;
while(i<=10){
do {
sum = sum + i;
printf(x = );
i = i + 1;
scanf(%f,&x);
}
sum += x;
printf(Total : %d ,sum);
++ count;
}
} while(count <= 5);
printf(Average = %f , (sum/5))
}
Do while example
#include<stdio.h>
int main()
{
int n,i=1;
int sum=0;
printf("\n Enter N:");
scanf("%d",&n);
do
{
sum=sum+i;
i++;
} while(i<=10);
Initialization Statement
Increment Statement
False Test
Condition
?
True
Body of The loop
Following Statement
#include<stdio.h>
/* check whether a number is prime or not */
int main()
#include<stdio.h>
{
int main() {
int n,i;
int n,i,factors = 0;
int sum=0;
printf("Enter a number : ");
printf("\n Enter N:");
scanf("%d",&n);
scanf("%d",&n);
for(i = 1; i <= n; i++) {
for(i=1;i<=n;i++)
if((n % i)==0) ++factors;
{
}
sum=sum+i;
if (factors == 2)
}
printf("%d is prime number.",n);
printf("\n Sum of N natural number: %d",
else
sum);
printf("%d is not prime number.",n);
return 0;
}
}
Infinite for loop
Syntax:
for( ; ; )
Example
#include<stdio.h>
int main()
{
for(;;)
{
printf("\n Hello");
}
return 0;
}
#include<stdio.h>
int main()
{
int i=0;
while(i<20)
{
i++;
if (i==10)
break;
}
printf("\n%d",i);
return 0;
}
continue Statements
continue;
It is sometimes desirable to skip some
statements inside the loop. In such cases,
continue statements are used
Flow diagram of continue
Example
# include <stdio.h>
int main()
{
int i,num,product;
for(i=1,product=1;i<=4;++i)
{
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; / *In this program, when num equals to zero, it skips the statement product*=num
and continue the loop. */
product*=num;
}
printf("product=%d",product);
return 0;
}
Output: ?
#include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; continue; printf("Nothing to see\n"); } return 0; }
#include <stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
continue;
printf("Nothing to see\n");
}
printf("\n%d",i);
return 0;
}
Output:
?
goto statement
Syntax:
#include <stdio.h>
int main()
{
int i;
for (i=1;i<=3;i++)
{
MIT:
goto MITS;
}
MITS: printf("\n Hello...");
goto MIT;
return 0;
}
Output:
NoVote:
printf("you are not eligible to vote");
goto Exit;
Exit:
return 0;
}
exit() function
C library function
#include<stdlib.h>
Terminates the calling process immediately
#include <stdio.h>
#include <stdlib.h>
int main ()
{
printf("Start of the program....\n");
printf("Exiting the program....\n");
exit(0);
printf("End of the program....\n");
return 0;
}
Class room Exercise 1
Program to find numbers between 100 and 150 evenly
divisible by 3 [Use for loop & if simple statement]
Program to generate multiplication tables of user choice.
[use any loop]
Program to find the biggest of three numbers. [use nested
if statement]
Program to print the week name for an entered digit [For
instance, if 1 is entered as input, Monday should be
printed as output] [Use switch case statement]
Program for conversion of upper case to lower case
alphabet [use ASCII logic]
Class room Exercise 2
C program to Print all the even numbers between two
limits. (For instance, if the inputs r1=5, r2=34, output must
be 6, 8, 10, 12,., 30,32,33)
C Program to Check Vowel or consonant [Hint: use switch
case stmt or if statement]
C program to print all the numbers divisible by 6 but not
multiple of 5 between two ranges.
C Program to print N numbers in reverse order [For
instance, if input N=12, the output must be,
12,11,10,9,8,7,6,5,4,3,2,1]
C Program to Display Fibonacci Sequence
Class room Exercise 3
C program to find sum of odd numbers between two
ranges.
C program to find sum of even numbers between two
ranges.
C program to print the digits in words from 1 to 99. [use
switch case]
Example
//Upper to Lower case
#include<stdio.h>
int main()
{
char a,b;
printf("\n Enter a character:");
scanf("%c",&a);
if(a>=65 && a<=90)
b=a+32;
printf("\n %c",b);
return 0;
}
Homework Exercises
int main()
{
int number, rem, sum = 0, i;
printf("Enter a Number\n");
scanf("%d", &number);
for (i = 1; i <= (number - 1); i++)
{
rem = number % i;
if (rem == 0)
{
sum = sum + i;
}
}
if (sum == number)
printf("Entered Number is perfect number");
else
printf("Entered Number is not a perfect number");
return 0;
}
Armstrong number
#include <stdio.h>
main()
{
int number, temp, digit1, digit2, digit3;
void main()
{
long i, k;