Lecture 2
Lecture 2
Lecture 2
Area of a circle
#include<stdio.h>
main()
{
float radius, area;
radius=3.1;
area = 3.14 * radius * radius;
printf("Area of Circle : %f", area);
}
Lets have a small revision
#include <stdio.h>
6 + a / 5 * b = 16
int main (void) a / b * b = 24
{ c / d * d = 25.000000
-a = -25
int a = 25;
int b = 2;
float c = 25.0;
float d = 2.0;
printf ("6 + a / 5 * b = %i\n", 6 + a / 5 * b);
printf ("a / b * b = %i\n", a / b * b);
printf ("c / d * d = %f\n", c / d * d);
printf ("-a = %i\n", -a);
return 0;
}
Decimal points will be lost if variable is declared as int instead of float
More about the %
#include <stdio.h>
int main (void) a%b=0
{ a%c=5
a%d=4
int a = 25, b = 5, c = 10, d = 7; a / d * d + a % d = 25
printf ("a %% b = %i\n", a % b);
printf ("a %% c = %i\n", a % c);
printf ("a %% d = %i\n", a % d);
printf ("a / d * d + a %% d = %i\n",a / d * d + a % d);
return 0;
}
Lets test what we learned so far
#include <stdio.h>
int main (void)
123.125000 assigned to an int produces 123
{ -150 assigned to a float produces -150.000000
float f1 = 123.125, f2; -150 divided by 100 produces -1.000000
int i1, i2 = -150; -150 divided by 100.0 produces -1.500000
char c = 'a'; (float) -150 divided by 100 produces -1.500000
i1 = f1; // floating to integer conversion
printf ("%f assigned to an int produces %i\n", f1, i1);
f1 = i2; // integer to floating conversion
printf ("%i assigned to a float produces %f\n", i2, f1);
f1 = i2 / 100; // integer divided by integer
printf ("%i divided by 100 produces %f\n", i2, f1);
f2 = i2 / 100.0; // integer divided by a float
printf ("%i divided by 100.0 produces %f\n", i2, f2);
f2 = (float) i2 / 100; // type cast operator
printf ("(float) %i divided by 100 produces %f\n", i2, f2);
return 0;
}
Widely used Variables in C language
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
_bool variable
• A _Bool variable can hold values 0 or 1
• _Bool variables are used in programs that need to indicate a Boolean
• By convention 0 is used to indicate a false value, and 1 indicates a
true value.
• Storing a 0 in a _Bool variable results in a 0
• Storing any nonzero value in a _Bool variable results in a 1 all the time
• Use header file <stdbool.h> that defines the values of bool as true or
false.
Example
integerVar = 100
#include <stdio.h> floatingVar = 331.790000
int main (void) charVar = W
{ boolVar = 0
int integerVar = 100;
float floatingVar = 331.79;
char charVar = 'W';
_Bool boolVar = 0;
printf ("integerVar = %i\n", integerVar);
printf ("floatingVar = %f\n", floatingVar);
printf ("charVar = %c\n", charVar);
printf ("boolVar = %i\n", boolVar);
return 0;
}
if statement
• Provides a general decision-making
if ( expression )
program statement
• A simple condition