main()
{
printf("hello world\n");
printf("my age is 36\n");
getchar();
}
#include
main()
{
int a;
printf("%d",a);
getchar();
}
#include
main()/* any errors*/
{
int 36age;
……
}
#include
main()/* any variable, define*/
{
age;
clrscr();
printf("hello world\n");
scanf("%d",age);
printf("the age u entered is %d",age);
fflush(stdin);
getchar();
}
#include
main()
{
int nob,nos,noc,ts,tc;
char name[10];
clrscr();
printf("enter your name:");
scanf("%s",&name);
printf("%s",name);
printf("\thow many brothers u have:",name);
scanf("%d",&nob);
printf("how many sisters u have:");
scanf("%d",&nos);
printf("how many children u have:");
scanf("%d",&noc);
ts=nob+nos;
tc=noc;
printf("total brothers and sisters are %d and total children are %d",ts,tc);
fflush(stdin);
getchar();
}
#include
main()
{
int age;
clrscr();
printf("enter your age:");
scanf("%d",&age);
printf("the age you entered is %d");
fflush(stdin);
getchar();
}
#include
main()
{
printf("hello world\n");
getchar();
}
#include
main
(
)
{
printf(" he llo world\n");
getchar();
}
#include
main()
{
int age;
printf("hello world\n");
age=36;
printf("my age is %d\n",age);
getchar();
}
main()/*any interesting thing!*/
{
int age;
printf(“hello world\n”);
scanf(“%d\n”,age);
printf(“%d”,age);
#include
main()
{
char name[20],str2;
int length;
clrscr();
/* name ="rajesh";*/
strcpy(name,"rajesh");
strcpy(str2,"my name is\t");
strcat(str2,name);
printf(name);
printf("\n%s",str2);
length=strlen(str2);
printf("\n%d",length);
getchar();
}
#include
main()
{
int age,half,years;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
half=age/2;
years=age-5;
printf("\nhalf your age is %d",half);
printf("five years ago your age was %d",years);
getchar();
}
#include
main()
{
int x,y,z,p;
clrscr();
x=9;
y=x+6/3; /* divided by happens first result is 11*/
z=x*y+1+2-3*4;/*multiply happens first result is 90*/
printf("%d\t%d\t%d\n",x,y,z);
y=(x+6)/3;
p=15%6;
printf("%d\t%d\n",y,p);
p=(10+5)%12;
printf("%d\n",p);
printf("%d\n",3*17);
getchar();
}
#include
main()
{
int x=415;
double y=3.14159;
int len=1;
char string[30];
clrscr();
strcpy(string,"hello");
printf("12345678901234567890123456789\n");
printf("%s<<<<\n",string);
printf("%10s<<<<\n",string);/*right justified*/
printf("%-10s<<<<\n",string);/*left justified*/
printf("%.3s<<<\n",string);/*maximum number of characters*/
printf("%.*s",len,string);/*maximum characters specified by len */
printf(" \n ");
printf("* *\n");
printf("** **\n");
printf("12345678901234567890123456789\n");
printf("%d<<<<\n",x);
printf("%10d<<<<\n",x);
printf("%-10d<<<<\n",x);
printf("%010d<<<<\n",x);
printf("%.*d<<<<\n",len,x);
printf("%.1d<<<<\n",x);
printf(" \n ");
printf("* *\n");
printf("** **\n");
printf("12345678901234567890123456789\n");
printf("%c<<<<\n",string[0]);
printf("%10c<<<<\n",string[0]);
printf("%-10c<<<<\n",string[0]);
getchar();
}
#include
main()
{
int x;
double y;
char string[100];
clrscr();
printf("enter a word:");
scanf("%s",string);/*no ampersand is used*/
fflush(stdin);
printf("\n the word entered is %s\n",string);
printf("enter many words:");
scanf("%[^\n]",string);
fflush(stdin);
printf("%s\n",string);
getchar();
}
#include
main()
{
int age,magic_age=40;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
printf("you are %d years old!\n",age);
if (age > magic_age)
printf("you are very old!\n");
printf("you are %d older than %d\n",age-magic_age,magic_age);
getchar();
}
#include
main()
{
int age;
clrscr();
printf("please enter your age:");
scanf("%d",&age);
fflush(stdin);
if ( age > 30)
printf("you are older than 30\n");
age = age +5;
printf("\n\n=====block within a block====\n\n");
{
int newage;
newage=age+30;
printf("newage is %d\n",newage);
}
getchar();
}
#include
main ()
{
int age,magic_age=40;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
printf("your age is %d\n",age);
if (age < magic_age)
printf("you are young\n");
else
if (age > magic_age)
printf("you are old\n");
else
if (age == 40)
printf("perfect!!!\n");
else
printf("invalid age!\n");
getchar();
}
#include
main()
{
int age;
clrscr();
printf("enter age:");
scanf("%d",&age);
if (age <30);/* no error will be shown and wow! will be printed irrespective of whatever you enter*/
printf("wow!");
}
#include
main()
{
int age;
clrscr();
printf("enter age:");
scanf("%d",&age);
if(age <= 1)
printf("kid\n");
else if (age <=18)
printf("youngster\n");
else if (age == 21)
printf("now you are grown up\n");
else if (age == 40)
printf(" you are getting older\n");
else
printf("invalid entry\n");
fflush(stdin);
getchar();
}
#include
main()
{
double x=5000.0,y=0.0025,num=13.4485;
clrscr();
printf("12345678901234567890123456789\n");
printf("%f %f\n",x,y);/* if %d is used output is 0*/
printf("%e %e\n",x,y);
printf("%f\n",num);
printf("%10f\n",num);
printf("%12.5f\n",num);
printf("%.3f\n",num);
getchar();
}
#include
main()
{
int i=12345;
float x=345.678;
clrscr();
printf("12345678901234567890123456789\n");
printf("%3d\n",i);
printf("%5d\n",i);
printf("%8d\n",i);
printf("%3g\n",x);
printf("%10g\n",x);
printf("%13g\n",x);
getchar();
}
#include
main()
{
float x=123.456;
clrscr();
printf("12345678901234567890123456789\n");
printf("%7f\n",x);
printf("%7.3f\n",x);
printf("%7.1f\n");
#include
main()
{
int age;
clrscr();
printf("please enter your age:");
scanf("%d",&age);
printf("\nyou are %d years old\n",age);
switch(age)
{
case 1:
case 2:
case 3:
printf("sorry you can not go to school\n");
break; /*if break is forgotten next stmt will be executed*/
case 5:
printf("you are now in I class\n");
break;
case 15:
printf("you must be in 10th standard now\n");
break;
case 18:
printf("ready to vote!!!\n");
break;
case 21:
printf("ready to get married\n");
break;
case 40:
printf("you have matured\n");
break;
case 58:
printf("you can retire, now!!!\n");
break;
default:
printf("your age is of no importance!\n");
}
fflush(stdin);
getchar();
}
#include
main()
{
int age;
int very_old = age >=80;
clrscr();
printf("enter your age:");
scanf("%d",&age);
if (very_old)/*if(3+4) will also give the same result*/
printf("you are very old as you are %d years old\n",age);
printf("the value of the variable very_old is %d\n",very_old);
fflush(stdin);
getchar();
}
/*correct the bug*/
main()
{
int x = 1:
if (x = 1);
printf("x equals 1\m")
otherwise
printf("x does not equal 1\m");
fflush(stdio);
getchar(char);
)
#include
main()
{
int x=5;
clrscr();
if(x=1)
printf("one\n");
getchar();
}
Exercise
Wap CD shop database.input the following details and print them again on the screen.
movie,director,number of songs,hit/fail,price.
/*use of got lable*/
main()
{
int age;
char name[41];
int very_old;
printf("Please enter your age: ");
scanf("%d", &age);
printf("You are %d years old\n", age);
if (!(age <= 19 && age >= 13))
goto other;
if (age > 19 || age < 13)
printf("You are not a teenager\n");
up:
if (age == 10 || age == 20 || age == 30 || age > 100)
printf("You have a special age\n");
printf("Please enter your name: ");
scanf("%s", name);
if (!(strcmp(name, "Bruce") != 0 && age != 40))
printf("You not called Bruce and are aged 40.\n");
if (strcmp(name, "Bruce") == 0 || age == 40)
printf("You not called Bruce and are aged 40.\n");
other:
very_old = age > 80;
if (!very_old)
printf("You are not very old\n");
if (very_old == 0)
printf("You are not very old\n");
if (age > 10)
goto up;
fflush(stdin);
getchar();
}
two approaches of programming:
programmer’s perspective
• structured programming
• object oriented programming
end user’s perspective
• sequential
• event driven
. • Assignment operator =
. • Arithmetic operators +, -, *, /, %
. • Relational operators >, >=, <, <=, == , !=
. • Logical operators !, &&, ||
. • Address operator &
. • Increment and Decrement operators ++, -
. • Compound Assignment Operators =, +=, -=, /=, *=, %=
. • sizeof operator
The basic arithmetic operators help us in performing the arithmetic operations.The % (modulo operator) is used to find the reminder of a divide operation eg.
int x=5,y=2;
int z=5/2;
will store 2 in z
int z=5%2
will store 1 in z % operator cannot be applied to float data type. Hence the instruction
5.2 % 2.5
will result in error For comparing if 2 values are equal or not remember to use == and not a single =.
== indicates comparisons and
= indicates assignment operation
eg. int x=5,y=3 x==y
will be considered as an conditional expression that will be evaluated to true(non-zero) for false(zero)
x=y will be considered as an assignment expression which will assign 3 (value of y) to x. x after the instruction will have value 3.
Logical operators available are
! (NOT), && (AND), || (OR) eg.
consider 3 variables x,y,z containing values 1,2,3 respectively
x=1, y=2, z=3
the condition x==1 && y == 3 will evaluate to false
the condition x==1 && z==3 will evaluate to true
the condition x==1 || y==3 will evaluate to true
the condition x==1 || z==3 will evaluate to true
the condition !(x <2 && y==2) will evaluate to false
Classification of Operators:
.(1) Based on the number of operands:
.
.Unary operators ++, -
.
.Binary operators +,-,*,/,%,==,<,>,>=,<=,!=,&&,||
.
.Ternary operators ? :
.
.(2) Based on the operations performed:
.
.Arithmetic operators
.
.Relational operators
.
.Logical operators
• Assign an expression to a variable
Syntax
Variable = Variable or constant or expression
data-type variable = constant
Example:
iNum = 10;
int i = 10;
float f = 13.24;
The statement i = f, will truncate the value .24 from f and i will have a value 13
Type Casting
. • Temporary conversion of one data type into another
. • In some situations, the compiler will automatically convert one data type into another
. • Type casting is an overhead for the compiler
. • Example:
float fResult;
fResult = 7 / 2 ;
The variable fResult will store 3.0 instead of 3.5
To get the ‘float’ value, the expression should be:
fResult = 7.0 / 2; or
fResult = 7 / 2.0; or
fResult = 7.0 / 2.0; or
fResult = (float) 7 / 2; or
fResult = 7 / (float) 2;
Precedence of Arithmetic Operators
Operator Priority
* , / and % Highest
+ and Lowest
Structured Programming
Rajesh Kulkarni
Control Structures: conditional constructs
if statement
if (expression) statement1
if (expression) statement1 else statement2
expression must have an integral type. Zero is false, nonzero is true.
Notes:
expression must be parenthesized
Examples
Examples
Which of the following code is preferred?why?
Examples
/* This program displays the absolute value of a number given by the user */
#include
int main()
{
double num;
printf("Please enter a real number: ");
scanf("%lf", &num);
if (num<0)
num = -num;
printf("The absolute value is %g\n", num);
return 0;
}
if-else statement
condition
True or false
In C, every expression has a numeric value
An expression is ‘true’ when its value is non-zero
If it is zero, it is false
Therefore, in the following –
if (expression) statement
statement is executed if expression is non zero.
More about operators
In C, every expression has a numeric value
When using arithmetical operators (+, -, *, /) this is straightforward
The value of A+B is the sum of A and B
And so on…
More about operators
Expressions with relational operators (<, <=, >, >=, etc.) have values as well (intuitively, we are used to thinking about them as ‘true’ or ‘false’)
A < B evaluates to zero if A is larger than or equal to B, and some non-zero value if A is smaller than B
The exact non-zero value varies (and is not important for that matter)
Relational operators
They are:
A == B (Note the difference from A = B!!!!!)
A != B
A < B
A > B
A <= B
A >= B
The value of the expression is non-zero if it’s true, zero if it’s false
An example (fragment)
int first, second, min;
/* … */
if (first < second)
{
min = first;
printf ("The first number is smaller than the second.\n");
}
else
{
min = second;
printf ("The second number is smaller than the first\n");
}
printf("The smaller number is equal to %d\n", min);
An example
int a, b;
printf("Enter two numbers\n");
scanf("%d%d", &a, &b);
if (a == b)
{
printf("The numbers equal %d\n", a);
printf("The expression a == b is %d\n", a == b);
}
else
{
printf("The numbers are not equal\n");
printf("The expression a == b is %d\n", a == b);
}
The assignment operator =
The assignment operator is also an operator. Hence, expressions involving it have a numeric value.
This value equals to whatever appears on the right of the assignment operator
For example:
(x = 4) evaluates to 4
(y = 0) evaluates to 0
A very common mistake
Very often a programmer might confuse between the equality operator and the assignment operator:
if (x==4) …
if (x=4) …
The second is usually a mistake, but legal in C so the compiler doesn’t warn us about it!
Logical operators
Allows to evaluate two or more expressions -
!A – ‘not’ - True when A is not, and vice versa.
A && B – ‘and’ - True when both A and B are true
A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true
A silly example
#include
int main(void)
{
int grade;
printf("Please enter your grade: ");
scanf("%d", &grade);
if (grade < 0 || grade > 100)
printf("This is not a valid grade!\n");
else
printf("This is indeed a grade.\n");
return 0;
}
Example
main()
{ int x;
scanf(”%d”,&x);
if(x%2)
{
printf(“ the number %d is ODD\n”,x);
}
else
{
printf(“ the number %d is EVEN\n”,x);
}
}
Example
main()
{ int x,y;
x=10;y=20;
printf(“ %d%d are\n”,x,y);
x=x+y;
y=x-y;
x=x-y;
printf(“ %d%d are\n”,x,y);
}
Dangling else problem
if (exp1) if (exp2) stmta else stmtb
Avoiding the dangling else problem
Null statement
if (exp1)
if (exp2)
stmta
else
;
else
stmtb
else if statements
if statements distinguish between exactly 2 cases and execute different code in each case
The else-if construction allows for a multi-way decision
else if statements
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
An example
if (grade >= 90)
printf ("A\n");
else if (grade >= 80)
printf ("B\n");
else if (grade >= 70)
printf ("C\n");
else if (grade >= 60)
printf ("D\n");
else
printf ("F\n");
Validating input
When getting input from the user, it is highly recommended to check whether it is valid.
If it’s not, you should display an appropriate message and return a non-zero value.
For example –
if (grade < 0 || grade > 100)
{
printf(“Invalid input!\n”);
return 1;
}
The return keyword
For now, used to terminate the program and return a value to the operating system
If the program is successful the return value should be zero; non-zero otherwise
The exact nature of this keyword will become clear in the future
Exercise
Input –
An English letter
Output –
If input is a lowercase letter – the corresponding uppercase letter
If input is an uppercase letter - corresponding lowercase letter
Note –
Remember to check for input validity!
Exercise
Input
Two integers, A and B
Output
Their relation (i.e. displays A==B, AB)
Solution
#include
int main()
{
int A, B;
printf("Enter two Numbers\n");
scanf("%d%d", &A, &B);
if (A == B)
printf("A==B\n");
else if (A > B)
printf("A>B\n");
else
printf("A
return 0;
}
The switch statement
a multiway conditional statement
similar to if-else if-else
allows the selection of an arbitrary number
of choices based on an integer value
The switch statement
expression must have an integer value
when the switch statement is executed:
the expression is evaluated
if a case matches the value of the expression, the program jumps to the first statement after that case label
otherwise, the default case is selected
the default is optional
That grade example again
switch (grade/10) {
case 10:
case 9:
printf ("A\n");
break;
case 8:
printf ("B\n");
break;
case 7:
printf ("C\n");
break;
case 6:
printf ("D\n");
break;
default:
printf ("F\n");
}
Give me a break
when the switch transfers to the chosen case, it starts executing statements at that point
it will “fall through” to the next case unless you “break out”
break causes the program to immediately jump to the next statement after the switch statement
switch
switch (expression) {
case const-expr/: statements
case const-expr/: statements
default : statements
}
switch (digit)
{
case 0:
case 1:
case 2:
case 3:
case 4: printf (“Round down\n”);
break;
case 5:
case 6:
case 7:
case 8:
case 9:printf(“Round up\n”);
}
Exercise
Write a program that accepts a number between 1 and 100 from the user. If there is a coin of that value in cents, it should display its name. Otherwise, it should report that there is no such coin
1 = cent, 5 = nickel, 10 = dime, 25 = quarter, 100 = dollar
Remember to check for the validity of the input!
The ?: operator
expr1 ? expr2 : expr3
Nicer way to write:
(expr1)? expr2 : expr3
If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated
The ?: operator
#include
int main()
{
int i, j, min;
printf("Please enter two numbers: ");
scanf("%d%d", &i, &j);
min = (i < j)? i : j;
printf("The minimum between %d and %d is %d\n", i, j, min);
return 0;
}
Goto Statements
goto label;
………
……..
label : statements;
Goto Statements
Forward goto: if statement along with the label appear below the goto statement
Backward goto: if statement along with the label appear above the goto statement
Iteration Constructs
Iteration constructs repeat a sequence of code in a controlled manner.
while
for
do-while
while loop
while (expression)
statement
No comments:
Post a Comment