Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Computer only understand binary format and human can understand only English
language. So Programming language allows user to communicate with computer and write a
program(Software).
e. C vs. C++
Machine code is written using 0’s and 1’s and it’s difficult to understand
or read. Usually compilers and interpreters convert the source code into machine
code.
High-level language is machine independent. It’s more user friendly and use
English like words so the user can understand it very easily. Use compiler or
interpreter to translate into machine language.
Low-level language is machine dependent. It’s more machine friendly. It’s
difficult to understand or read hence its written using 0’s and 1’sor symbols.
c. Compiler vs. Interpreter
Compiler: Scans the entire program and translates the whole program at
once. Generates error messages only after scanning the whole program, Ex: C,C++
Interpreter: Translates the program line by line at at a time. Continues
translating the program until the first error is met, in which case it stops.Ex:
Python, Ruby.
Structured Language
Structured Programming is designed which focuses on process/ logical
structure and then data required for that process.
Structured programming follows top-down approach.
Structured Programming is also known as Modular Programming and a subset
of procedural programming language.
In Structured Programming, Programs are divided into small self-
contained functions.
e. C vs. C++
C
C is a procedural programming language
In C language, the solution is achieved through a sequence of procedures or steps. Therefore
is a function driven language.
C++
C++ can model the whole solution in terms of objects and that makes the solution better
organized. C++ is an object driven language.
f. C++ vs java
C++
C++ is mainly used for system programming
C++ supports multiple inheritance.
C++ supports operator overloading.
C++ supports pointers. You can write pointer program in C++.
C++ uses compiler only.
Java
Java is mainly used for application programming. It is widely used in window, web-
based, enterprise and mobile applications.
Java doesn't support multiple inheritance through class. It can be achieved by
interfaces in java.
Java doesn't support operator overloading.
But you can't write the pointer program in java. It means java has restricted ava
supports pointer internally. Pointer support in java.
Java uses compiler and interpreter both.
Logical Errors: Errors that prevent your program from what you are expecting from
it.In these types of errors you won’t get any error messages.Ex: Using a different number
which is not suppose to.
Tutorial 2
5. Determine which of the following are valid identifiers. If invalid, explain why.
(b) 1record : invalid ; The first character of the identifier must be a letter of the
alphabet
(c) file-3 : invalid ; The rest of the identifier name can consist of letters (upper or
lowercase),underscore(‘_’) or digits (0-9).
(e) $tax : invalid ; The first character of the identifier must be a letter of the
alphabet (upper or lowercase ) or an underscore(‘_’).
(f) name : valid
(g) name and address ; invalid ; You can’t put spaces between an identifers
(h) name-and-address ; invalid ; The rest of the identifier name can consist of
letters (upper or lowercase),underscores(‘_’) or digits (0-9).
(j) 123 - 45 - 6789 ;The first character of the identifier must be a letter of the
alphabet
6. State whether each of the following is true or false. If false, explain why.
Flase ; comments are not print on the screen when the program
execute.
True
True
True
g) A program that prints three lines of output must contain three printf
statements.
Flase ; In one printf you can print three lines using \n inside the
printf)
printf( "*\n**\n***\n****\n*****\n" );
output
**
***
****
*****
8. Identify and correct the errors in each of the following statements. (Note:
There may be more than one error per statement.)
scanf(“%d”,&value);
scanf(“%d”,&lnteger);
d) printf( "Remainder of %d divided by %d is\n", x, y, x % y );
a) printf( "%d", x );
b) printf( "%d", x + x );
c) printf( "x=" );
x=
d) printf( "x=%d", x );
x=2
5=5
f) z = x + y;
nothing
nothing
h) /* printf( "x + y = %d", x + y ); */
nothing
i) printf( "\n" );
nothing
10. State which of the following are true and which are false. If false, explain
your answer.
True
False, This is not an assignment statement. this only print the a=5; on the
screen.
Tutorial 03
Q1. Write four different C statements that each add 1 to integer variable x.
x= x+1;
x+=1;
x++;
++x;
Tutorial 04
1) What is wrong with the following if statement (there are at least 3 errors).
The Indentation indicates the desired behavior.
++numNeighbors;
else
--numNeighbors;
int number = 4;
if (number > 0)
if (alpha > 0)
else
Output
if (doesSignificantWork)
if (makesBreakthrough)
nobelPrizeCandidate = true;
else
nobelPrizeCandidate = false;
else if (!doesSignificantWork)
nobelPrizeCandidate = false;
If(taxCode==’T’)
– If integer variable opCode has the value 1, read in double values for X and Y
and calculate and print their sum.
double x,y,sum;
If(opcode=1)
printf(“Enter the two numbers);
scanf(“%lf %lf”,&x,&y);
sum = x +y;
printf(“sum is %lf”,sum);
– If integer variable currentNumber is odd, change its value so that it is now 3 times
currentNumber plus 1, otherwise change its value so that it is now half of
currentNumber (rounded down when currentNumber is odd).
if(currentNumber%2==1)
currentNumber=(currentNumber*3)+1;
else
currentNumber=currentnumber*0.5;
– Assign true to the boolean variable leapYear if the integer variable year is a leap
year. (A leap year is a multiple of 4, and if it is a multiple of 100, it must also be a
multiple of 400.)
int main()
int year;
scanf("%d",&year);
if(year%4 == 0)
if( year%100 == 0)
if ( year%400 == 0)
else
else
else
}
– Assign a value to double variable cost depending on the value of integer
variable distance as follows:
Distance Cost
----------------------------------- ----------
double cost;
if(distance> 0 && distance<100)
cost=5.00;
else if(distance> 100 && distance<500)
cost=8.00;
else if(distance>500 && distance<1000)
cost=10.00;
else(distance== 1000 && distance>1000)
cost=12.00;
Tutorial 05 – Writing switch condition, while, do while & for loops
Switch
Input two numbers and display the outputs of the basic mathematic operations. The output screen
should be displayed as follows;
#include <stdio.h>
#include <stdlib.h>
int main()
char x;
float no1,no2;
scanf("%f %f",&no1,&no2);
printf("1.+\n2.-\n3.*\n4./\n");
scanf("%s",&x);
switch(x)
While loop
1. Input 10 numbers and display the total count of odd & even numbers in the entered number
series.
#include <stdio.h>
#include <stdlib.h>
int main()
int counter=1,oddcount=0,evencount=0,no;
while(counter<=10)
scanf("%d",&no);
if(no%2==0)
evencount=evencount+1;
else
oddcount=oddcount+1;
counter++;
}
2. Modify the above program in to enter series of numbers terminates when the user enter -
99 and display the same expected output.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int oddcount=0,evencount=0,no;
while(no!=-99)
{
printf("Enter the number:");
scanf("%d",&no);
if(no%2==0 && no!=-99)
evencount=evencount+1;
if(no%2==1 && no!=-99)
oddcount=oddcount+1;
}
printf("The total odd count is %d \n",oddcount);
printf("the total even count is %d",evencount);
}
Do while loop
Rewrite the programs for the above while loop question 1 & 2 using do while loop
1. #include <stdio.h>
#include <stdlib.h>
int main()
int counter=1,oddcount=0,evencount=0,no;
do
scanf("%d",&no);
if(no%2==0)
evencount=evencount+1;
else
oddcount=oddcount+1;
counter++;
}while(counter<=10);
2. #include <stdio.h>
#include <stdlib.h>
int main()
int oddcount=0,evencount=0,no;
do
scanf("%d",&no);
evencount=evencount+1;
oddcount=oddcount+1;
}while(no!=-99);
For loop
1. Input 10 numbers and display the average value using the for loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
float x,no,total=0,avg;
for(x=1;x<=10;x++)
{
printf("enter the number:");
scanf("%f",&no);
total+=no;
}
avg=total/10;
printf("Average value of numbers is %f ",avg);
}
2. Display the following output using the for loop
*
**
***
****
*****
Output
int main()
int x,y;
for(x=1;x<=5;x++)
for(y=1;x>=y;y++)
printf("*");
}
printf("\n");
Tutorial 06–
Following illustration shows the process of calculating the matrix sum. The values are used as
samples.
3 2 4 2 6 3 5 8 7
1 4 6 + 4 3 2 = 5 7 8
4 3 2 5 1 7 9 4 9
#include <stdio.h>
#include <stdlib.h>
int main()
int a[3][3],b[3][3],c[3][3],i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf("\t %d",a[i][j]);
printf("\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
printf("\t %d",b[i][j]);
printf("\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j] =a[i][j]+b[i][j];
printf("\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf("\t %d",c[i][j]);
printf("\n");
}
Tutorial 07– Functions in C Language
1.Write a function that will read 2 numbers and calculate and display sum and difference.
#include <stdio.h>
#include <stdlib.h>
void sumdifference()
{
int x,y,sum=0,difference;
printf("Enter 2 Numbers");
scanf("%d %d",&x,&y);
sum=x+y;
difference=x-y;
printf("the sum is %d\n",sum);
printf("the difference is %d\n",difference);
}
int main()
{
sumdifference();
return 0;
}
2. Write a function that accepts 2 numbers as parameters and calculate and display sum and
difference.
#include <stdio.h>
#include <stdlib.h>
void sumdiffrence(int x,int y)
{
int sum=x+y,difference=x-y;
printf("The sum is %d\n",sum);
printf("the difference is %d",difference);
}
int main()
{
int a,b;
printf("Enter 2 Numbers");
scanf("%d %d",&a,&b);
sumdiffrence(a,b);
return 0;
}
3. Write a function that accepts 2 whole numbers as parameters and calculate and return the
product.
#include <stdio.h>
#include <stdlib.h>
int calproduct(int x,int y)
{
int product=x*y;
return product;
}
int main()
{
int a,b;
printf("Enter 2 whole numbers");
scanf("%d %d",&a,&b);
int ans = calproduct(a,b);
printf("The product is %d\n",ans);
}
4. Write a function that accepts 2 whole numbers as parameters and calculate and return the
quotient.
#include <stdio.h>
#include <stdlib.h>
int calquotient(int x,int y)
{
int quotient=x/y;
return quotient;
}
int main()
{
int a,b;
printf("Enter 2 whole numbers");
scanf("%d %d",&a,&b);
int ans=calquotient(a,b);
printf("The quotient is %d",ans);
}
5. Write a function to read 2 numbers and display the sum. Call this function from
the main function several times.
#include <stdio.h>
#include <stdlib.h>
void sum()
{
int sum=0,x,y;
printf("Enter 2 numbers");
scanf("%d %d",&x,&y);
sum=x+y;
printf("The sum is %d\n",sum);
}
int main()
{
sum();
sum();
sum();
}
6.Write a function which accepts 2 integers as parameters and display the sum,
difference and product using a single printf statement.
#include <stdio.h>
#include <stdlib.h>
int sdp(int x,int y)
{
int sum=x+y,difference=x-y,product=x*y;
printf("The sum is %d\n The difference is %d\n The product is
%d",sum,difference,product);
}
int main()
{ int a,b;
printf("Enter 2 numbers");
scanf("%d %d",&a,&b);
sdp(a,b);
return 0;
}
7. Write a function which accepts an integer and a float value as parameters
and return the product as a double value. Display the result from the main function.
#include <stdio.h>
#include <stdlib.h>
double calproduct(int x,float y)
{
double product=x*y;
return product;
}
int main()
{
int x;
float y;
printf("Enter a whole number\n");
scanf("%d",&x);
printf("Enter a decimal number\n");
scanf("%f",&y);
double ans = calproduct(x,y);
printf("The product is %.2lf",ans);
return 0;
}
8.Give the function header for each of the following functions.
a. Function hypotenuse that takes two double-precision floating-point arguments,
side1 and side2, and returns a double-precision floating-point result.
b. Function smallest that takes three integers, x, y, z, and returns an integer.
c. Function instructions that does not receive any arguments and does not return a
value. [Note: Such functions are commonly used to display instructions to a user.]
d. Function intToFloat that takes an integer argument, number, and returns a
floatingpoint result.
a.
double hypotenuse (double side1,duble side 2)
{
Double hypotenuse=sqrt((side1)*2+ (side2)*2);
Return double;
}
b.
Int smallest (int x,int y,int z)
{
Int min=x;
If (min>y)
Y=min;
If (min>z)
z=min;
Return min;
}
c.
void instructions( )
{
Printf(“instructions”);
}
d.
float inttofloat (int x)
{
Return x;
}
PRACTICAL 01
#include <stdio.h>
int main ()
printf("Name: Dushan\n");
return 0 ;
#include <stdio.h>
int main ()
printf("*\n");
printf("**\n");
printf("***\n");
printf("****\n");
printf("*****\n");
return 0;
3. Input values for int,float,double and char data types and display the value of each of the
variable.
#include <stdio.h>
int main ()
int x;
float f;
double d;
char c;
scanf("%d",&x);
scanf("%f",&f);
scanf("%lf",&d);
scanf(" %c",&c);
return 0;
#include <stdio.h>
int main ()
int x,y,t;
printf("Enter a number\n");
scanf("%d",&x);
printf("Enter a number\n");
scanf("%d",&y);
t=x+y;
printf("total is %d",t);
return 0;
5. Input two numbers with decimals and display the average with decimals
#include <stdio.h>
int main ()
{
float x,y,avg;
printf("Enter a number\n");
scanf("%f",&x);
printf("Enter a number\n");
scanf("%f",&x);
avg=(x+y)/2;
printf("Average is %f",avg);
return 0;
6. Input a student name, birth year and display student name with age.
#include <stdio.h>
int main ()
int by;
char name[25];
scanf("%s",&name);
scanf("%d",&by);
return 0;
7. Input two numbers, swap the values and display the output. ( Before swap and after
swap)
#include <stdio.h>
int main ()
int x,y;
printf("Enter a number\n");
scanf("%d",&x);
printf("Enter a number\n");
scanf("%d",&y);
return 0;
#include<stdio.h>
main()
{
printf("The color: %s\n", "blue");
printf("First number: %d\n", 12345);
printf("Second number: %04d\n", 25);
printf("Third number: %i\n", 1234);
printf("Float number: %3.2f\n", 3.14159);
printf("Hexadecimal: %x\n", 255);
printf("Octal: %o\n", 255);
printf("Unsigned value: %u\n", 150);
printf("Just print the percentage sign %%\n", 10); }
The color: blue
Hexadecimal: ff
Octal: 377
PRACTICAL 2
Question 1
#include <stdio.h>
int main()
int age;
scanf("%d",&age);
printf("\n\nWelcome(%d)",age);
printf("Let's Be Friends");
}
Question 2
#include <stdio.h>
int main()
}
Question 3
#include <stdio.h>
int main()
int d,t;
scanf("%d",&d);
scanf("%d",&t);
#include <stdio.h>
int main()
float fahr,cel;
scanf("%f",&fahr);
cel=(fahr-32)/1.8;
return 0;
}
Question 5
#include<stdio.h>
int main(){
int i=5,j;
j=(++i)+(++i)+(++i);
printf("%d %d",i,j);
return 0;
} // output 8, 22
Question 6
#include<stdio.h>
int main(){
int i=1;
i=2+2*i++;
printf("%d",i);
return 0;
} //Output 4
Question 7
#include<stdio.h>
int main(){
int a=2,b=7,c=10;
c=a==b;
printf("%d",c);
return 0;
}// output 0
Question 8
#include<stdio.h>
int main(){
int a=0,b=10;
if(a=0){
printf("true");
else{
printf("false");
return 0;
}// false
Question 9
#include<stdio.h>
int main(){
int a;
return 0;
} //output 131
Question 10
#include<stdio.h>
int main(){
int i=5;
printf("%d",a);
return 0;
}//output 22
PRACTICAL 3
1 .Write a program to input two numbers and display the highest number.
#include<stdio.h>
int main()
int x,y;
scanf("%d %d",&x,&y);
if(x>y)
printf("%d",x);
else
printf("%d",y);
return 0;
2.Write a complete program to ask user enter three integer numbers, and then tell the user
the largest value and smallest value among the three numbers.
#include<stdio.h>
int main()
int x,y,z;
printf("Enter 3 numbers\n");
scanf("%d %d %d",&x,&y,&z);
if(x>y&&x>z)
else if (y>z&&y>x)
else
return 0;
3.Display employee name, new salary, when the user inputs employee name, and basic salary.
You can refer following formula and the table to calculate new salary:
New Salary = Basic Salary + Increment
Basic Salary Increment
Less than 5000 5% of Basic Salary
More than or equal 5000
and less than 10000 10% of Basic Salary
More than or equal 10,000 15% of Basic Salary
#include <stdio.h>
#include <stdlib.h>
int main()
{
float basicsal,newsal;
char name[25];
if(basicsal<5000)
newsal=basicsal+basicsal*5.0/100;
if(basicsal>=5000)
newsal=basicsal+basicsal*10.0/100;
if(basicsal>=10000)
newsal=basicsal+basicsal*15.0/100;
printf("Name :%s\n New salary is :%.2f\n",name,newsal);
return 0;
}
4.(Diameter, Circumference and Area of a Circle) Write a program that reads in the
radius
of a circle and prints the circle’s diameter, circumference and area. Use the constant
value 3.14159 for π. Perform each of these calculations inside the printf statement(s)
and use the conversion specifier %f.
#include<stdio.h>
int main()
{
float r,c,d,a,pi=3.14159;
printf("Enter the radius of the circle\n");
scanf("%f",&r);
c=(2*pi*r);
d=2*r;
a=(pi*r*r);
printf("The circumference of the circle %f\n",c);
printf("The diameter of the circle %f\n",d);
printf("The area of the circle %f",a);
return 0;
}
5. Write a program that reads in two integers and determines and prints if the first
#include<stdio.h>
int main()
int x,y;
printf("Enter 2 numbers\n");
scanf("%d %d",&x,&y);
if (y%x==0)
else
return 0;
6.Write a C program that prints the integer equivalents of some uppercase letters,
lowercase letters, digits and special symbols. As a minimum, determine the integer
equivalents of the following: A B C a b c 0 1 2 $ * + / and the blank character.
#include<stdio.h>
int main()
printf("%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n",'A','B','
C','a','b','c','0','1','$','*','+','/',' ');
return 0;
Output 65,66,67,97,98,99,48,49,36,42,43,47,32
7. The gross remuneration of a company salesman comprises the Basic Salary and certain
additional allowances and bonuses as given below:
Salesmen with over 5 years’ service receive a 10% additional allowance of Basic
Salary each month.
Salesmen working in Colombo ( Input character ‘C’ if the city is Colombo) receive
an additional allowance of Rs. 2,500/- per month.
of monthly sales
0-25000 10
25000-50000 12
>=50000 15
#include <stdio.h>
#include <stdlib.h>
int main()
int year;
char city,c[1];
float basicsalary,newsalary,monthlysalary,allo1,allo2,allo3;
scanf("%f",&basicsalary);
scanf("%f",&monthlysalary);
scanf("%d",&year);
if (year>=5)
allo1=basicsalary*0.10;
if (city=c)
allo2=basicsalary+2500;
if(monthlysalary<25000)
basicsalary=monthlysalary + (monthlysalary*0.10);
if(25000<monthlysalary<50000)
basicsalary=monthlysalary + (monthlysalary*0.12);
if(monthlysalary>=50000)
basicsalary=monthlysalary + (monthlysalary*0.15);
newsalary=(basicsalary+allo1+allo2+allo3);
return 0;
}
Practical Number 04
Areas covered Selection and iteration control structures
1.Input 10 numbers and to output number of positive, number of negative, number of zeros
#include <stdio.h>
#include <stdlib.h>
int main()
int number;
int positive = 0;
int negative = 0;
int zero = 0;
scanf("%d", &number);
if(number > 0)
positive++;
negative++;
else
zero++;
printf("The number of positive integers %d\n The number of negative integers %d\nThe
numbers which are zero %d",positive,negative,zero);
}
2.Input Marks of 10 students and output the maximum , minimum and average Marks.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float marks;
float max = 0;
float min = 100;
float average;
float total = 0;
int i;
}
printf("Total - %f\n", total);
printf("Average - %f", total/10);
printf("Max - %f", max);
printf("Min - %f", min);
3.Input price of 10 items and display the average value of an Item , number of items which
the price is greater than 200.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float price;
float total;
int num = 0;
float avg;
return 0;
}
4.Input the Employee no and the Basic Salary of the Employees in an organisation ending
with the dummy value -999 for Employee no and count the number Employees whose Basic
Salary >=5000.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int employeeNo;
int basicSalary;
int num = 0;
while(1)
{
printf("Enter Employee number: ");
scanf("%d", &employeeNo);
if(employeeNo == -999)
break;
printf("Enter your salary: ");
scanf("%d",&basicSalary);
}
printf("The number of employees whose basic salary is >= 5000 are %d",num);
}
5. Input employee number, and hours worked by employees, and to display the following:
Employee number, Over Time Payment, and the percentage of employees whose Over Time
Payment exceeding the Rs. 4000/-.
The user should input –999 as employee number to end the program, and the normal Over Time
Rate is Rs.150 per hour and Rs. 200 per hour for hours in excess of 40.
#include <stdio.h>
#include <stdlib.h>
int main()
int employeeNo;
int hours;
float overTime;
int total = 0;
int totalOT = 0;
while(1)
overTime =0;
if(employeeNo == -999)
break;
scanf("%d", &hours);
total++;
totalOT++;
Q1) Use If-Else and write a program that reads an integer and determines and prints if the
number is even or odd. (I.e. divisible by 2)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number,rem;
printf("Enter a number: ");
scanf("%d",&number);
rem = (number % 2);
switch(rem)
{
case 1:printf("The number is odd");break;
case 0:printf("The number is even");break;
default: printf("Invalid input");
}
}
With if-else statements.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number,rem;
printf("Enter a number: ");
scanf("%d",&number);
if(number % 2 == 0)
printf("This number is even");
else
printf("This number is odd");
}
Q2) Write a simple menu driven calculator to perform (+ - / *) operations. (The program must
display a menu to select the desired operator.)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,a,b;
float avg;
printf("Enter a operator number: \n");
printf("1- +\n2- -\n3- /\n4- *\n");
scanf("%d", &num);
printf("Enter two numbers ");
scanf("%d %d", &a,&b);
avg = (float)a/b;
switch(num)
{
case 1:printf("%d + %d = %d",a,b, a+b);break;
case 2:printf("%d - %d = %d",a,b, a-b);break;
case 3:printf("%d/%d = %f",a,b,avg);break;
case 4:printf("%d*%d = %d",a,b,a*b);break;
}
}
Q4) Create a text-based, menu-driven program that allows the user to choose whether to calculate
the circumference of a circle, the area of a circle or the volume of a sphere. The program should
then input a radius from the user, perform the appropriate calculation and display the result.
#include <stdio.h>
#include <stdlib.h>
#define PI 3.14159
int main()
{
float radius;
int num;
printf("1-Calculate circumference\n2-Calculate circle area\n3-Calculate sphere volume\n");
scanf("%d",&num);
printf("Enter radius: ");
scanf("%f", &radius);
switch(num)
{
case 1:printf("Circumference of circle is %f", 2 * PI * radius);break;
case 2:printf("Area of circle is %f", PI * radius * radius);break;
case 3:printf("Volume of sphere is %f", (4 * PI * radius * radius * radius)/3);break;
}
}
Q5) Write a C program to read a character from the user and determine whether the given letter
is vowel or not. (Use a switch statement which also includes ‘default’ state).
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c", &c);
switch(c)
{
case 'a':case 'A':case 'e':case 'E':case 'i':case 'I':case 'o':case 'O':case 'u':case 'U':
printf("%c is a vowel", c);break;
default:printf("%c is not a vowel", c);
}
}
Q6) Write a C program to enter month number and print total number of days in month using
switch case. First assume that the given month belongs to a non-leap year.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int monthNo;
printf("Enter a month number: ");
scanf("%d", &monthNo);
switch(monthNo)
{
case 1:printf("Month %d has %d days", monthNo, 31);break;
case 2:printf("Month %d has %d days", monthNo, 28);break;
case 3:printf("Month %d has %d days", monthNo, 31);break;
case 4:printf("Month %d has %d days", monthNo, 30);break;
case 5:printf("Month %d has %d days", monthNo, 31);break;
case 6:printf("Month %d has %d days", monthNo, 30);break;
case 7:printf("Month %d has %d days", monthNo, 31);break;
case 8:printf("Month %d has %d days", monthNo, 31);break;
case 9:printf("Month %d has %d days", monthNo, 30);break;
case 10:printf("Month %d has %d days", monthNo, 31);break;
case 11:printf("Month %d has %d days", monthNo, 30);break;
case 12:printf("Month %d has %d days", monthNo, 31);break;
}
}
LOOPS
Q1) Write a C program to print numbers from 0 to 100. (You are required to write 3 separate
answers each using While, Do..While, For, looping structures).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number = 0;
for(number = 0;number <= 100; number++)
{
printf("%d\n", number);
}
printf("FOR LOOP\n");
number = 0;
do{
printf("%d\n",number);
number++;
}while(number <= 100);
printf("Do while LOOP");
}
Q2) Write a C program to calculate and print the total of 10 marks and the average. If the
average is less than 50 program should print “Fail!” otherwise “Pass!”
#include <stdio.h>
#include <stdlib.h>
int main()
{
float number = 0;
float total = 0;
float avg = 0;
int main()
{
int number;
int factorial = 1;
printf("Enter number for factorial: ");
scanf("%d", &number);
}
printf("Factorial %d", factorial);
}
Q4) Write a C program to calculate the sum of all digits of a user given number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number;
int sum = 0;
printf("Enter a number: ");
scanf("%d", &number);
while(number != 0)
{
sum += (number % 10);
number /= 10;
}
printf("The sum of numbers are %d", sum);
}
Q5) Write a C program to reverse the digits of a number using do-while statement.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int rem = 0;
int number;
int reversed = 0;
printf("Enter a number: ");
scanf("%d", &number);
while(number != 0)
{
rem = number % 10;
reversed = reversed * 10 + rem;
number /= 10;
}
printf("The reversed numbers is %d", reversed);
}
Q6) Write a C program to calculate nth power of a given integer. The user input base and
exponent. (Do NOT use inbuilt functions, instead use a loop)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int base;
int power;
int result = 1;
printf("Enter a base: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &power);
int main()
{
int first = 0,second = 1,n,i,next = 0;
printf("How many fibonacchi numbers do you want: ");
scanf("%d", &n);
int main()
{
int main()
{
int i = 0,j = 0, k = 1;
for(i = 0; i < 5; i++)
{
for(j = 0; j < k; j++)
{
printf("*");
}
printf("\n");
k++;
}
}
int main()
{
int num,i;
printf("Enter a number: ");
scanf("%d",&num);
for(i = 1; i <= num ; i++)
{
if(num % i == 0)
printf("%d is a facor of %d\n",i,num);
}
return 0;
}
Q12) Write a C program to add all user inputs until user input ‘-1’. And then display the sum.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int num = 0,sum = 0;
while(num != -1)
{
printf("Enter a number: ");
scanf("%d",&num);
if(num != -1)
sum += num;
}
printf("The sum is %d",sum);
return 0;
}
Q13) Write a C program to read user inputs for an integer array (size = 10) and print the array.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int numbers[10],i;
return 0;
}
Q14) Re-Write the above code to count all the even numbers in above integer array and display
the count.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int numbers[10],i,count = 0;;
if(numbers[i] % 2 == 0)
count++;
}
return 0;
}
Practical Number 05
Areas covered Single Dimensional Arrays
1. Declare a Single dimensional array with 10 elements. Input the values to the array and find
the followings;
I. Minimum value
II. Maximum value
III. Average value
IV. Reverse order of values
#include <stdio.h>
#include <stdlib.h>
int main()
int arr[10],i;
float avg,sum = 0;
min = 1E14;
max = 1E-14;
scanf("%d",&arr[i]);
sum += arr[i];
max = arr[i];
if(arr[i] < min)
min = arr[i];
return 0;
2. Declare two single dimensional array with the size given by the user and find , display the
followings;
Scalar Sum ( Adding values of each element of an array)
Vector Sum (Adding values of each relative elements of an array and store them in
third array)
Vector Product (Multiply values of each relative elements of an array and store
them in third array)
Scalar Product (Multiply values of each relative elements of an array and store them
in third array. After placing the values in third array add all the values)
#include <stdio.h>
#include <stdlib.h>
int main()
int a,b,i,sum = 0;
scanf("%d",&a);
scanf("%d",&b);
int arr1[a],arr2[b],arr3[a],arr4[a];
scanf("%d",&arr1[i]);
sum += arr1[i];
printf("\n");
sum = 0;
scanf("%d",&arr2[i]);
sum += arr2[i];
}
printf("\n");
if(a == b)
printf("%d, ",arr3[i]);
printf("\n");
printf("%d, ",arr4[i]);
return 0;
}
Practical Number 06
Areas covered Multi Dimensional Arrays
#include <stdio.h>
#include <stdlib.h>
int main()
int arr[3][4],i,j,max;
float avg,sum = 0;
max = arr[0][0];
scanf("%d",&arr[i][j]);
sum += arr[i][j];
max = arr[i][j];
printf("|");
printf("%d\t|",arr[i][j]);
printf("\n");
return 0;
}
Practical Number 07
Areas covered Functions
1. A parking garage charges a $2.00 minimum fee to park for up to three hours and an
additional $0.50 per hour for each hour or part thereof over three hours. The maximum
charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24
hours at a time. Write a program that will calculate and print the parking charges for each of
three customers who parked their cars in this garage yesterday. You should enter the hours
parked for each customer. Your program should print the results in a neat tabular format,
and should calculate and print the total of yesterday's receipts. The program should use the
function calculate Charges to determine the charge for each customer. Your outputs should
appear in the following format:
Car Hours Charge
1 1.5 2.00
2 4.0 2.50
3 24.0 10.00
TOTAL 29.5 14.50
#include <stdio.h>
#include <stdlib.h>
int main()
{
reciepts();
return 0;
}
void reciepts()
{
int n,i;
printf("Car\tHours\tCharge\n");
for(i = 0; i < n; i++)
{
float price = 0;
if(hours[i] <= 3)
{
price = 2.0;
}else if(hours[i] > 3)
{
price = 2 + ((hours[i] - 3) * 0.5);
}else if(hours[i] >= 24)
{
price = 10;
}
printf("%d\t%.2f\t%.2f\n",i+1,hours[i],price);
sumP += price;
}
printf("---------------------\n");
printf("Total\t%.2f\t%.2f",sumH,sumP);
printf("\n");
2. Define a function called hypotenuse that calculates the length of the hypotenuse of a right
triangle when the other two sides are given. Use this function in a program to determine the
length of the hypotenuse for each of the following triangles. The function should take two
arguments of type double and return the hypotenuse as a double.
3. Write a function integerPower(base, exponent) that returns the value of baseexponent For
example, integerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero
integer, and base is an integer. Function integerPower should use for to control the
calculation. Do not use any math library functions.
int i,ans = 1;
ans *= base;
return ans;
4) Write a program that inputs a series of integers and passes them one at a time to function even,
which uses the remainder operator to determine if an integer is even. The function should take an
integer argument and return 1 if the integer is even and 0 otherwise.
#include <stdio.h>
#include <stdlib.h>
int main()
int i,n;
scanf("%d",&n);
int num[n];
scanf("%d",&num[i]);
return 0;
5. Write a function that takes the time as three integer arguments (for hours, minutes, and
seconds) and returns the number of seconds since the last time the clock “struck 12.” Use
this function to calculate the amount of time in seconds between two times, both of which
are within one 12-hour cycle of the clock.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = timeSec(4,3,2);
int b = timeSec(3,5,6);
printf("Time1 is %d: \n",a);
printf("Time2 is %d: \n",b);
c) int main()
int i;
printf("Celcius \t Farenheit\n");
}
printf("-----------------------------\n");
printf("Farenheit \t Celcius\n");
return 0;
if(min > b)
min = b;
if(min > c)
min = c;
return min;
}
8)Write a function that takes an integer value and returns the number with its digits reversed. For
example, given the number 7631, the function should return 1367.
while(num != 0)
num /= 10;
return ans;
8. Write a function qualityPoints that inputs a student’s average and returns 4 if a student's
average is 90–100, 3 if the average is 80–89, 2 if the average is 70–79, 1 if the average is
60–69, and 0 if the average is lower than 60.
return 4;
return 2;
return 1;
else
return 0;
9. Write a function which gets an integer array and number of elements as parameters and
calculates and displays sum and average of all the integers of the array.
#include <stdio.h>
#include <stdlib.h>
int main()
int n;
scanf("%d",&n);
int arr[n];
arrSumAvg(arr,n);
return 0;
int i;
scanf("%d",&arr[i]);
sum += arr[i];
10. Write a function which gets two equal size integer arrays and number of elements as
parameters and calculates and displays sum of parallel elements of both arrays.
#include <stdio.h>
#include <stdlib.h>
void arrSum(int arr1[], int arr2[],int size);
int main()
arrSum(arr1,arr2,4);
return 0;
int i;
1. How do you write comments in a c program? What is the purpose of comments in a program?
Using // ‘comment’
*main function.
3. What is the purpose of ‘scanf’ ?
*Yes.
5. Determine which of the following are valid identifiers. If invalid, explain why.
(d) return
*Valid – a,f,i
6. State whether each of the following is true or false. If false, explain why.
b) Comments cause the computer to print the text enclosed between /* and */ on the
screen when the program is executed.
c) The escape sequence \n when used in a printf format control string causes the cursor
to position to the beginning of the next line on the screen.
d) All variables must be defined before they’re used.
g) A program that prints three lines of output must contain three printf statements.
c) true
d) true
e) true
f) false
g) false
printf( "*\n**\n***\n****\n*****\n" );
**
***
****
*****
8. Identify and correct the errors in each of the following statements. (Note: There may be more
than one error per statement.)
a) scanf(“%d”,&value);
b) printf( "The product of %d and %d is %d"\n, x, y , x* y);
c) scanf( "%d", &anInteger );
d) printf( "Remainder of %d divided by %d is %d\n", x, y, x % y );
e) printf( "The sum is %d\n," x + y );
f) printf( "The value you entered is: %d\n, value );
9. What, if anything, prints when each of the following statements is performed? If nothing prints,
then answer “Nothing.” Assume x = 2 and y = 3 .
a) printf( "%d", x );
b) printf( "%d", x + x );
c) printf( "x=" );
d) printf( "x=%d", x );
f) z = x + y;
i) printf( "\n" );
a) 2
b) 4
c) x=
d) x=2
e) 5=5
f) Nothing
g) Nothing
h) Nothing
i) Nothing(New line character)
10. State which of the following are true and which are false. If false, explain your answer.
b) The following are all valid variable names: _under_bar_ , m928134 , t5 , j7 , her_sales ,
his_account_total , a , b , c , z , z2 .
a) True
b) True
c) False
d) True
e) False
Q1. Write four different C statements that each add 1 to integer variable x.
x = x + 1;
x += 1;
x++;
++x;
a) Assign the sum of x and y to z and increment the value of x by 1 after the calculation.
b) Multiply the variable product by 2 using the *= operator.
d) Test if the value of the variable count is greater than 10. If it is, print “Count is greater
than 10.”
g) Calculate the remainder after q is divided by divisor and assign the result to q. Write
this statement two different ways.
h) Print the value 123.4567 with 2 digits of precision. What value is printed?
i) Print the floating-point value 3.14159 with three digits to the right of the decimal point.
What value is printed?
a) z = x++ + y;
b) product *= 2;
c) product = product * 2;
d) if(count > 10)
printf(“Count is greater than 10”);
e) total -= --x;
f) total += x--;
g) q = q % divisor
q %= divisor;
h) printf(“%.2f”,123.4567);
i) printf(“%.3f”,3.14159);
f) Increment variable i by 1.
g) Test i to see if it’s less than or equal to y in the condition of a while statement.
a) scanf(“%d”,&x);
b) scanf(“%d”,&y);
c) i = 1;
d) power = 1;
e) power *= x;
f) i++;
g) while(i <= y){}
h) printf(“%d”,power);
1) What is wrong with the following if statement (there are at least 3 errors). The
Indentation indicates the desired behavior.
if numNeighbors >= 3 || numNeighbors = 4
++numNeighbors;
else
--numNeighbors;
++numNeighbors;
} else
--numNeighbors;
if (number > 0)
if (alpha > 0)
else
if (doesSignificantWork) {
if (makesBreakthrough)
nobelPrizeCandidate = true;
else
nobelPrizeCandidate = false;
else if (!doesSignificantWork)
nobelPrizeCandidate = false;
4) Write if statements to do the following:
– If character variable taxCode is ’T’, increase price by adding the taxRate percentage of price
to it.
– If integer variable opCode has the value 1, read in double values for X and Y and calculate and
print their sum.
– If integer variable currentNumber is odd, change its value so that it is now 3 times currentNumber
plus 1, otherwise change its value so that it is now half of currentNumber (rounded down when
currentNumber is odd).
– Assign true to the boolean variable leapYear if the integer variable year is a leap year. (A leap
year is a multiple of 4, and if it is a multiple of 100, it must also be a multiple of 400.)
– Assign a value to double variable cost depending on the value of integer variable distance as
follows:
Distance Cost
----------------------------------- ----------
- If(taxCode == ‘T’)
Price += (price* taxrate);
- If(opcode == 1)
{
scanf(“%lf %lf”,&x,&y);
printf(“The sum is = %lf”,x+y);
}
- If(currentNumber % 2 != 0)
{
currentNumber = (currentNumber + 1) * 3;
else
{
currentNumber /= 2;
}
If(year % 4 == 0)
{
leapyear = true;
if(year % 100 == 0)
{
If(year % 400 == 0)
leapyear = true;
else
leapyear = false;
}
}
Switch
Input two numbers and display the outputs of the basic mathematic operations. The output screen
should be displayed as follows;
Int main()
scanf(“%d %d”,&num1,&num2);
printf(“1. + \n 2. - \n 3. * \n 4. / \n”);
scanf(“%d”,&op);
switch(op)
case4:printf(“Division = %f”,(float)num1/num2);
While loop
1. Input 10 numbers and display the total count of odd & even numbers in the entered number
series.
2. Modify the above program in to enter series of numbers terminates when the user enter -
99 and display the same expected output.
While(num > 0)
scanf(“%d”,&input);
if(input % 2 == 0)
even++;
else
odd++;
num--;
While(input != -99)
{
printf(“Enter a number: “);
scanf(“%d”,&input);
if(input % 2 == 0)
even++;
else
odd++;
num--;
Do while loop
Rewrite the programs for the above while loop question 1 & 2 using do while loop
Do
scanf(“%d”,&input);
if(input % 2 == 0)
even++;
else
odd++;
num--;
Do
scanf(“%d”,&input);
if(input % 2 == 0)
even++;
else
odd++;
num--;
while(input != -99);
For loop
1. Input 10 numbers and display the average value using the for loop
2. Display the following output using the for loop
*
**
***
****
*****
int num,i;
float avg,sum = 0;
sum += num;
int i,j;
printf("*");
printf("\n");
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr1[3][3],arr2[3][3],arr3[3][3],i,j;
scanf("%d",&arr1[i][j]);
scanf("%d",&arr2[i][j]);
{ printf("|");
printf("%d\t|",arr3[i][j]);
printf("\n");
return 0;
}
4. Write a function that will read 2 numbers and calculate and display sum and
difference.
void sumdiff()
float a,b;
scanf("%f",&a);
scanf("%f",&b);
5. Write a function that accepts 2 numbers as parameters and calculate and display
sum and difference.
6. Write a function that accepts 2 whole numbers as parameters and calculate and
return the product.
return a * b;
}
7. Write a function that accepts 2 whole numbers as parameters and calculate and
return the quotient.
8. Write a function to read 2 numbers and display the sum. Call this function from the
main function several times.
void sumdiff()
int a,b;
scanf("%f",&a);
scanf("%f",&b);
Int main()
sumdiff();
sumdiff();
sumdiff();
return 0;
9. Write a function which accepts 2 integers as parameters and display the sum,
difference and product using a single printf statement.
void sumdiff(int a, int b)
printf("The sum of entered values is: %d\n The difference of the values is: %d\n The
product of the values is: %d", a+b, a-b, a*b);
10. Write a function which accepts an integer and a float value as parameters and
return the product as a double value. Display the result from the main function.
return a * b;
int main()
printf("%.4f",val(3,4.53));
return 0;
11. Give the function header for each of the following functions.
e. Function hypotenuse that takes two double-precision floating-point arguments,
side1 and side2, and returns a double-precision floating-point result.
f. Function smallest that takes three integers, x, y, z, and returns an integer.
g. Function instructions that does not receive any arguments and does not return a
value. [Note: Such functions are commonly used to display instructions to a user.]
h. Function intToFloat that takes an integer argument, number, and returns a
floatingpoint result.
if(min > y)
min = y;
if(min > z)
min = z;
return min;
}
c) void instructions()
{
Printf(“Instructions”);
}
d) float intToFloat(int a)
{
return a;