0% found this document useful (0 votes)
5 views

Lecture 2

Uploaded by

Vincent Anzo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 2

Uploaded by

Vincent Anzo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Introduction to Basic Computer

Programming

1
TYPE CONVERSION IN C

2
Implicit Type Conversion
Done by the compiler on its own, without any
external trigger from the user.
Generally takes place when in an expression more
than one data type is present. In such conditions
type conversion (type promotion) takes place to
avoid loss of data.

3
Example
#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
} 4
Explicit Type Conversion
This process is also called type casting and it is
user-defined. Here the user can typecast the result
to make it of a particular data type.

(type) expression

5
Example 1
#include<stdio.h>
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
} 6
Example 2
#include <stdio.h>
int main() {
float a = 1.5;
int b = (int)a;
printf("a = %f\n", a);
printf("b = %d\n", b);
return 0;
} 7
INPUT AND OUTPUT

8
printf() and scanf() in C
The printf() and scanf() functions are used for
input and output in C language. Both functions
are inbuilt library functions, defined in stdio.h

9
printf() function
The printf() function is used for output. It prints
the given statement to the console.

The syntax of printf() function


printf("format string",argument_list);
The format string can be %d (integer), %c
(character), %s (string), %f (float) etc.
10
scanf() function
The scanf() function is used for input. It reads the
input data from the console.

Syntax
scanf("format string",argument_list);

11
An example that gets input and prints the cube
of the given number.
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:
%d ",number*number*number);
12
An example of input and output that
prints addition of 2 numbers.
#include<stdio.h>
int main(){
int x=0,y=0,result=0;
printf("enter first number:");
scanf("%d",&x);
printf("enter second number:");
scanf("%d",&y);
result=x+y;
printf("sum of 2 numbers:%d ",result);
return 0;
} 13
Task
1. Write a C program to print your name, course unit
and nationality.

2. Write a program to take two numbers as input


and print their average.

14
Example
Write a program that calculates age

15
Task
Write a C program to take input using scanf for
height and width of a triangle and calculate and
print it’s area using printf.

16
OPERATORS

17
Introduction
An operator is a symbol that tells the compiler to perform
specific mathematical or logical functions.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators 18
Arithmetic Operators(A=10, B=20)
Operato Description Example
r
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an B%A=0
integer division.
++ Increment operator increases the integer value by A++ = 11
one.
-- Decrement operator decreases the integer value by A-- = 9
one.
19
Example
#include<stdio.h>
int main(){
int x=52, y=17, rem1, rem2;
rem1 = x%2;
rem2 = y%2;
printf(“Remainder dividing 52 by 2 is :%d ",rem1);
printf(“Remainder dividing 17 by 2 is :%d ",rem2);
return 0;
}
20
Write a program to take input and find the
remainder when divided by 14

21
Example
#include<stdio.h>
int main(){
int x=20, a, b;
a=x++;
b=x--;
printf(“Value of a is %d",a);
printf(“Value of b is %d",b);
return 0;
}
22
Task
1. Write a C program calculate the remainder when
a number is divided by 3 and then add one(1) to
the value using the increment operator
i. Define variable and initialize with number
ii. Get reminder after dividing by 3
iii. Increment by 1 (++) and print

2. Write a C grogram to take input temperature in


Celsius and convert it to Fahrenheit
i. Take input from user in Celsius (scanf) 24
ii. Use formula to convert to Fahrenheit and print
Relational Operators(A=10, B=20)
Operat Description Example
or
== Checks if the values of two operands are equal (A == B) is not true.
or not. If yes, then the condition becomes true.

!= Checks if the values of two operands are equal (A != B) is true.


or not. If the values are not equal, then the
condition becomes true.

> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand. If yes, then the
condition becomes true.

25
Con’t
< Checks if the value of (A < B) is true.
left operand is less
than the value of right
operand. If yes, then
the condition becomes
true.
>= Checks if the value of (A >= B) is not true.
left operand is greater
than or equal to the
value of right operand.
If yes, then the
condition becomes
true.
<= Checks if the value of (A <= B) is true.
left operand is less
than or equal to the 26
value of right operand.
Example
#include<stdio.h>
int main(){
int pw;
scanf(“%d”,&pw);
if(pw == 100){
printf(“Login successful!!”);
}
return 0; } 27
Logical Operators(A=1, B=0)
Operat Description Example
or
&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then the condition
becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands is non-zero, then the condition
becomes true.

! Called Logical NOT Operator. It is used to !(A && B) is true.


reverse the logical state of its operand. If a
condition is true, then Logical NOT operator will
make it false.

28
Example
#include<stdio.h> if(coursework >= 15 &&
int main(){ fees <= 0){
int fees, coursework; printf(“You are eligible for
printf (“\nEnter course work exams!!”);
”); }
scanf(“%d”,&coursework); else{
printf (“\nEnter fees balance printf(“Clear fees balance or
”); redo cw”);
scanf(“%d”,&fees); } 29
Logical AND (&&)
We shall go to the movies and the restaurant

Logical OR (||)
We shall go to the movies or the restaurant

30
Assignment Operators
Operat Description Example
or
= Simple assignment operator. Assigns values C = A + B will assign the
from right side operands to left side operand value of A + B to C

+= Add AND assignment operator. It adds the right


C += A is equivalent to C = C
operand to the left operand and assign the
+A
result to the left operand.
-= Subtract AND assignment operator. It subtracts
the right operand from the left operand and C -= A is equivalent to C = C -
assigns the result to the left operand. A

*= Multiply AND assignment operator. It multiplies


the right operand with the left operand and C *= A is equivalent to C = C *
assigns the result to the left operand. 31
A
Con’t
/= Divide AND assignment operator. It
divides the left operand with the right
operand and assigns the result to the left C /= A is equivalent to C = C / A
operand.

%= Modulus AND assignment operator. It


takes modulus using two operands and
assigns the result to the left operand. C %= A is equivalent to C = C % A

32
Misc Operators(sizeof and ? :)
Operat Description Example
or

sizeof() sizeof(a), where a is integer, will return 4.


Returns the size of a variable.

& &a; returns the actual address of the


Returns the address of a variable. variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value X :


Conditional Expression. otherwise value Y

33
Operators Precedence in C
Certain operators have higher precedence than
others; for example, the multiplication operator has
a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13,
not 20 because operator * has a higher precedence
than +

34
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= Right to left


^= |=

Comma , Left to right

35
Task
Write a C program that calculates the area of
different shapes based on user input.
– Print to screen Sample - Enter the shape you want to calculate
(1 - Square, 2 - Circle, 3 - Triangle):
– Take input for user choice (scanf)
– if(square)//take input for length and width and calculate
– if(circle)//take input for radius and calculate
– if(triangle)//take input for base and height and calculate
36
CONTROL STATEMENTS

37
Decision making
Used when one or more conditions
to be evaluated by the program,
along with a statement to be
executed if the condition is true,
and optionally, other statements
to be executed if the condition is
false.
C assumes any non-
zero and non-null values as true,
and if it is either zero or null, then
it is assumed as false value.
38
If
An if statement consists of a boolean expression
followed by one or more statements.

if(expression){
//code to be executed
}

39
Example 1
#include<stdio.h>
int main(){
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
return 0;
} 40
if(b>a && b > c)
Example 2 {
#include <stdio.h> printf("%d is largest",b);
int main() }
{ if(c>a && c>b)
int a, b, c; {
printf("Enter three numbers?"); printf("%d is largest",c);
}
scanf("%d %d %d",&a,&b,&c); if(a == b && a == c)
if(a>b && a>c) {
{ printf("All are equal");
printf("%d is largest",a); }
} }
41
Failed Task – second chance
#incl…
int mai…{
– Define variable choice (int) and take input for choice
(scanf)
– Check if choice == 1 [inside if, take input for length and
width and calculate area]
– Check if choice == 2 [inside if, take input for radius and
calculate area]
42
– Check if choice == 3 [inside if, take input for height and
If Else
An if statement can be followed by an optional else statement,
which executes when the Boolean expression is false.

if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}
43
Task
Write a C program to check if a number is even or
odd using:
#include<stdio.h>
int main(){
int num = 5;
if(num %2 == 0){
printf(“Number is even”);
}
else{
printf(“Number is odd”);
44
}}
Task
Write a C program to take input integer and print
“Divisible” if input is divisible by 5 else print “Not
divisible”

45
Nested If
You can use one if or else if statement inside another if or else
if statement(s).

if(expression){
//code to be executed
if(expression){
//code to be executed
}
} 46
If else-if ladder Statement(Multiple
conditions)
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
} 47
else if(number==50){
Example 1 printf("number is equal to 50");

#include<stdio.h> }
int main(){ else if(number==100){
int number=0; printf("number is equal to 100"
);
printf("enter a number:");
}
scanf("%d",&number); else{
if(number==10){ printf("number is not equal to
printf("number is equals to 1 10, 50 or 100");
0"); }
} return 0;
}
48
Task
Write a program in C to implement a grading system
using if-else as follows
– 80 and above = A
– Between 75 to 79= B+
– Between 70 to 74= B
– Between 60 to 69 = C
– Between 50 to 59 = D
– Below 50 = F 49
#include <stdio.h>
int main () { case 'F' :
char grade = 'B'; printf("Better try again\n" );
switch(grade) { break;
case 'A' : default :
printf("Excellent!\n" ); printf("Invalid grade\n" );
break; }
case 'B' : printf("Your grade is %c\n", grade );
printf(“Very good!\n" ); return 0;
break; }
case 'C' :
printf("Well done\n" );
break;
53
The ? : Operator
We have covered conditional operator ? : in the previous
chapter which can be used to replace if...else statements.
Exp1 ? Exp2 : Exp3;
How the value of a ? expression is determined −
Exp1 is evaluated. If it is true, then Exp2 is evaluated and
becomes the value of the entire ? expression.
If Exp1 is false, then Exp3 is evaluated and its value
becomes the value of the expression.
54
Task
Write the C program
– User selects conversion type
– Take input values and convert
– Conversions Types:
 Km to mile
 Meter to feet
 Liter to ounce

55
The End

56

You might also like