SlideShare a Scribd company logo
Computer -- Hardware
Key board
Mouse
Input Devices
Monitor
Printer
Output Devices
Secondary Storage Devices
Input
Storage
Area
Program Storage Area
Output
Storage
Area
Working Storage Area
Primary or Main Memory (RAM)
Register 1
Arithmetic
and
Logic Unit
Register 2
……
……
Register N
Micro Processor
Algorithm: Step by step procedure of solving a particular problem.
Pseudo code: Artificial informal language used to develop algorithms.
Flow chart: Graphical representation of an algorithm.
Algorithm to find whether a number even or odd:
Step1: Begin Step1: START
Step2: Take a number Step2: Read num
Step3: if the number is divisible by2 then Step3: if(num%2=0) then
print that number is even print num is even
otherwise print that number is odd otherwise
print num is odd
Step4: End Step4: STOP
(Algorithm in natural language) (Algorithm by using pseudo code)
#include<stdio.h>
#include<conio.h>
main()
{
int num;
printf(“Enter any number”);
scanf(“%d”,&num);
if(num%2==0)
printf(“%d is even”,num);
else
printf(%d is odd”,num);
}
(Program in C language)
start
read num
print num
is even
stop
If numIf num
%2=0%2=0
print num
is odd
Flow chart:Flow chart:
YesYes NoNo
Flow chart symbols
Oval Terminal
Parallegram Input/output
Rectangle Process
Document Hard copy
Diamond Decision
Circle Connector
Double sided Rectangle Sub program
Hexagon Iteration
Trapezoid Manual Operation
Cylinder Magnetic Disk Storage
Machine Language – Assembly Language – High-Level Language
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
entry main,^m<r2>
sub12 #12,sp
jsb C$MAIN_ARGS
moveb $CHAR_STRING_CON
pusha1 -8(fp)
pusha1 (r2)
calls #2,SCANF
pusha1 -12(fp)
pusha1 3(r2)
calls #2,SCANF
mull3 -8(fp),-12(fp),-
pusha 6(fp)
calls #2,PRINTF
clrl r0
ret
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
00000000 00000100 0000000000000000
01011110 00001100 11000010 0000000000000010
11101111 00010110 0000000000000101
11101111 10111110 0000000000001011
11111000 10101101 11011111 0000000000010010
01100010 11011111 0000000000010101
11101111 00000010 11111011 0000000000010111
11110100 10101101 11011111 0000000000011110
00000011 10100010 11011111 0000000000100001
11101111 00000010 11011111 0000000000100100
01111110 11110100 10101101
11111000 10101110 11000101 0000000000101011
00000110 10100010 11111011 0000000000110001
11101111 00000010 11111011 0000000000110100
01010000 11010100 0000000000111011
00000100 0000000000111101
1
2
3
4
5
6
7
8
9
1
0
#include<stdio.h>
int main(void)
{
int n1, n2,product;
printf(“Enter two numbers : “);
scanf(“%d %d”,&n1,&n2);
product = n1 * n2;
printf(“%d”,product);
return 0;
}
The only language the computer can understand is machine
language (binary language).
A high level language is an English like language where one
instruction typically translates into a series of machine-
language instructions.
A low level language corresponds closely to machine code so
that a single low-level language instruction translates to a
single machine language instruction.
Language Translation
• Translator
– is a computer program that reads a
program written in one language,
which is called the source
language, and translates it in to
another language, which is called
the target language.
• Assembler
• Compiler
• Assembler
– Assembler is a software or a tool
that translates Assembly language
to machine code.
• Compiler
– Compiler is a program that
translates High level language such
as programs written in C, C++ to
machine code
Difference between Compiler
and Interpreter
No Compiler Interpreter
1 Compiler Takes Entire program as input
Interpreter Takes Single instruction as
input .
2 Intermediate Object Code is Generated No Intermediate Object Code is Generated
3
Conditional Control Statements are
Executes faster
Conditional Control Statements are
Executes slower
4
Memory Requirement : More(Since
Object Code is Generated)
Memory Requirement is Less
5 Program need not be compiledevery time
Every time higher level program is
converted into lower level program
6
Errors are displayed after entire
program is checked
Errors are displayed for every
instruction interpreted (if any)
7
Example : C Compiler [Eg. cc, gcc,
ANSI C, Borland C, etc.]
Example : Python Interpreter (Eg. IDLE,
etc.)
Structure of C program
/*Program to find/*Program to find
area and perimeter of Circle */area and perimeter of Circle */
#include<stdio.h>#include<stdio.h>
#define PI 3.1415#define PI 3.1415
float radius;float radius;
float area();float area();
float perimeter();float perimeter();
int main()int main()
{{
float a, p;float a, p;
printf(“Enter radius : “);printf(“Enter radius : “);
scanf(“%f”,&radius);scanf(“%f”,&radius);
a = area();a = area();
p = perimeter();p = perimeter();
printf(“Area of Circle : %f”,a);printf(“Area of Circle : %f”,a);
printf(“Perimeter : %f”,p);printf(“Perimeter : %f”,p);
}}
float area()float area()
{{
return (PI * radius * radius);return (PI * radius * radius);
}}
float perimeter()float perimeter()
{{
return (2 * PI * radius);return (2 * PI * radius);
}}
Documentation/Comment SectionDocumentation/Comment Section
Linkage/header file SectionLinkage/header file Section
Definition SectionDefinition Section
Global Declaration SectionGlobal Declaration Section
Main Function SectionMain Function Section
Local Declaration PartLocal Declaration Part
Executable Code PartExecutable Code Part
Sub Program SectionSub Program Section
Function1()Function1()
Function2()Function2()
…………………………
FunctionN()FunctionN()
Preprocessor DirectivesPreprocessor Directives
99
Compilation & Linking
helloworld.chelloworld.c
stdio.hstdio.h
#include <stdio.h>#include <stdio.h>
helloworld.ohelloworld.o
Helloworld.exeHelloworld.exe
header fileheader file
compilercompiler
linkerlinker
executable fileexecutable file
object fileobject file
source filesource file
Program Development Steps
1)Statement of Problem
a) Working with existing system and using proper
questionnaire, the problem should be explained
clearly.
b) What inputs are available, outputs are required
and what is needed for creating workable solution
should be understood clearly.
2)Analysis
a) The method of solutions to solve the problem can
be identified.
b) We also judge that which method gives best
results among different methods of solution.
3)Designing
a) Algorithms and flow charts will be prepared.
b) Keep focus on data, architecture, user interfaces
and program components.
4)Implementation
The algorithms and flow charts developed in the
previous steps are converted into actual programs in
the high level languages like C.
4.a)Compilation
Translate the program into machine code. This
process is called as Compilation. Syntactic errors are
found quickly at the time of compiling the program.
These errors occur due to the usage of wrong
syntaxes for the statements.
Eg: x=a*y+b
There is a syntax error in this statement, since, each
and every statement in C language ends with a
semicolon (;).
4.b)Execution
The next step is Program execution. In this phase, we
may encounter two types of errors.
Runtime Errors: these errors occur during the
execution of the program and terminates the program
abnormally.
Logical Errors: these errors occur due to incorrect
usage of the instructions in the program. These errors
are neither detected during compilation or execution
nor cause any stoppage to the program execution but
produces incorrect ouz
Executing a C program
compiles
Syntax
Errors?
Yes
Object machine code
010110 100
…………….
01011 101
C-compiler
#include<stdio.h>
int main()
{
…….
Text
Editor
prog1.c
prog1.obj
Linker
Executable
machine code
00101010
………….
01010101
adds
Translators are system software
used to convert high-level
language program into
machine-language code.
Compiler : Coverts the entire
source program at a time
into object code file, and
saves it in secondary storage
permanently. The same
object machine code file will
be executed several times,
whenever needed.
Interpreter : Each statement of
source program is translated
into machine code and
executed immediately.
Translation and execution of
each and every statement is
repeated till the end of the
program. No object code is
saved. Translation is
repeated for every execution
of the source program.
machine code of
library file
Input
prog1.exe
No
C-Runtime
Executes
Feeds
Runtime
or Logic
Errors ?
Yes
Output
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
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-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
int main ( )
{
printf(" %d", printf("%s", “welcome"));
return 0 ;
}
int main()
{
char a;
printf("%d",scanf("%c",&a));
return 0;
}
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.
Irrespective of the character that user
enters, this program prints 1
This program prints welcome 7
Careful to use scanf()
• The basic problem is that scanf() leaves the
newline after the number in the buffer, and
then reads it with %c on the next pass.
• This is a good demonstration of why we
need to cautious about to use scanf()
Conversion/Access/fomat Specifiers
CodeCode FormatFormat
%s String of characters (until null zero is reached )
%c Character
%d Decimal integer
%f Floating-point numbers
%e Exponential notation floating-point numbers
%u Unsigned integer
%o Octal integer
%x Hexadecimal integer
%i Signed decimal integer
%p Display a pointer
%hd short integer
%ld long integer
%lf long double
%% Prints a percent sign (%)
Back Slash ( Escape Sequence) Characters
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
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Data type modifiers in C
Used to change the properties of current properties ofUsed to change the properties of current properties of
data type. Data type modifiers are classified intodata type. Data type modifiers are classified into
following types.following types.
•longlong
•shortshort
•unsignedunsigned
•signedsigned
Data type modifiers in C
Modifiers are prefixed with basic data types to modify (eitherModifiers are prefixed with basic data types to modify (either increase orincrease or
decreasedecrease)) the amount of storage space allocated to a variablethe amount of storage space allocated to a variable..
For exampleFor example, storage space for, storage space for int data type is 4 byteint data type is 4 byte for 32 bit processor.for 32 bit processor.
We canWe can increaseincrease the range by usingthe range by using long int which is 8 bytelong int which is 8 byte. We can. We can
decreasedecrease the range by usingthe range by using short int which is 2 byteshort int which is 2 byte..
Precedence and Associativity of Operators
Precdence Group Operators Associativity
(Highest to Lowest )
(param) subscript etc., ( ) [ ] –>. L  R
Unary operators - + ! ~ ++ – – (type) * & sizeof R  L
Multiplicative * / % L  R
Additive + – L  R
Bitwise shift << >> L  R
Relational < <= > >= L  R
Equality = = != L  R
Bitwise AND & L  R
Bitwise exclusive OR ^ L  R
Bitwise OR | L  R
Logical AND && L  R
Logical OR | | L  R
Conditional ?: R  L
Assignment = += –= *= /= %= &= ^= R  L
|= <<= >>=
Comma , L  R
Conditional/Decision Control
Statements
• Simple if
• if… else
• nested if… else
• If else ladder
– if… else if… else
TestTest
ExpressionExpression
??
EntryEntry
FalseFalse
Next statementNext statement
True Statement-blockTrue Statement-block
TrueTrue
simple if:simple if:
TestTest
ExpressionExpression
??
EntryEntry
True-blockTrue-block
StatementsStatements
FalseFalse
False-blockFalse-block
StatementsStatements
TrueTrue
Next statementNext statement
if-else:if-else:
/* check a citizen is eligible for voting *//* check a citizen is eligible for voting */
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
int age;int age;
printf(“Enter the age : ”);printf(“Enter the age : ”);
scanf(“%d”,&age);scanf(“%d”,&age);
if(age >= 18)if(age >= 18)
printf(“Eligible for voting…”);printf(“Eligible for voting…”);
getch();getch();
}}
/* print a number is even or odd *//* print a number is even or odd */
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
int number;int number;
printf(“Enter a number : “);printf(“Enter a number : “);
scanf(“%d”, &number);scanf(“%d”, &number);
if((number %2) == 0)if((number %2) == 0)
printf(“%d is even number.”,number);printf(“%d is even number.”,number);
elseelse
printf(“%d is odd number.”,number);printf(“%d is odd number.”,number);
}}
TestTest
condition1condition1
??
EntryEntry
Statement-3Statement-3
TrueTrue
TestTest
condition2condition2
??
FalseFalse
Statement-2Statement-2 Statement-1Statement-1
TrueTrue
FalseFalse
Next statementNext statement
nested if…else:nested if…else: /* check whether a year is leap year or not *//* check whether a year is leap year or not */
#include<stdio.h>#include<stdio.h>
int main() {int main() {
int year;int year;
printf("Enter the year ?");printf("Enter the year ?");
scanf("%d",&year);scanf("%d",&year);
if((year %100) == 0)if((year %100) == 0)
{{
if((year % 400) == 0)if((year % 400) == 0)
printf("%d is leap year.",year);printf("%d is leap year.",year);
elseelse
printf("%d is not leap year.",year);printf("%d is not leap year.",year);
} else {} else {
if((year % 4) == 0)if((year % 4) == 0)
printf("%d is leap year.",year);printf("%d is leap year.",year);
elseelse
printf("%d is not leap year.",year);printf("%d is not leap year.",year);
}}
getch();getch();
}}
if…else…if :if…else…if :
EntryEntry
TestTest
condition1condition1
??
TrueTrue
Statement-1Statement-1
TrueTrue
Statement-2Statement-2
TestTest
condition2condition2
??
FalseFalse
TrueTrueTestTest
conditionNconditionN
??
FalseFalse
Statement-NStatement-N
Next statementNext statement
/* program to print the grade of student *//* program to print the grade of student */
#include<stdio.h>#include<stdio.h>
int main() {int main() {
int marks;int marks;
printf("Enter marks ? ");printf("Enter marks ? ");
scanf("%d", &marks);scanf("%d", &marks);
if(marks >= 75)if(marks >= 75)
printf("Distinction");printf("Distinction");
else if(marks >= 60)else if(marks >= 60)
printf("First class");printf("First class");
else if(marks >= 50)else if(marks >= 50)
printf("Second class");printf("Second class");
else if(marks >= 35)else if(marks >= 35)
printf("Third class");printf("Third class");
elseelse
printf("Failed");printf("Failed");
}}
switch statement :switch statement :
EntryEntry
switchswitch
expressionexpression
??
Next statementNext statement
/* program to simulate a simple calculator *//* program to simulate a simple calculator */
#include<stdio.h>#include<stdio.h>
int main() {int main() {
float a,b;float a,b;
char opr;char opr;
printf("Enter number1 operator number2 : ");printf("Enter number1 operator number2 : ");
scanf("%f %c %f",&a,&opr,&b);scanf("%f %c %f",&a,&opr,&b);
switch(opr)switch(opr)
{{
case '+':case '+':
printf("Sum : %f",(a + b));printf("Sum : %f",(a + b));
break;break;
case '-':case '-':
printf("Difference : %f",(a - b));printf("Difference : %f",(a - b));
break;break;
case '*':case '*':
printf("Product : %f",(a * b));printf("Product : %f",(a * b));
break;break;
case '/':case '/':
printf("Quotient : %f",(a / b));printf("Quotient : %f",(a / b));
break;break;
default:default:
printf("Invalid Operation!");printf("Invalid Operation!");
}}
}}
associateassociate
statementstatement
associateassociate
statementstatement
associateassociate
statementstatement
associateassociate
statementstatement
value1value1 value2value2 valueNvalueN defaultdefault
ExitExit
…………......
Example
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
int a,b;int a,b;
char choice;char choice;
printf("nInput 2 numbers:");printf("nInput 2 numbers:");
scanf("%d %d",&a,&b);scanf("%d %d",&a,&b);
printf("nEnter your choice:");printf("nEnter your choice:");
scanf("%c",&choice);scanf("%c",&choice);
switch(choice)switch(choice)
{{
case '+':case '+':
printf("nAddition:%d",(a+b));printf("nAddition:%d",(a+b));
break;break;
case '-':case '-':
printf("nSubtraction:%d",(a-b));printf("nSubtraction:%d",(a-b));
break;break;
default:default:
printf("nNo such choice available...");printf("nNo such choice available...");
break;break;
}}
return 0;return 0;
}}
?: - Conditional operator
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
flag = ((num%2==0)?1:0);
if(flag==0)
printf("nEven");
else
printf("nOdd");
}
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
}
Syntax:
(Condition) ? stmt 1 : stmt 2
Loop Control/ Iterative
Statements
• while loop
• for loop
• do-while loop
Test
Condition
?
Body of The loop
False
truetrue
while – (Entry controlled )while – (Entry controlled )
EntryEntry
Loop StatementsLoop Statements
Following Statement
Test
Condition
?
Body of The loop
False
TrueTrue
EntryEntry
Following Statement
do-while – (Exit controlled )do-while – (Exit controlled )
/* sum of 1 to 10 numbers *//* sum of 1 to 10 numbers */
#include<stdio.h>#include<stdio.h>
int main() {int main() {
int i = 1,sum = 0;int i = 1,sum = 0;
while(i<=10){while(i<=10){
sum = sum + i;sum = sum + i;
i = i + 1;i = i + 1;
}}
printf(“Total : %d “,sum);printf(“Total : %d “,sum);
}}
/* average of 5 numbers *//* average of 5 numbers */
#include<stdio.h>#include<stdio.h>
int main() {int main() {
int count = 1;int count = 1;
float x, sum = 0;float x, sum = 0;
do {do {
printf(“x = “);printf(“x = “);
scanf(“%f”,&x);scanf(“%f”,&x);
sum += x;sum += x;
++ count;++ count;
} while(count <= 5);} while(count <= 5);
printf(“Average = %f “, (sum/5))printf(“Average = %f “, (sum/5))
}}
Do while example
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
int n,i=1;int n,i=1;
int sum=0;int sum=0;
printf("n Enter N:");printf("n Enter N:");
scanf("%d",&n);scanf("%d",&n);
dodo
{{
sum=sum+i;sum=sum+i;
i++;i++;
} while(i<=10);} while(i<=10);
printf("n Sum of N natural number: %d", sum);printf("n Sum of N natural number: %d", sum);
return 0;return 0;
}}
for --for --
StatementStatement
Initialization Statement
Increment Statement
Test
Condition
?
Body of The loop
EntryEntry
TrueTrue
Following Statement
False
/* check whether a number is prime or not *//* check whether a number is prime or not */
#include<stdio.h>#include<stdio.h>
int main() {int main() {
int n,i,factors = 0;int n,i,factors = 0;
printf("Enter a number : ");printf("Enter a number : ");
scanf("%d",&n);scanf("%d",&n);
for(i = 1; i <= n; i++) {for(i = 1; i <= n; i++) {
if((n % i)==0) ++factors;if((n % i)==0) ++factors;
}}
if (factors == 2)if (factors == 2)
printf("%d is prime number.",n);printf("%d is prime number.",n);
elseelse
printf("%d is not prime number.",n);printf("%d is not prime number.",n);
}}
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
int n,i;int n,i;
int sum=0;int sum=0;
printf("n Enter N:");printf("n Enter N:");
scanf("%d",&n);scanf("%d",&n);
for(i=1;i<=n;i++)for(i=1;i<=n;i++)
{{
sum=sum+i;sum=sum+i;
}}
printf("n Sum of N natural number: %d",printf("n Sum of N natural number: %d",
sum);sum);
return 0;return 0;
}}
Infinite for loop
• Syntax:
– for( ; ; )
• Example
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
for(;;)for(;;)
{{
printf("n Hello");printf("n Hello");
}}
return 0;return 0;
}}
This program will print Hello infinite number of timesThis program will print Hello infinite number of times
Important Functions in math.h
abs(x) absolute value of integer x
ceil(x) rounds up and returns the smallest integer greater than or
equal to x
floor(x) rounds down and returns the largest integer less than or
equal to x
log(x) returns natural logarithm
pow(x,y) returns the value of xy
sqrt(x) returns square root of x
exp(x) returns natural anti logarithm
sin(x) returns sine value where x in radians
cos(x) returns cosine value where x in radians
tan(x) returns tangent values where x in radians
fmod(x,y) calculate x modulo y, where x and y are double
hypot(x,y) calculate hypotenuse of right angle where x,y are sides.
log10(x) returns logarithm base 10
Jump Statement
• break
• continue
• goto
break Statements
• break;
– break is used in terminating the loop
immediately after it is encountered
Flow diagram of break
Example
/* C program to demonstrate the working of break statement by terminating a loop, if/* C program to demonstrate the working of break statement by terminating a loop, if
user inputs negative number*/user inputs negative number*/
# include <stdio.h># include <stdio.h>
int main(){int main(){
float num,average,sum=0;float num,average,sum=0;
int i,n;int i,n;
printf("Maximum no. of inputsn");printf("Maximum no. of inputsn");
scanf("%d",&n);scanf("%d",&n);
for(i=1;i<=n;++i){for(i=1;i<=n;++i){
printf("Enter n%d: ",i);printf("Enter n%d: ",i);
scanf("%f",&num);scanf("%f",&num);
if(num<0.0)if(num<0.0)
break; //for loop breaks if num<0.0break; //for loop breaks if num<0.0
sum=sum+num;sum=sum+num;
}}
average=sum/(i-1);average=sum/(i-1);
printf("Average=%.2f",average);printf("Average=%.2f",average);
return 0;return 0;
}}
#include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; continue; printf("Nothing to seen"); } return 0; }
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
int i=0;int i=0;
while(i<20)while(i<20)
{{
i++;i++;
if (i==10)if (i==10)
break;break;
}}
printf("n%d",i);printf("n%d",i);
return 0;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># include <stdio.h>
int main()int main()
{{
int i,num,product;int i,num,product;
for(i=1,product=1;i<=4;++i)for(i=1,product=1;i<=4;++i)
{{
printf("Enter num%d:",i);printf("Enter num%d:",i);
scanf("%d",&num);scanf("%d",&num);
if(num==0)if(num==0)
continue; / *In this program, when num equals to zero, it skips the statement product*=numcontinue; / *In this program, when num equals to zero, it skips the statement product*=num
and continue the loop. */and continue the loop. */
product*=num;product*=num;
}}
printf("product=%d",product);printf("product=%d",product);
return 0;return 0;
}}
Output:Output: ??
Predict the output
#include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; continue; printf("Nothing to seen"); } return 0; }
#include <stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
continue;
printf("Nothing to seen");
}
printf("n%d",i);
return 0;
}
Output:
?
goto statement
• Syntax:
#include <stdio.h>#include <stdio.h>
int main()int main()
{{
int i;int i;
for (i=1;i<=3;i++)for (i=1;i<=3;i++)
{{
MIT:MIT:
goto MITS;goto MITS;
}}
MITS: printf("n Hello...");MITS: printf("n Hello...");
goto MIT;goto MIT;
return 0;return 0;
}}
Output:Output:
Indefinitely prints “Hello…”Indefinitely prints “Hello…”
Example
int main()int main()
{{
int age;int age;
Vote:Vote:
printf(“n you are eligible for voting");printf(“n you are eligible for voting");
NoVote:NoVote:
printf(“n you are not eligible to vote");printf(“n you are not eligible to vote");
printf(“n Enter you age:");printf(“n Enter you age:");
scanf("%d", &age);scanf("%d", &age);
if(age>=18)if(age>=18)
goto Vote;goto Vote;
elseelse
goto NoVote;goto NoVote;
return 0;return 0;
}}
Explanation:
•Vote and NoVote are labels.
•When the input is >= 18, the goto
statement is transferring the control to
label – Vote,
•Otherwise it transfers the control to
label-NoVote.
•This prints some unordered
outputs
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
int age;int age;
printf("Enter you age:");printf("Enter you age:");
scanf("%d", &age);scanf("%d", &age);
if(age>=18)if(age>=18)
gotogoto Vote;Vote;
elseelse
gotogoto NoVote;NoVote;
Vote:Vote:
printf("you are eligible for voting");printf("you are eligible for voting");
gotogoto Exit;Exit;
NoVote:NoVote:
printf("you are not eligible to vote");printf("you are not eligible to vote");
gotogoto Exit;Exit;
Exit:Exit:
return 0;return 0;
}}
Explanation:
•Vote and NoVote are labels.
•When the input is >= 18, the goto statement i
transferring the control to label – Vote,
•Otherwise it transfers the control to label-
NoVote.
•This prints ordered outputs
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]
Unit 1   c - all topics
Example
//Upper to Lower case//Upper to Lower case
#include<stdio.h>#include<stdio.h>
int main()int main()
{{
char a,b;char a,b;
printf("n Enter a character:");printf("n Enter a character:");
scanf("%c",&a);scanf("%c",&a);
if(a>=65 && a<=90)if(a>=65 && a<=90)
b=a+32;b=a+32;
printf("n %c",b);printf("n %c",b);
return 0;return 0;
}}
Homework Exercises
• C Program to Check whether a given Number is Armstrong
• C Program to Check whether a given Number is Perfect Number
– A perfect number is a positive integer that is equal to the sum of
its proper positive divisors
• C Program to Print Armstrong Number from 1 to 1000
• C Program to Swap the Contents of two Numbers using Bitwise XOR
Operation
Perfect Number
#include <stdio.h>
int main()
{
int number, rem, sum = 0, i;
printf("Enter a Numbern");
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>#include <stdio.h>
main()main()
{{
int number, temp, digit1, digit2, digit3;int number, temp, digit1, digit2, digit3;
printf("Print all Armstrong numbers between 1 and 1000:n");printf("Print all Armstrong numbers between 1 and 1000:n");
number = 001;number = 001;
while (number <= 900)while (number <= 900)
{{
digit1 = number - ((number / 10) * 10);digit1 = number - ((number / 10) * 10);
digit2 = (number / 10) - ((number / 100) * 10);digit2 = (number / 10) - ((number / 100) * 10);
digit3 = (number / 100) - ((number / 1000) * 10);digit3 = (number / 100) - ((number / 1000) * 10);
temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3);temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3);
if (temp == number)if (temp == number)
{{
printf("n Armstrong no is:%d", temp);printf("n Armstrong no is:%d", temp);
}}
number++;number++;
}}
}}
Swapping Binary number using
XOR operator
#include <stdio.h>#include <stdio.h>
void main()void main()
{{
long i, k;long i, k;
printf("Enter two integers n");printf("Enter two integers n");
scanf("%ld %ld", &i, &k);scanf("%ld %ld", &i, &k);
printf("n Before swapping i= %ld and k = %ld", i, k);printf("n Before swapping i= %ld and k = %ld", i, k);
i = i ^ k;i = i ^ k;
k = i ^ k;k = i ^ k;
i = i ^ k;i = i ^ k;
printf("n After swapping i= %ld and k = %ld", i, k);printf("n After swapping i= %ld and k = %ld", i, k);
}}

More Related Content

PPTX
Programming in C Basics
PPT
Introduction to c programming
PPT
Introduction to C Programming
PPTX
PDF
Introduction to C programming
PPTX
C_Programming_Notes_ICE
PDF
Advanced C Language for Engineering
PPTX
Introduction to C Programming
Programming in C Basics
Introduction to c programming
Introduction to C Programming
Introduction to C programming
C_Programming_Notes_ICE
Advanced C Language for Engineering
Introduction to C Programming

What's hot (20)

PDF
Learning the C Language
PPT
Fundamental of C Programming Language and Basic Input/Output Function
PPT
C program
DOC
C notes for exam preparation
PPTX
C Programming Language Tutorial for beginners - JavaTpoint
PPTX
PPT
Programming in c
PPT
introduction to C programming (C)
PDF
Hands-on Introduction to the C Programming Language
ODP
OpenGurukul : Language : C Programming
PPT
The smartpath information systems c pro
PPTX
Unit ii
PPT
Unit 4 Foc
PPTX
A brief introduction to C Language
PPTX
Introduction to c
PPT
Chapter3
PPT
Brief introduction to the c programming language
DOC
1. introduction to computer
PDF
C programming
PPTX
Learning the C Language
Fundamental of C Programming Language and Basic Input/Output Function
C program
C notes for exam preparation
C Programming Language Tutorial for beginners - JavaTpoint
Programming in c
introduction to C programming (C)
Hands-on Introduction to the C Programming Language
OpenGurukul : Language : C Programming
The smartpath information systems c pro
Unit ii
Unit 4 Foc
A brief introduction to C Language
Introduction to c
Chapter3
Brief introduction to the c programming language
1. introduction to computer
C programming
Ad

Viewers also liked (20)

PDF
Grade 9 Mathematics Module 5 Quadrilaterals (LM)
PDF
Personalized Information Retrieval system using Computational Intelligence Te...
PDF
Being Miss Geeky - WIT
PDF
Does Your Stuff Scale?
PDF
China high speed railway lines network-201407
PPT
Mh beethoven
PDF
Merkel wiper auas
PDF
02មហាគ្រោះជាតិខ្មែរ great danger-khmer-nation-official-khmerlanguage​​ by tie...
PDF
Marriott management philosophy
DOC
Report abc company draft
PDF
Effectivnoe upravlenie personalom
PDF
Emc cla rii on fibre channel storage fundamentals
PDF
1351 anglyskoe slovo_dlya_detey_i_vzroslykh
PDF
Helping Journalists Get It Right
PDF
HAKQ Profile
PDF
Solinea Lazuli Tower Project Brief
PDF
Obo mne
PDF
Propertics of element
PDF
Nidec asi capability overview for oil&gas applications
DOCX
Mu0012 – Employee relations management
Grade 9 Mathematics Module 5 Quadrilaterals (LM)
Personalized Information Retrieval system using Computational Intelligence Te...
Being Miss Geeky - WIT
Does Your Stuff Scale?
China high speed railway lines network-201407
Mh beethoven
Merkel wiper auas
02មហាគ្រោះជាតិខ្មែរ great danger-khmer-nation-official-khmerlanguage​​ by tie...
Marriott management philosophy
Report abc company draft
Effectivnoe upravlenie personalom
Emc cla rii on fibre channel storage fundamentals
1351 anglyskoe slovo_dlya_detey_i_vzroslykh
Helping Journalists Get It Right
HAKQ Profile
Solinea Lazuli Tower Project Brief
Obo mne
Propertics of element
Nidec asi capability overview for oil&gas applications
Mu0012 – Employee relations management
Ad

Similar to Unit 1 c - all topics (20)

PPT
Unit1 C
PPT
Unit1 C
PPT
C Lang notes.ppt
PPT
C Language Unit-1
PPT
Unit1 jwfiles
PPTX
C Programming Unit-1
PPT
What is turbo c and how it works
PPTX
C and its errors
PPTX
C++ lecture 01
PPTX
Chapter1.pptx
PPTX
C Language ppt create by Anand & Sager.pptx
PPTX
C lang7age programming powerpoint presentation
PDF
C programming introduction for beginners.pdf
DOCX
Lect '1'
PDF
C notes.pdf
PPTX
C++ programming language basic to advance level
PDF
Unit 2 introduction to c programming
PPTX
Introduction%20C.pptx
PPTX
C_Programming_Language_tutorial__Autosaved_.pptx
PPSX
C basics 4 std11(GujBoard)
Unit1 C
Unit1 C
C Lang notes.ppt
C Language Unit-1
Unit1 jwfiles
C Programming Unit-1
What is turbo c and how it works
C and its errors
C++ lecture 01
Chapter1.pptx
C Language ppt create by Anand & Sager.pptx
C lang7age programming powerpoint presentation
C programming introduction for beginners.pdf
Lect '1'
C notes.pdf
C++ programming language basic to advance level
Unit 2 introduction to c programming
Introduction%20C.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
C basics 4 std11(GujBoard)

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharma ospi slides which help in ospi learning
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
RMMM.pdf make it easy to upload and study
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Insiders guide to clinical Medicine.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
Pre independence Education in Inndia.pdf
PDF
Classroom Observation Tools for Teachers
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Microbial diseases, their pathogenesis and prophylaxis
Pharma ospi slides which help in ospi learning
PPH.pptx obstetrics and gynecology in nursing
RMMM.pdf make it easy to upload and study
Renaissance Architecture: A Journey from Faith to Humanism
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
TR - Agricultural Crops Production NC III.pdf
01-Introduction-to-Information-Management.pdf
Computing-Curriculum for Schools in Ghana
Anesthesia in Laparoscopic Surgery in India
Insiders guide to clinical Medicine.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Complications of Minimal Access Surgery at WLH
Pre independence Education in Inndia.pdf
Classroom Observation Tools for Teachers
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
O5-L3 Freight Transport Ops (International) V1.pdf

Unit 1 c - all topics

  • 1. Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Secondary Storage Devices Input Storage Area Program Storage Area Output Storage Area Working Storage Area Primary or Main Memory (RAM) Register 1 Arithmetic and Logic Unit Register 2 …… …… Register N Micro Processor
  • 2. Algorithm: Step by step procedure of solving a particular problem. Pseudo code: Artificial informal language used to develop algorithms. Flow chart: Graphical representation of an algorithm. Algorithm to find whether a number even or odd: Step1: Begin Step1: START Step2: Take a number Step2: Read num Step3: if the number is divisible by2 then Step3: if(num%2=0) then print that number is even print num is even otherwise print that number is odd otherwise print num is odd Step4: End Step4: STOP (Algorithm in natural language) (Algorithm by using pseudo code) #include<stdio.h> #include<conio.h> main() { int num; printf(“Enter any number”); scanf(“%d”,&num); if(num%2==0) printf(“%d is even”,num); else printf(%d is odd”,num); } (Program in C language) start read num print num is even stop If numIf num %2=0%2=0 print num is odd Flow chart:Flow chart: YesYes NoNo
  • 3. Flow chart symbols Oval Terminal Parallegram Input/output Rectangle Process Document Hard copy Diamond Decision Circle Connector Double sided Rectangle Sub program Hexagon Iteration Trapezoid Manual Operation Cylinder Magnetic Disk Storage
  • 4. Machine Language – Assembly Language – High-Level Language 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 entry main,^m<r2> sub12 #12,sp jsb C$MAIN_ARGS moveb $CHAR_STRING_CON pusha1 -8(fp) pusha1 (r2) calls #2,SCANF pusha1 -12(fp) pusha1 3(r2) calls #2,SCANF mull3 -8(fp),-12(fp),- pusha 6(fp) calls #2,PRINTF clrl r0 ret 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 00000000 00000100 0000000000000000 01011110 00001100 11000010 0000000000000010 11101111 00010110 0000000000000101 11101111 10111110 0000000000001011 11111000 10101101 11011111 0000000000010010 01100010 11011111 0000000000010101 11101111 00000010 11111011 0000000000010111 11110100 10101101 11011111 0000000000011110 00000011 10100010 11011111 0000000000100001 11101111 00000010 11011111 0000000000100100 01111110 11110100 10101101 11111000 10101110 11000101 0000000000101011 00000110 10100010 11111011 0000000000110001 11101111 00000010 11111011 0000000000110100 01010000 11010100 0000000000111011 00000100 0000000000111101 1 2 3 4 5 6 7 8 9 1 0 #include<stdio.h> int main(void) { int n1, n2,product; printf(“Enter two numbers : “); scanf(“%d %d”,&n1,&n2); product = n1 * n2; printf(“%d”,product); return 0; } The only language the computer can understand is machine language (binary language). A high level language is an English like language where one instruction typically translates into a series of machine- language instructions. A low level language corresponds closely to machine code so that a single low-level language instruction translates to a single machine language instruction.
  • 5. Language Translation • Translator – is a computer program that reads a program written in one language, which is called the source language, and translates it in to another language, which is called the target language. • Assembler • Compiler • Assembler – Assembler is a software or a tool that translates Assembly language to machine code. • Compiler – Compiler is a program that translates High level language such as programs written in C, C++ to machine code
  • 6. Difference between Compiler and Interpreter No Compiler Interpreter 1 Compiler Takes Entire program as input Interpreter Takes Single instruction as input . 2 Intermediate Object Code is Generated No Intermediate Object Code is Generated 3 Conditional Control Statements are Executes faster Conditional Control Statements are Executes slower 4 Memory Requirement : More(Since Object Code is Generated) Memory Requirement is Less 5 Program need not be compiledevery time Every time higher level program is converted into lower level program 6 Errors are displayed after entire program is checked Errors are displayed for every instruction interpreted (if any) 7 Example : C Compiler [Eg. cc, gcc, ANSI C, Borland C, etc.] Example : Python Interpreter (Eg. IDLE, etc.)
  • 7. Structure of C program /*Program to find/*Program to find area and perimeter of Circle */area and perimeter of Circle */ #include<stdio.h>#include<stdio.h> #define PI 3.1415#define PI 3.1415 float radius;float radius; float area();float area(); float perimeter();float perimeter(); int main()int main() {{ float a, p;float a, p; printf(“Enter radius : “);printf(“Enter radius : “); scanf(“%f”,&radius);scanf(“%f”,&radius); a = area();a = area(); p = perimeter();p = perimeter(); printf(“Area of Circle : %f”,a);printf(“Area of Circle : %f”,a); printf(“Perimeter : %f”,p);printf(“Perimeter : %f”,p); }} float area()float area() {{ return (PI * radius * radius);return (PI * radius * radius); }} float perimeter()float perimeter() {{ return (2 * PI * radius);return (2 * PI * radius); }} Documentation/Comment SectionDocumentation/Comment Section Linkage/header file SectionLinkage/header file Section Definition SectionDefinition Section Global Declaration SectionGlobal Declaration Section Main Function SectionMain Function Section Local Declaration PartLocal Declaration Part Executable Code PartExecutable Code Part Sub Program SectionSub Program Section Function1()Function1() Function2()Function2() ………………………… FunctionN()FunctionN()
  • 9. 99 Compilation & Linking helloworld.chelloworld.c stdio.hstdio.h #include <stdio.h>#include <stdio.h> helloworld.ohelloworld.o Helloworld.exeHelloworld.exe header fileheader file compilercompiler linkerlinker executable fileexecutable file object fileobject file source filesource file
  • 10. Program Development Steps 1)Statement of Problem a) Working with existing system and using proper questionnaire, the problem should be explained clearly. b) What inputs are available, outputs are required and what is needed for creating workable solution should be understood clearly. 2)Analysis a) The method of solutions to solve the problem can be identified. b) We also judge that which method gives best results among different methods of solution. 3)Designing a) Algorithms and flow charts will be prepared. b) Keep focus on data, architecture, user interfaces and program components. 4)Implementation The algorithms and flow charts developed in the previous steps are converted into actual programs in the high level languages like C. 4.a)Compilation Translate the program into machine code. This process is called as Compilation. Syntactic errors are found quickly at the time of compiling the program. These errors occur due to the usage of wrong syntaxes for the statements. Eg: x=a*y+b There is a syntax error in this statement, since, each and every statement in C language ends with a semicolon (;). 4.b)Execution The next step is Program execution. In this phase, we may encounter two types of errors. Runtime Errors: these errors occur during the execution of the program and terminates the program abnormally. Logical Errors: these errors occur due to incorrect usage of the instructions in the program. These errors are neither detected during compilation or execution nor cause any stoppage to the program execution but produces incorrect ouz
  • 11. Executing a C program compiles Syntax Errors? Yes Object machine code 010110 100 ……………. 01011 101 C-compiler #include<stdio.h> int main() { ……. Text Editor prog1.c prog1.obj Linker Executable machine code 00101010 …………. 01010101 adds Translators are system software used to convert high-level language program into machine-language code. Compiler : Coverts the entire source program at a time into object code file, and saves it in secondary storage permanently. The same object machine code file will be executed several times, whenever needed. Interpreter : Each statement of source program is translated into machine code and executed immediately. Translation and execution of each and every statement is repeated till the end of the program. No object code is saved. Translation is repeated for every execution of the source program. machine code of library file Input prog1.exe No C-Runtime Executes Feeds Runtime or Logic Errors ? Yes Output
  • 12. 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 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.
  • 13. 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.
  • 14. 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 )
  • 15. printf() & scanf() functions int main ( ) { printf(" %d", printf("%s", “welcome")); return 0 ; } int main() { char a; printf("%d",scanf("%c",&a)); return 0; } 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. Irrespective of the character that user enters, this program prints 1 This program prints welcome 7
  • 16. Careful to use scanf() • The basic problem is that scanf() leaves the newline after the number in the buffer, and then reads it with %c on the next pass. • This is a good demonstration of why we need to cautious about to use scanf()
  • 17. Conversion/Access/fomat Specifiers CodeCode FormatFormat %s String of characters (until null zero is reached ) %c Character %d Decimal integer %f Floating-point numbers %e Exponential notation floating-point numbers %u Unsigned integer %o Octal integer %x Hexadecimal integer %i Signed decimal integer %p Display a pointer %hd short integer %ld long integer %lf long double %% Prints a percent sign (%)
  • 18. Back Slash ( Escape Sequence) Characters 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
  • 19. 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
  • 20. Value range of different types Type Storage size Value range char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295
  • 21. Data type modifiers in C Used to change the properties of current properties ofUsed to change the properties of current properties of data type. Data type modifiers are classified intodata type. Data type modifiers are classified into following types.following types. •longlong •shortshort •unsignedunsigned •signedsigned
  • 22. Data type modifiers in C Modifiers are prefixed with basic data types to modify (eitherModifiers are prefixed with basic data types to modify (either increase orincrease or decreasedecrease)) the amount of storage space allocated to a variablethe amount of storage space allocated to a variable.. For exampleFor example, storage space for, storage space for int data type is 4 byteint data type is 4 byte for 32 bit processor.for 32 bit processor. We canWe can increaseincrease the range by usingthe range by using long int which is 8 bytelong int which is 8 byte. We can. We can decreasedecrease the range by usingthe range by using short int which is 2 byteshort int which is 2 byte..
  • 23. Precedence and Associativity of Operators Precdence Group Operators Associativity (Highest to Lowest ) (param) subscript etc., ( ) [ ] –>. L  R Unary operators - + ! ~ ++ – – (type) * & sizeof R  L Multiplicative * / % L  R Additive + – L  R Bitwise shift << >> L  R Relational < <= > >= L  R Equality = = != L  R Bitwise AND & L  R Bitwise exclusive OR ^ L  R Bitwise OR | L  R Logical AND && L  R Logical OR | | L  R Conditional ?: R  L Assignment = += –= *= /= %= &= ^= R  L |= <<= >>= Comma , L  R
  • 24. Conditional/Decision Control Statements • Simple if • if… else • nested if… else • If else ladder – if… else if… else
  • 25. TestTest ExpressionExpression ?? EntryEntry FalseFalse Next statementNext statement True Statement-blockTrue Statement-block TrueTrue simple if:simple if: TestTest ExpressionExpression ?? EntryEntry True-blockTrue-block StatementsStatements FalseFalse False-blockFalse-block StatementsStatements TrueTrue Next statementNext statement if-else:if-else: /* check a citizen is eligible for voting *//* check a citizen is eligible for voting */ #include<stdio.h>#include<stdio.h> int main()int main() {{ int age;int age; printf(“Enter the age : ”);printf(“Enter the age : ”); scanf(“%d”,&age);scanf(“%d”,&age); if(age >= 18)if(age >= 18) printf(“Eligible for voting…”);printf(“Eligible for voting…”); getch();getch(); }} /* print a number is even or odd *//* print a number is even or odd */ #include<stdio.h>#include<stdio.h> int main()int main() {{ int number;int number; printf(“Enter a number : “);printf(“Enter a number : “); scanf(“%d”, &number);scanf(“%d”, &number); if((number %2) == 0)if((number %2) == 0) printf(“%d is even number.”,number);printf(“%d is even number.”,number); elseelse printf(“%d is odd number.”,number);printf(“%d is odd number.”,number); }}
  • 26. TestTest condition1condition1 ?? EntryEntry Statement-3Statement-3 TrueTrue TestTest condition2condition2 ?? FalseFalse Statement-2Statement-2 Statement-1Statement-1 TrueTrue FalseFalse Next statementNext statement nested if…else:nested if…else: /* check whether a year is leap year or not *//* check whether a year is leap year or not */ #include<stdio.h>#include<stdio.h> int main() {int main() { int year;int year; printf("Enter the year ?");printf("Enter the year ?"); scanf("%d",&year);scanf("%d",&year); if((year %100) == 0)if((year %100) == 0) {{ if((year % 400) == 0)if((year % 400) == 0) printf("%d is leap year.",year);printf("%d is leap year.",year); elseelse printf("%d is not leap year.",year);printf("%d is not leap year.",year); } else {} else { if((year % 4) == 0)if((year % 4) == 0) printf("%d is leap year.",year);printf("%d is leap year.",year); elseelse printf("%d is not leap year.",year);printf("%d is not leap year.",year); }} getch();getch(); }}
  • 27. if…else…if :if…else…if : EntryEntry TestTest condition1condition1 ?? TrueTrue Statement-1Statement-1 TrueTrue Statement-2Statement-2 TestTest condition2condition2 ?? FalseFalse TrueTrueTestTest conditionNconditionN ?? FalseFalse Statement-NStatement-N Next statementNext statement /* program to print the grade of student *//* program to print the grade of student */ #include<stdio.h>#include<stdio.h> int main() {int main() { int marks;int marks; printf("Enter marks ? ");printf("Enter marks ? "); scanf("%d", &marks);scanf("%d", &marks); if(marks >= 75)if(marks >= 75) printf("Distinction");printf("Distinction"); else if(marks >= 60)else if(marks >= 60) printf("First class");printf("First class"); else if(marks >= 50)else if(marks >= 50) printf("Second class");printf("Second class"); else if(marks >= 35)else if(marks >= 35) printf("Third class");printf("Third class"); elseelse printf("Failed");printf("Failed"); }}
  • 28. switch statement :switch statement : EntryEntry switchswitch expressionexpression ?? Next statementNext statement /* program to simulate a simple calculator *//* program to simulate a simple calculator */ #include<stdio.h>#include<stdio.h> int main() {int main() { float a,b;float a,b; char opr;char opr; printf("Enter number1 operator number2 : ");printf("Enter number1 operator number2 : "); scanf("%f %c %f",&a,&opr,&b);scanf("%f %c %f",&a,&opr,&b); switch(opr)switch(opr) {{ case '+':case '+': printf("Sum : %f",(a + b));printf("Sum : %f",(a + b)); break;break; case '-':case '-': printf("Difference : %f",(a - b));printf("Difference : %f",(a - b)); break;break; case '*':case '*': printf("Product : %f",(a * b));printf("Product : %f",(a * b)); break;break; case '/':case '/': printf("Quotient : %f",(a / b));printf("Quotient : %f",(a / b)); break;break; default:default: printf("Invalid Operation!");printf("Invalid Operation!"); }} }} associateassociate statementstatement associateassociate statementstatement associateassociate statementstatement associateassociate statementstatement value1value1 value2value2 valueNvalueN defaultdefault ExitExit …………......
  • 29. Example #include<stdio.h>#include<stdio.h> int main()int main() {{ int a,b;int a,b; char choice;char choice; printf("nInput 2 numbers:");printf("nInput 2 numbers:"); scanf("%d %d",&a,&b);scanf("%d %d",&a,&b); printf("nEnter your choice:");printf("nEnter your choice:"); scanf("%c",&choice);scanf("%c",&choice); switch(choice)switch(choice) {{ case '+':case '+': printf("nAddition:%d",(a+b));printf("nAddition:%d",(a+b)); break;break; case '-':case '-': printf("nSubtraction:%d",(a-b));printf("nSubtraction:%d",(a-b)); break;break; default:default: printf("nNo such choice available...");printf("nNo such choice available..."); break;break; }} return 0;return 0; }}
  • 30. ?: - Conditional operator #include<stdio.h> int main() { int num; printf("Enter the Number : "); scanf("%d",&num); flag = ((num%2==0)?1:0); if(flag==0) printf("nEven"); else printf("nOdd"); } #include<stdio.h> int main() { int num; printf("Enter the Number : "); scanf("%d",&num); (num%2==0)?printf("Even"):printf("Odd"); } Syntax: (Condition) ? stmt 1 : stmt 2
  • 31. Loop Control/ Iterative Statements • while loop • for loop • do-while loop
  • 32. Test Condition ? Body of The loop False truetrue while – (Entry controlled )while – (Entry controlled ) EntryEntry Loop StatementsLoop Statements Following Statement Test Condition ? Body of The loop False TrueTrue EntryEntry Following Statement do-while – (Exit controlled )do-while – (Exit controlled ) /* sum of 1 to 10 numbers *//* sum of 1 to 10 numbers */ #include<stdio.h>#include<stdio.h> int main() {int main() { int i = 1,sum = 0;int i = 1,sum = 0; while(i<=10){while(i<=10){ sum = sum + i;sum = sum + i; i = i + 1;i = i + 1; }} printf(“Total : %d “,sum);printf(“Total : %d “,sum); }} /* average of 5 numbers *//* average of 5 numbers */ #include<stdio.h>#include<stdio.h> int main() {int main() { int count = 1;int count = 1; float x, sum = 0;float x, sum = 0; do {do { printf(“x = “);printf(“x = “); scanf(“%f”,&x);scanf(“%f”,&x); sum += x;sum += x; ++ count;++ count; } while(count <= 5);} while(count <= 5); printf(“Average = %f “, (sum/5))printf(“Average = %f “, (sum/5)) }}
  • 33. Do while example #include<stdio.h>#include<stdio.h> int main()int main() {{ int n,i=1;int n,i=1; int sum=0;int sum=0; printf("n Enter N:");printf("n Enter N:"); scanf("%d",&n);scanf("%d",&n); dodo {{ sum=sum+i;sum=sum+i; i++;i++; } while(i<=10);} while(i<=10); printf("n Sum of N natural number: %d", sum);printf("n Sum of N natural number: %d", sum); return 0;return 0; }}
  • 34. for --for -- StatementStatement Initialization Statement Increment Statement Test Condition ? Body of The loop EntryEntry TrueTrue Following Statement False /* check whether a number is prime or not *//* check whether a number is prime or not */ #include<stdio.h>#include<stdio.h> int main() {int main() { int n,i,factors = 0;int n,i,factors = 0; printf("Enter a number : ");printf("Enter a number : "); scanf("%d",&n);scanf("%d",&n); for(i = 1; i <= n; i++) {for(i = 1; i <= n; i++) { if((n % i)==0) ++factors;if((n % i)==0) ++factors; }} if (factors == 2)if (factors == 2) printf("%d is prime number.",n);printf("%d is prime number.",n); elseelse printf("%d is not prime number.",n);printf("%d is not prime number.",n); }} #include<stdio.h>#include<stdio.h> int main()int main() {{ int n,i;int n,i; int sum=0;int sum=0; printf("n Enter N:");printf("n Enter N:"); scanf("%d",&n);scanf("%d",&n); for(i=1;i<=n;i++)for(i=1;i<=n;i++) {{ sum=sum+i;sum=sum+i; }} printf("n Sum of N natural number: %d",printf("n Sum of N natural number: %d", sum);sum); return 0;return 0; }}
  • 35. Infinite for loop • Syntax: – for( ; ; ) • Example #include<stdio.h>#include<stdio.h> int main()int main() {{ for(;;)for(;;) {{ printf("n Hello");printf("n Hello"); }} return 0;return 0; }} This program will print Hello infinite number of timesThis program will print Hello infinite number of times
  • 36. Important Functions in math.h abs(x) absolute value of integer x ceil(x) rounds up and returns the smallest integer greater than or equal to x floor(x) rounds down and returns the largest integer less than or equal to x log(x) returns natural logarithm pow(x,y) returns the value of xy sqrt(x) returns square root of x exp(x) returns natural anti logarithm sin(x) returns sine value where x in radians cos(x) returns cosine value where x in radians tan(x) returns tangent values where x in radians fmod(x,y) calculate x modulo y, where x and y are double hypot(x,y) calculate hypotenuse of right angle where x,y are sides. log10(x) returns logarithm base 10
  • 37. Jump Statement • break • continue • goto
  • 38. break Statements • break; – break is used in terminating the loop immediately after it is encountered
  • 40. Example /* C program to demonstrate the working of break statement by terminating a loop, if/* C program to demonstrate the working of break statement by terminating a loop, if user inputs negative number*/user inputs negative number*/ # include <stdio.h># include <stdio.h> int main(){int main(){ float num,average,sum=0;float num,average,sum=0; int i,n;int i,n; printf("Maximum no. of inputsn");printf("Maximum no. of inputsn"); scanf("%d",&n);scanf("%d",&n); for(i=1;i<=n;++i){for(i=1;i<=n;++i){ printf("Enter n%d: ",i);printf("Enter n%d: ",i); scanf("%f",&num);scanf("%f",&num); if(num<0.0)if(num<0.0) break; //for loop breaks if num<0.0break; //for loop breaks if num<0.0 sum=sum+num;sum=sum+num; }} average=sum/(i-1);average=sum/(i-1); printf("Average=%.2f",average);printf("Average=%.2f",average); return 0;return 0; }}
  • 41. #include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; continue; printf("Nothing to seen"); } return 0; } #include<stdio.h>#include<stdio.h> int main()int main() {{ int i=0;int i=0; while(i<20)while(i<20) {{ i++;i++; if (i==10)if (i==10) break;break; }} printf("n%d",i);printf("n%d",i); return 0;return 0; }}
  • 42. continue Statements • continue; – It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used
  • 43. Flow diagram of continue
  • 44. Example # include <stdio.h># include <stdio.h> int main()int main() {{ int i,num,product;int i,num,product; for(i=1,product=1;i<=4;++i)for(i=1,product=1;i<=4;++i) {{ printf("Enter num%d:",i);printf("Enter num%d:",i); scanf("%d",&num);scanf("%d",&num); if(num==0)if(num==0) continue; / *In this program, when num equals to zero, it skips the statement product*=numcontinue; / *In this program, when num equals to zero, it skips the statement product*=num and continue the loop. */and continue the loop. */ product*=num;product*=num; }} printf("product=%d",product);printf("product=%d",product); return 0;return 0; }} Output:Output: ??
  • 45. Predict the output #include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; continue; printf("Nothing to seen"); } return 0; } #include <stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; continue; printf("Nothing to seen"); } printf("n%d",i); return 0; } Output: ?
  • 47. #include <stdio.h>#include <stdio.h> int main()int main() {{ int i;int i; for (i=1;i<=3;i++)for (i=1;i<=3;i++) {{ MIT:MIT: goto MITS;goto MITS; }} MITS: printf("n Hello...");MITS: printf("n Hello..."); goto MIT;goto MIT; return 0;return 0; }} Output:Output: Indefinitely prints “Hello…”Indefinitely prints “Hello…”
  • 48. Example int main()int main() {{ int age;int age; Vote:Vote: printf(“n you are eligible for voting");printf(“n you are eligible for voting"); NoVote:NoVote: printf(“n you are not eligible to vote");printf(“n you are not eligible to vote"); printf(“n Enter you age:");printf(“n Enter you age:"); scanf("%d", &age);scanf("%d", &age); if(age>=18)if(age>=18) goto Vote;goto Vote; elseelse goto NoVote;goto NoVote; return 0;return 0; }} Explanation: •Vote and NoVote are labels. •When the input is >= 18, the goto statement is transferring the control to label – Vote, •Otherwise it transfers the control to label-NoVote. •This prints some unordered outputs
  • 49. #include<stdio.h>#include<stdio.h> int main()int main() {{ int age;int age; printf("Enter you age:");printf("Enter you age:"); scanf("%d", &age);scanf("%d", &age); if(age>=18)if(age>=18) gotogoto Vote;Vote; elseelse gotogoto NoVote;NoVote; Vote:Vote: printf("you are eligible for voting");printf("you are eligible for voting"); gotogoto Exit;Exit; NoVote:NoVote: printf("you are not eligible to vote");printf("you are not eligible to vote"); gotogoto Exit;Exit; Exit:Exit: return 0;return 0; }} Explanation: •Vote and NoVote are labels. •When the input is >= 18, the goto statement i transferring the control to label – Vote, •Otherwise it transfers the control to label- NoVote. •This prints ordered outputs
  • 50. 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; }
  • 51. 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]
  • 52. 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
  • 53. 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]
  • 55. Example //Upper to Lower case//Upper to Lower case #include<stdio.h>#include<stdio.h> int main()int main() {{ char a,b;char a,b; printf("n Enter a character:");printf("n Enter a character:"); scanf("%c",&a);scanf("%c",&a); if(a>=65 && a<=90)if(a>=65 && a<=90) b=a+32;b=a+32; printf("n %c",b);printf("n %c",b); return 0;return 0; }}
  • 56. Homework Exercises • C Program to Check whether a given Number is Armstrong • C Program to Check whether a given Number is Perfect Number – A perfect number is a positive integer that is equal to the sum of its proper positive divisors • C Program to Print Armstrong Number from 1 to 1000 • C Program to Swap the Contents of two Numbers using Bitwise XOR Operation
  • 57. Perfect Number #include <stdio.h> int main() { int number, rem, sum = 0, i; printf("Enter a Numbern"); 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; }
  • 58. Armstrong number #include <stdio.h>#include <stdio.h> main()main() {{ int number, temp, digit1, digit2, digit3;int number, temp, digit1, digit2, digit3; printf("Print all Armstrong numbers between 1 and 1000:n");printf("Print all Armstrong numbers between 1 and 1000:n"); number = 001;number = 001; while (number <= 900)while (number <= 900) {{ digit1 = number - ((number / 10) * 10);digit1 = number - ((number / 10) * 10); digit2 = (number / 10) - ((number / 100) * 10);digit2 = (number / 10) - ((number / 100) * 10); digit3 = (number / 100) - ((number / 1000) * 10);digit3 = (number / 100) - ((number / 1000) * 10); temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3);temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3); if (temp == number)if (temp == number) {{ printf("n Armstrong no is:%d", temp);printf("n Armstrong no is:%d", temp); }} number++;number++; }} }}
  • 59. Swapping Binary number using XOR operator #include <stdio.h>#include <stdio.h> void main()void main() {{ long i, k;long i, k; printf("Enter two integers n");printf("Enter two integers n"); scanf("%ld %ld", &i, &k);scanf("%ld %ld", &i, &k); printf("n Before swapping i= %ld and k = %ld", i, k);printf("n Before swapping i= %ld and k = %ld", i, k); i = i ^ k;i = i ^ k; k = i ^ k;k = i ^ k; i = i ^ k;i = i ^ k; printf("n After swapping i= %ld and k = %ld", i, k);printf("n After swapping i= %ld and k = %ld", i, k); }}