Вы находитесь на странице: 1из 12

Instructions

1. Use Borland C for the following programs   
2. Create a folder CF_Lab2 in C or any other drive 
3. It is recommended to create a new file for each program, alternately modify the same file 
4. For any help contact lab staff or faculty member available in the lab   
5. If you want a copy of your programs, at the end of the lab session copy the lab folder from local 
drive to your Z‐drive

Topics Covered
1. VArious data types provided by C 
2. Format Sepcifier for data types 
3. Mod, increment, decrement operators 
4. Multiple input using scanf 
5. Relational operators 
6. If‐else statements 
7. Logical operators 

Task-01
Without executing this program write the output of this program on a paper, once you have written the 
predicted output on the paper , execute the program and compared the output shown by this program 
on the screen with the output you wrote down on the paper.   

#include <conio.h>
#include <stdio.h>
void main(void)
{
clrscr();
printf("This is year %d\n",2011);
printf("The sun will rise at %d:%d in the morning today \n",6,30);
printf("If we multiply %d with %d the answer will be %d \n",12,3,36);
printf("My friend %s came to visit me yesterday at %d-%d p.m.\n", "Ahmed",5,30);
printf("\n\t%d\n\t%d+\n\t----\n\t%d",10,20,30); getch();
}

Type conversion
Example-1
#include<stdio.h>
#include<conio.h>
void main()
{
int a=4,b=37;
float result;
result=b/a;
printf(“Result of 37 / 5 = %f”,result);
getch();

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
} Q: Is your output correct? If not why?
Second version of example-1
#include<stdio.h>
#include<conio.h>
int main()
{
float a=4.0,b=37.0;
float result;
result=b/a;
printf(“Result of 37 / 5 = %f”,result);
getch();
return 0;
}

Q Is your answer correct this time ?,Do you understand the type conversion problem involved ?
(You may read the following explanation or skip if you know answer to the question)

Explanation
Line 1) int a=4,b=37;
Line 2) float result;
Line 3) result=b/a;

At line 3 , the division b / a is an integer division, as in c/c++ if an operation involve integers only, the answer
will must be an integer, in our case fraction produced during division will be converted to integer and later
will be stored as float in the variable result;

We know that b/a = 37/4 = 9.25 but as the result is to be stored as it is an integer division the answer will be
an integer i.e. 9 only, as this value has to be stored in a float variable this value will be promoted (converted)
to float first i.e. 9 will be converted to 9.0 and then stored in result.

In case of result=10/3 , the value stored in result will be 3.0 not 3 or 3.3333… for same reasons

In case of result=10/3.0 or result=10.0/3 second value will be first promoted to float type i.e. in 10/3.0 10 will
be converted to 10.0 and the division will be 10.0/3.0 which a division of floating point numbers, the answer
will also be a float point number 3.333…. this value will be stored in variable result.

Task-02
Try to predict the value x in following statements, write programs to verify your answers. If your predicted
answer do not match with output of your program see explanation at the end of this document.

1. x=10/3 where x is an integer variable


2. x=25/6 where x is a float variable
3. x=25/6.0 where x is a float variable

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
Increment and Decrement Operators
Execute the example programs to understand the working of unary operators, if you understand the
concept try to solve the tasks that follow

Example‐2 Sample Program 
The following program demonstrate use of increment and decrement operators

#include <conio.h>
#include <stdio.h>
int main(){
int a,b,c;
a=10;
b=20;
c=30;
printf(“Starting value of a,b,c are\n“);
printf(“a=%d,b=%d,c=%d\n“,a,b,c);
printf(“after a++,b++,c++ value are\n”);
a++;
b++;
c++;
printf(“a=%d, b=%d ,c=%d \n“,a,b,c);
getch();
return 0;}
 
Example‐2B    Modified Sample Program 
#include <conio.h>
#include <stdio.h>
int main(){
int a,b,c;
a=10;
b=20;
c=30;
printf(“Starting value of a,b,c are\n“);
printf(“a=%d,b=%d,c=%d\n“,a,b,c);
a=b+(c++);
printf(“after a=b+(c++) values are \n”);
printf(“a= %d ,b =%d ,c =%d \n“,a,b,c);
getch();
return 0; }

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
Tasks-03
1) Write program for the following expressions, where a,b,c are integer variables, evaluate the expression and
display the final result (final value of variable a)
Initial values of a,b,c are 10,20,30

a) a=b*c;
b) b*=b+c;
c) c=a++;
d) a=++b+c++;

2) Enhance the code and get the values of a,b and c from the user

Example-3 Working with other data types

The following program demonstrates how other data types are declared and are printed

#include <conio.h>
#include <stdio.h>
int main()
{
char block_name = ‘Y’;
long int block_volume = 987654 ;
float block_density= 120.25 ;
double block_mass=98765410.65;
printf”Block name = %c \n”, block_name);
printf(”Block volume = %ldmeter cube \n” ,block_volume);
printf(”Block density = %f (grams/cm)\n “,block_density);
printf(”Block mass %f (kgs)”,block_mass);
getch();
return 0;
}

Using sizeof()
Example-4

sizeof() is a library function, the function returns the number of bytes allocated to any variable in the
memory, the function can also return the number of bytes that are specified for various data types. See the
example to understand the concept

#include <conio.h>
#include <stdio.h>
int main()
{
int a=20;

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
float b=1.8.3;
int size_a, size_b;
size_a=sizeof(a);
size_b=sizeof(b);
printf(”size of variable a is %d bytes \n “,size_a);
printf(”size of variable b is %d bytes “,size_b);
getch();
return 0;
}

Example-05 Print number of bytes specified for various data types


#include <conio.h>
#include <stdio.h>
int main()
{
printf(”size of int data type is %d bytes \n “,sizeof(int));
printf(”size of float data type is %d bytes “,sizeof(float));
getch();
return 0;
}
Try: Using sizeof function print size of all data types (use lecture slides to verify your output)
Try: use sizeof function to determine the number of bytes used by the program in example 6

Task-04
 A car is travelling with a velocity of 30 km/hour , how much time will it take to reach its destination
which is 600 km from starting point, represent the time in hours, minutes and seconds;
 Modify the above program such that it can find the time for any given velocity V and distance S
 Write a program to find the area of a circle whose radius is r , the program should take the value of
r from the user using scanf function and print the area of the circle.

Task -05
Write a program to solve the following equation for any values of a and b 
(a+b)2= (a2+b2+2ab);
 

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
Relational Operator
When programming, the aim of the program will often require checking of one value stored by a 
variable against another value to determine whether one is larger, smaller, or equal to the other. There 
are a number of operators that allow these checks. When a comparison is performed by relation 
operator the result is either true or false.Here are some of the relational operators,along with examples: 

Relational    Operator Purpose      Example 


 
  >    Greater than                        5 > 4 is TRUE,    3 > 4 is FALSE 
  <    Less than                                    4 < 5 is TRUE,    4 < 4 is FALSE 
  >=          Greater than or equal            4 >= 4 is TRUE,    3 >= 4 is FALSE 
  <=          Less than or equal                  3 <= 4 is TRUE,    5 <= 4 is FALSE 
  ==          Equal to                                      5 == 5 is TRUE,    3==6 is FALSE   
  !=           Not equal to                              5 != 4 is TRUE,    5!=5 is FALSE   

Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical 
operators: 

Operator  Meaning of Operator  Example 

&&  Logial AND  If c=5 and d=2 then,((c==5) && (d>5)) returns false. 

||  Logical OR  If c=5 and d=2 then, ((c==5) || (d>5)) returns true. 

!  Logical NOT  If c=5 then, !(c==5) returns false. 

Explanation

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the 
given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the 
expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is 
true, !(c==5) is false.

BASIC If, Elsestatement 
The structure of an if statement is as follows: 

if ( Comparison )
Line of code

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
The line of code will execute only if the comparison is true, if there are multiple line of code to be 
executed when a comparison is true, the structure will be as follows 

if ( Comparison ){
Line of code-1
Line of code-2
Line of code-3
Line of code-.
Line of code-.
Line of code-N
}
else
Sometimes when the condition in an if statement evaluates to false, it would be nice to execute some 
code instead of the code executed when the statement evaluates to true. The "else" statement 
effectively says that whatever code after it (whether a single line or code between brackets) is executed 
if the if statement is FALSE. 
It can look like this: 

if ( TRUE ) {
/* Execute these statements if TRUE */
}
else {
/* Execute these statements if FALSE */
}

Example‐06 

#include <stdio.h>
#include <conio.h>

int main()
{
int age;

printf( "Please enter your age" ); /*Asks for age */


scanf( "%d", &age ); /*The input is put in age */
if ( age < 100 ) { /*If the age is less than 100 */
printf ("\nYou are pretty young!" ); /*Executed if comparison is true
*/
}
else {
printf( "\nYou are really old\n" ); /*Executed if comparison is false
*/
}

getch();
return 0;
}

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
Task-06
Just for exercise convert the following statements into conditional statements for A, B, C and D, you do
not need to write program for this, either do it verbally or write down on your notebook. If you feel you
understand the concepts and do not need this exercise you may proceed to next part. To better
understand the task see the examples.

Given that A, B, C, D are all integer variables having some initial value (which is not known)

Example (Single condition)

Statement Conditional Statement


A is a positive number A>0
B is not zero B!=0
Example (Multiple Conditions)

Statement Conditional Statement

A and B are positive numbers A>0 && B>0


B and C are non zero numbers B!=0 && C!=0

Single Condition

1) A and B are equal


2) A is an even number
3) 5 C is a factor of C
4) B divides C and there is no remainder
5) C is greater than D
6) B is an odd number
7) Sum of A and B is less than C
8) C is greater than 100 and less than 200

Multiple conditions

1) C and D are negative numbers


2) A is greater than B and C is greater than D
3) A is even or B is odd number
4) A or B or C is a positive number
5) A and B are greater than 20 or C and D are less than 100
6) A and B are even numbers
7) A is even and B is odd number
8) C is positive and D is negative
9) A or B is even and C is odd

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
The % ( Modulus ) Operator
It returns the remainder of a division. e.g.

13%5 = 13 / 5 = 2 (quotient) + 3 (remainder) = 3

17%5= 17 / 5 = 3 (quotient) + 2 (remainder) = 2

56%13= 4 (quotient) + 4 (remainder) = 4

We can check if a number is even or odd by using % (mod) operator if a number is even the remainder
with 2 will be zero for odd number it will be a non zero number

3 %2 = 1 (3 is odd)

7 %2 = 1 (7 is odd)

6% 2 = 0 (6 is even)

The following program will get an integer from the user and will check whether the number is even or odd

Example-07
#include<stdio.h>
#include<conio.h>
int main(){
int num;
printf(“Enter a Number : “);
scanf(“%d”,&num);
if(num%2==0)
printf(“\nEven Number”);
else
printf(“\nOdd Number”);
getch();
return 0;}

Task-07
1. Re-write the program-2 and check that the number entered by the user is a multiple of 7 or not
2. Extend the program-2, get two numbers X and Y from the user, check that X completely divides Y or
not. If X does not divides Y print the remainder. The output of the program should be as follows

Sample Output

Enter value for X: 3

Enter value for Y: 10

X does not Divides Y

Remainder is = 1

Press any key to terminate the program. . .

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
Example-08 (Same or different numbers)
The following program will get three integers from the user and will check whether the numbers are same
or not

#include <stdio.h>
#include <conio.h>
int main(){
int a,b,c;
printf(“Enter value for A : “)
scanf(“%d”,&a);
printf(“\nEnter value for B : “)
scanf(“%d”,&b);
printf(“\nEnter value for C : “)
scanf(“%d”,&c);
if(a==b && a==c)
printf(“ \nThe numbers are same “);
else
printf(“\nThe numbers are different”);
getch();
return 0;}

Try: (Extend the program-03)

Re-write the program-03 and check which of the three numbers is greatest, print the value of the number as well. See
sample output

Sample Output-01

Enter value of A : 5

Enter value of B : 8

Enter value of C : 9

Result: 9 is greatest among 5,8 and 9

Sample Output-02

Enter value of A : 5

Enter value of B : 8

Enter value of C : 8

Result: 8 is greatest among 5, 8 and 8

 
CF‐Lab‐03 prepared by Nauman Shamim 
 
Task-08
Write a program that lets user enter an integer value between 1 and 10, the program validates the input
, if the value entered is between 1 and 10 the program prints the message “Valid Number” and value
entered otherwise the program should print message “Invalid Number” and value. For better
understanding of the problem following aretwo sample output of the program

Sample Output-1

Enter a number between 1 and 10 -->56


Invalid Number 56

Sample Output-2

Enter a number between 1 and 10 -->6


Valid Number 6

Task-09
Write a program that ask users to input marks of a subject and print the letter grade (See grading criteria
below). For details see the following sample execution of the program

Grading Criteria

Marks 51 – 60 D

Marks 61 – 70 C

Marks 71 – 80 B

Marks 81 – 100 A

Sample Output-1

Enter the marks: 80

Grade: A

Sample Output-2

(if user enters invalid marks)

Enter the marks: 125

Invalid marks, no grades can be assigned


 
CF‐Lab‐03 prepared by Nauman Shamim 
 
Task-10
Write a program that gets a three digit integer input and prints the sum of its digits. For example if user
enters 123 the program should calculate 1+2+3 = 6 as answer. To get an idea about the solution see
the program below

#include<stdio.h>
#include<conio.h>
void main(){
int num=12;
int digit1,digit2;
digit1=num%10;
digit2=num/10;
printf(“First digit is = %d ”,digit1);
printf(“\nSecond digit is =%d’,digit2);
}
Sample Output

Enter a number : 457


Sum of digits is=16

Task-11
Armstrong Numbers: An Armstrong number is an n-digit number that is equal to the sum of the nth
powers of its digits. For example 153 is an Armstrong number as it is a three digit number and if each
digit is raised to the 3rd power and summed the result will be 153.

13+53+33=153

Write a program that gets a three digit number from the user and checks whether the number is a
Armstrong number or not. Output of your program should be as under.

Hint: To check that a number is an Armstrong or not you first need to separate its digits as done in last
activity

Sample Output

Enter a number 342

Not a Armstrong number

Enter a number 371

The number is an Armstrong

 
CF‐Lab‐03 prepared by Nauman Shamim 
 

Вам также может понравиться