Sei sulla pagina 1di 99

S.A.D.

Dushan Nawodya - 10026123

Group A - 18.2 Batch


Bsc.(Hons) Software Engineering Plymouth university
Tutorial 01

1. Briefly explain the need of a programming language?

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).

2. Compare and contrast the differences between followings;

a. Source Code vs. Machine Code

b. High Level Language vs. Low Level Language

c. Compiler vs. Interpreter

d. Structured Language vs. Object Oriented Language

e. C vs. C++

f. C++ vs. Java Structured

g. Syntax error vs. Logical error

a. Source code vs machine code

Source Code is written using some kind of programming language which


we can understand very easily.

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.

b. High level language vs. Low level language

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.

d. Structured Language vs. Object Oriented Language

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.

Object oriented language


Object Oriented Programming is designed which focuses on data.
Object oriented programming follows bottom-up approach.
Object Oriented Programming supports inheritance, encapsulation,
abstraction, polymorphism, etc.
In Object Oriented Programming, Programs are divided into small entities
called objects.

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++

In addition to begin procedural, C++ is also an object oriented programming language.

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.

g. Syntax error vs. Logical error

Syntax Errors: Mistakes such as misspelled words, a missing punctuation character,


missing brackets, missing closing parenthesis. These type of errors are shown as errors in the
compiler.(or the translator which you are using)

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

1. How do you write comments in a c program? What is the purpose of


comments in a program?
There are two type of comments
Single line comment //
Multi line comment /*……………………………………………
………………………………………….*/
2. Which is the function that is essential in a C program?
Main Function
Int main ()

3. What is the purpose of ‘scanf’?


Allows user to input data into the program.

4. Is ‘standard c’ a case sensitive language?


Yes, all the syntax in c language is case sensitive.

5. Determine which of the following are valid identifiers. If invalid, explain why.

(a) record1 : valid

(b) 1record : invalid ; The first character of the identifier must be a letter of the
alphabet

(upper or lowercase ) or an underscore(‘_’).

(c) file-3 : invalid ; The rest of the identifier name can consist of letters (upper or
lowercase),underscore(‘_’) or digits (0-9).

(d) return : invalid ; You can’t use keyword in c as your identifiers.

(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).

(i) name_and_address; valid

(j) 123 - 45 - 6789 ;The first character of the identifier must be a letter of the
alphabet

(upper or lowercase ) or an underscore(‘_’). ; The rest of the identifier name can


consist of letters (upper or lowercase),underscores(‘_’) or digits (0-9).

6. State whether each of the following is true or false. If false, explain why.

a) Function printf always begins printing at the beginning of a new line.

False ; printf always begins printing where the cursor is stopped.

b) Comments cause the computer to print the text enclosed between /*


and */ on the screen when the program is executed.

Flase ; comments are not print on the screen when the program
execute.

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.

True

d) All variables must be defined before they’re used.

True

e) All variables must be given a type when they’re defined.


True

f) C considers the variables, number and NuMbEr to be identical.

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)

7. What does the following code print?

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.)

a) scanf( "d", value );

scanf(“%d”,&value);

b) printf( "The product of %d and %d is %d"\n, x, y );

printf(“The product of %d and %d is %d \n”,x,y(xy));

c) Scanf( "%d", anInteger );

scanf(“%d”,&lnteger);
d) printf( "Remainder of %d divided by %d is\n", x, y, x % y );

printf( "Remainder of %d divided by %d is %d \n", x, y, x % y );

e) print( "The sum is %d\n," x + y );

printf(“The sum is %d \n”,x+y);

f) Printf( "The value you entered is: %d\n, &value );

printf(“The value you enterd 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=" );

x=

d) printf( "x=%d", x );

x=2

e) printf( "%d = %d", x + y, y + x );

5=5

f) z = x + y;

nothing

g) scanf( "%d%d", &x, &y );

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.

a) C operators are evaluated from left to right.

False, It is depends on operator precedence.

b) The following are all valid variable names: _under_bar_ , m928134 , t5 ,


j7 , her_sales , his_account_total , a , b , c , z , z2 .

True

c) The statement printf("a = 5;"); is a typical example of an assignment


statement.

False, This is not an assignment statement. this only print the a=5; on the
screen.

d) A valid arithmetic expression containing no parentheses is evaluated


from left to right.

False ; it is evaluating mathematical order

e) The following are all invalid variable names: 3g , 87 , 67h2 , h22 , 2h

Flase ; h22 is valid. first character should be alphabet or underscore

Tutorial 03
Q1. Write four different C statements that each add 1 to integer variable x.

x= x+1;

x+=1;

x++;

++x;

Q2. Write a single C statement to accomplish each of the following:


a) Assign the sum of x and y to z and increment the value of x by 1 after
the calculation.
z=x+y;
x++;
b) Multiply the variable product by 2 using the *= operator.
Product *= 2;
c) Multiply the variable product by 2 using the = and * operators.
Product = product * 2;
d) Test if the value of the variable count is greater than 10. If it is, print
“Count is greater than 10.”
If(count>10)
{
Printf(“Count is greater than 10”);
}
e) Decrement the variable x by 1, then subtract it from the variable total.
Total -= --x;
f) Add the variable x to the variable total, then decrement x by 1.
Total += x--;
g) Calculate the remainder after q is divided by divisor and assign the
result to q. Write this statement two different ways.
q = q % divisor;
q %= divisor;
h) Print the value 123.4567 with 2 digits of precision. What value is printed?
Printf(“ %.2f ”, 123.4567); //displayed 123.45
i) Print the floating-point value 3.14159 with three digits to the right of the
decimal point. What value is printed?
Printf(“ %.3f ”, 3.14159); //displayed 3.142

Q3. Write single C statements that


a) Input integer variable x with scanf.
Scanf (“ %d ”, &x);
b) Input integer variable y with scanf.
Scanf (“ %d ”,& y);
c) Initialize integer variable i to 1.
i =1;
d) Initialize integer variable power to 1.
Power = 1;
e) Multiply variable power by x and assign the result to power.
power = power * x ;
f) Increment variable i by 1.
i++;
g) Test i to see if it’s less than or equal to y in the condition of a while
statement.
while ( i <= y)
h) Output integer variable power with printf.
Printf(“ %d ”,power );

Tutorial 04
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;

printf ("You are dead! \n " );

else

--numNeighbors;

NumNeighbors=4 is wrong should be recorrected as


numNeighbors==4

There is no () in the if statement

There is no {} inside the if block

2) Describe the output produced by this poorly indented program segment:

int number = 4;

double alpha = -1.0;

if (number > 0)

if (alpha > 0)

printf("Here I am! \n" );

else

printf("No, I’m here! \n");

printf(“No, actually, I’m here! \n");

It only print else part of the program

Output

No, I’m here!

No, actually, I’m here!


3) Consider the following if statement, where doesSignificantWork,
makesBreakthrough,

and nobelPrizeCandidate are all boolean variables:

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(taxCode==’T’)

Price = price+ (price*taxRate);

– 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;

printf("Enter a year: ");

scanf("%d",&year);

if(year%4 == 0)

if( year%100 == 0)

// year is divisible by 400, hence the year is a leap year

if ( year%400 == 0)

printf("%d is a leap year.", year);

else

printf("%d is not a leap year.", year);

else

printf("%d is a leap year.", year );

else

printf("%d is not a leap year.", year);

}
– Assign a value to double variable cost depending on the value of integer
variable distance as follows:

Distance Cost

----------------------------------- ----------

0 through 100 5.00

More than 100 but not more than 500 8.00

More than 500 but less than 1,000 10.00

1,000 or more 12.00

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;

Enter two numbers ____ ____


1. +
2. –
3. *
4. /

Please enter your Choice ___

#include <stdio.h>

#include <stdlib.h>

int main()

char x;

float no1,no2;

printf("Enter two numbers:");

scanf("%f %f",&no1,&no2);

printf("1.+\n2.-\n3.*\n4./\n");

printf("Please enter your choice:");

scanf("%s",&x);

switch(x)

case '+':printf("sum of your numbers is %.2f\n",no1+no2);break;

case '-':printf("difference of your numbers is %.2f\n",no1-no2);break;

case '*':printf("product of your numbers is %.2f\n",no1*no2);break;

case '/':printf("division of your numbers is %.2f\n",no1/no2);break;


default :printf("invalid");

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)

printf("Enter the number:");

scanf("%d",&no);

if(no%2==0)

evencount=evencount+1;

else

oddcount=oddcount+1;

counter++;

printf("The total odd count is %d \n",oddcount);

printf("the total even count is %d",evencount);

}
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

printf("Enter the number:");

scanf("%d",&no);

if(no%2==0)

evencount=evencount+1;

else
oddcount=oddcount+1;

counter++;

}while(counter<=10);

printf("The total odd count is %d \n",oddcount);

printf("the total even count is %d",evencount);

2. #include <stdio.h>

#include <stdlib.h>

int main()

int oddcount=0,evencount=0,no;

do

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;

}while(no!=-99);

printf("The total odd count is %d \n",oddcount);

printf("the total even count is %d",evencount);

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–

Working with Multi-Dimensional Arrays (Matrix)

Write a C program for the followings;

Declare two 3 x 3 square matrices and display the matrix sum.

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;

printf("Enter the values into the first matrix");

for(i=0;i<3;i++)

for(j=0;j<3;j++)

{
scanf("%d",&a[i][j]);

printf("Enter the values into the second matrix");

for(i=0;i<3;i++)

for(j=0;j<3;j++)

scanf("%d",&b[i][j]);

printf("print value to the first matrix");

for(i=0;i<3;i++)

for(j=0;j<3;j++)

printf("\t %d",a[i][j]);

printf("\n");

printf("print values to the second matrix");

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");

printf("addition two matrix");

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

1. Display your name and school name in two separate lines

#include <stdio.h>

int main ()

printf("Name: Dushan\n");

printf("School Name: St.Joseph Vaz College Wennappuwa");

return 0 ;

2. Display the following output using printf() statements

#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);

printf("%x %f %lf %c",x,f,d,c);

return 0;

4. Input two integers and display the total

#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];

printf("Enter your name\n");

scanf("%s",&name);

printf("Enter your birth year\n");

scanf("%d",&by);

printf("Student Name: %s\n",name);

printf("Birth Year : %d\n",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);

printf("Before Swap: %d %d\n",x,y);

printf("After Swap: %d %d",y,x);

return 0;

8. Execute the following code and analyze the output.

#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

First number: 12345

Second number: 0025

Third number: 1234


Float number: 3.14

Hexadecimal: ff

Octal: 377

Unsigned value: 150

Just print the percentage sign %

PRACTICAL 2

Question 1

#include <stdio.h>

int main()

int age;

printf("Hi,How old are you?");

scanf("%d",&age);

printf("\n\nWelcome(%d)",age);

printf("Let's Be Friends");

}
Question 2

#include <stdio.h>

int main()

printf("%5d%5d%5d\n", 2, 4, 8); //Right Align

printf("%5d%5d%5d\n", 3, 9, 27); //Right Align


printf("%5d%5d%5d\n", 4, 16, 64); //Right Align

}
Question 3

#include <stdio.h>

int main()

int d,t;

printf("Enter Distance Traveled");

scanf("%d",&d);

printf("Enter Time Taken");

scanf("%d",&t);

printf("Average speed is %.2fms-1",(float)d/t);

/*Intergers Truncuate decimal numbers

use Float or convert integres to float*/


Question 4

#include <stdio.h>

int main()

float fahr,cel;

printf("enter temperature in fahrenheit ");

scanf("%f",&fahr);
cel=(fahr-32)/1.8;

printf("Temperature in Celcius is %.4f",cel);

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;

a=015 + 0x71 +5;


printf("%d",a);

return 0;

} //output 131
Question 10

#include<stdio.h>

int main(){

int i=5;

int a=++i + ++i+ ++i;

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;

printf("Enter two numbers\n");

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)

printf("maximum number %d last number %d",x,z);

else if (y>z&&y>x)

printf("maximum number %d last number %d",y,z);

else

printf("maximum number %d last number %d",z,z);

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];

printf("Enter the name :");


scanf("%s",&name);
printf("Enter the basic salary :");
scanf("%f",&basicsal);

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

is a multiple of the second.

#include<stdio.h>

int main()

int x,y;

printf("Enter 2 numbers\n");

scanf("%d %d",&x,&y);
if (y%x==0)

printf("%d is a multiple of %d\n",x,y);

else

printf("%d is not a multiple of %d\n",x,y);

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.

The monthly bonus payment is computed as given below:


Monthly Sales(Rs) Bonus as a percentage

of monthly sales

0-25000 10

25000-50000 12

>=50000 15

Write a program to output the gross monthly remuneration of a salesman.

#include <stdio.h>

#include <stdlib.h>

int main()

int year;

char city,c[1];

float basicsalary,newsalary,monthlysalary,allo1,allo2,allo3;

printf("Enter the basic salary :");

scanf("%f",&basicsalary);

printf("Enter the monthly salary :");

scanf("%f",&monthlysalary);

printf("Enter the years of service :");

scanf("%d",&year);

printf("Enter C if you are from Colombo :");


scanf("%s",&city);

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);

printf("The new salary is %.2f",newsalary);

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;

printf("Enter 10 numbers: ");

for(int i = 0; i < 10; i++)

scanf("%d", &number);

if(number > 0)

positive++;

else if(number < 0)

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("Enter marks of 10 students: " );

for(i = 0; i < 10; i++)


{
printf("The marks of %d student is: ",i+1);
scanf("%f", &marks);
total += marks;
if(marks > max)
max = marks;

if(marks < min)


min = marks;

}
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;

printf("Enter a item price: ");

for(int i = 0; i < 10; i++)


{
scanf("%f", &price);
total += price;

if(price > 200)


num++;
}

printf("The average of a item is %f\n", total/10);


printf("The number of items whose price is greater than 200 is %d", num);

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);

if(basicSalary >= 5000)


num++;

}
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;

printf("Enter employee number: ");


scanf("%d",&employeeNo);

if(employeeNo == -999)

break;

printf("Enter hours worked: ");

scanf("%d", &hours);

total++;

if(hours > 0 && hours < 40)

overTime += (hours * 150);

if(hours >= 40)

overTime += (39 * 150);

overTime += (hours - 39) * 200;

if(overTime > 4000)

totalOT++;

printf("Employee number: %d\n",employeeNo);

printf("Over time payment: %f\n", overTime);

printf("The percentage of people over R.s 4000 of overtime %f%%\n", (float)totalOT/total);

PART B – Switch Statements

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;

while(number <= 100)


{
printf("%d\n", number);
number++;
}
printf("While 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;

printf("Enter 10 marks: ");

for(int i = 0; i <10; i++)


{
scanf("%f", &number);
total += number;
}
printf("total %f\n", total);
avg = (total / 10.0);
printf("Average - %f\n",avg);
if(avg > 50)
printf("Pass");
else
printf("Fail!");
}

Q3) Write a C program to calculate factorial of a user given number.


#include <stdio.h>
#include <stdlib.h>

int main()
{
int number;
int factorial = 1;
printf("Enter number for factorial: ");
scanf("%d", &number);

for(int i = number; i >= 1; i--)


{
factorial *= number;
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);

for(int i = power; i >= 1; i--)


{
result *= base;
}
printf("The result is %d", result);
}
Q7) Write a C program to print first 10 numbers of “Fibonacci Sequence”.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int first = 0,second = 1,n,i,next = 0;
printf("How many fibonacchi numbers do you want: ");
scanf("%d", &n);

for(i = 0 ; i < n; i++)


{
if(i == 0 || i == 1)
printf("%d\n", i);
else
{
next = first + second;
first = second;
second = next;
printf("%d\n", next);
}
}
}

Q8) Write a C program to check whether a given number is an Armstrong Number!


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{

int i,num,n = 0,rem,result = 0,original;

printf("Enter a number: ");


scanf("%d",&num);
original = num;
while(num != 0)
{
num /= 10;
n++;
}
num = original;

for(i = 0; i < n; i ++)


{
rem = num % 10;
rem = round(pow(rem,n));
result += rem;
num /= 10;
}
if(result == original)
printf("This is an Armstrong number");
else
printf("Not an Armstrong number");
return 0;
}
Q9) Write a C program to print all the ASCII values for letters A to Z.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
for(c = 'A'; c <= 'Z'; c++)
{
printf("%c characters ASCII number is %d\n",c,c);
}
}
Q10) Write a program to print this pattern.
*
**
***
****
*****
#include <stdio.h>
#include <stdlib.h>

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++;
}
}

Q11) Write a program to check whether a given number is prime or not.


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int num,i;

printf("Enter a number: ");


scanf("%d",&num);

for(i = 2; i < num /2; i++)


{
if(num % i == 0)
{
printf("This is not a prime");
return 0;
}
}
printf("This is a prime");
return 0;
}
Q12) Write a C program to print all factors of a given integer.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

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;

for(i = 0; i < 10; i++)


{
printf("Enter %d number: ",i+1);
scanf("%d",&numbers[i]);
}
for(i = 0; i < 10; i++)
printf("The number at index %d is %d\n",i,numbers[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;;

for(i = 0; i < 10; i++)


{
printf("Enter %d number: ",i+1);
scanf("%d",&numbers[i]);

if(numbers[i] % 2 == 0)
count++;
}

printf("The number of even numbers in the array are %d\n",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;

static int min,max;

min = 1E14;

max = 1E-14;

for(i = 0; i < 10; i++)

printf("Enter %d number: ",i+1);

scanf("%d",&arr[i]);

sum += arr[i];

if(arr[i] > max)

max = arr[i];
if(arr[i] < min)

min = arr[i];

avg = sum / 10;

printf("The average of the array is %.2f\n",avg);

printf("The minimum number in the array is %d\n",min);

printf("The maximum number in the array is %d\n",max);

printf("The reverse of the array is\n");

for(i = 9; i >= 0; i--)

printf("%d ", 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;

printf("Enter a number of elements for array: ");

scanf("%d",&a);

printf("Enter a number of elements for second array: ");

scanf("%d",&b);

int arr1[a],arr2[b],arr3[a],arr4[a];

for(i = 0; i < a; i++)

printf("Enter %d number for arr1: ",i+1);

scanf("%d",&arr1[i]);

sum += arr1[i];

printf("The scalar sum of arr1 is %d ",sum);

printf("\n");

sum = 0;

for(i = 0; i < b; i++)

printf("Enter %d number for arr2: ",i+1);

scanf("%d",&arr2[i]);

sum += arr2[i];
}

printf("The scalar sum of arr2 is %d ",sum);

printf("\n");

if(a == b)

for(i = 0; i < a; i++)

arr3[i] = arr1[i] + arr2[i];

arr4[i] = arr1[i] * arr2[i];

printf("The vector sum of array is: ");

for(i = 0; i < a; i++)

printf("%d, ",arr3[i]);

printf("\n");

printf("The vector product of array is: ");

for(i = 0; i < a; i++)

printf("%d, ",arr4[i]);

return 0;

}
Practical Number 06
Areas covered Multi Dimensional Arrays

Declare a multi-dimensional array with the size of 3 x 4 (3 rows and 4 columns)


Input the values in to array and display the followings;
a. Display the values in the form of matrix
b. Display the average value
c. Display the highest value

#include <stdio.h>

#include <stdlib.h>

int main()

int arr[3][4],i,j,max;

float avg,sum = 0;

max = arr[0][0];

for(i= 0; i < 3; i++)

for(j = 0; j < 4; j++)

printf("Enter value for arr[%d][%d] = ",i,j);

scanf("%d",&arr[i][j]);
sum += arr[i][j];

if(arr[i][j] > max)

max = arr[i][j];

for(i = 0; i < 3; i++)

printf("|");

for(j = 0; j < 4; j++)

printf("%d\t|",arr[i][j]);

printf("\n");

avg = sum / 12;

printf("The average is %.2f\n",avg);

printf("The max value is %d",max);

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("Enter number of cars: ");


scanf("%d",&n);

float hours[n],sumH = 0,sumP = 0;

for(i = 0; i < n; i++)


{
printf("Number of hours parked by %d car: ",i + 1);
scanf("%f",&hours[i]);
sumH += hours[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.

double hypotenuse(double base, double height)


{

return sqrt(base*base + height*height);


}

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 integerPower(int base,int exponent)

int i,ans = 1;

for(i = 0; i < exponent;i++)

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;

printf("How many do you want to check: ");

scanf("%d",&n);

int num[n];

for(i = 0; i < n; i++)

printf("Enter %d number: ", i+1);

scanf("%d",&num[i]);

for(i = 0; i < n; i++)

printf("Number %d returns %d its a %s number\n",num[i],even(num[i]),even(num[i]) == 1?


"Even":"Odd");

return 0;

int even(int num)

return !(num % 2);


}

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);

printf("The time difference %d ", abs(a - b));


return 0;
}

int timeSec(int hours,int minutes,int seconds)


{
int tinSec = 0;

tinSec += (hours * 3600) + (minutes * 60) + seconds;


return tinSec;

6. Implement the following integer functions:

a) Function celsius returns the Celsius equivalent of a Fahrenheit temperature.

b) Function fahrenheit returns the Fahrenheit equivalent of a Celsius temperature.


c) Use these functions to write a program that prints charts showing the Fahrenheit
equivalents of all Celsius temperatures from 0 to 100 degrees, and the Celsius equivalents of
all Fahrenheit temperatures from 32 to 212 degrees. Print the outputs in a neat tabular format
that minimizes the number of lines of output while remaining readable.

a) float celcius(int farenheit)

return ((farenheit - 32) * 5.0/9);

b) float farenheit(float celcius)

return ( (celcius * (9.0/5)) + 32);

c) int main()

int i;

printf("Celcius \t Farenheit\n");

for(i = 0; i <= 100; i++)

printf("%d \t\t %.2f\n",i,farenheit(i));

}
printf("-----------------------------\n");

printf("Farenheit \t Celcius\n");

for(i = 32; i <= 212; i++)

printf("%d \t\t %.2f\n",i,celcius(i));

return 0;

7. Write a function that displays the smallest of three floating-point numbers

float min(float a, float b, float c)


{
float min = a;

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.

int revNum(int num)

int ans = 0,rem = 0;

while(num != 0)

rem = num % 10;

ans = ans * 10 + rem;

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.

int qualityPoint(float avg)

if(avg >= 90 && avg <= 100)

return 4;

else if(avg >= 80 && avg < 90)


return 3;

else if(avg >= 70 && avg < 80)

return 2;

else if(avg >= 60 && avg < 70)

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>

void arrSumAvg(int arr[] , int size);

int main()

int n;

printf("Enter number of elements: ");

scanf("%d",&n);

int arr[n];

arrSumAvg(arr,n);
return 0;

void arrSumAvg(int arr[], int size)

int i;

float sum = 0,avg;

for(i = 0; i < size; i++)

printf("Enter %d element value: ",i+1);

scanf("%d",&arr[i]);

sum += arr[i];

avg = sum / size;

printf("The sum of elements is %d\n",(int)sum);

printf("The average of elements is %.2f",avg);

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()

int arr1[] = {4,5,6,7};

int arr2[] = {3,4,5,6};

arrSum(arr1,arr2,4);

return 0;

void arrSum(int arr1[], int arr2[],int size)

int i;

for(i = 0; i < size; i++)

printf("arr1[%d] + arr2[%d] = %d\n",i,i,arr1[i] + arr2[i]);

1. How do you write comments in a c program? What is the purpose of comments in a program?

Using // ‘comment’

*To explain a block of code.

2. Which is the function that is essential in a C program?

*main function.
3. What is the purpose of ‘scanf’ ?

*To get input from users.

4. Is ‘standard c’ a case sensitive language?

*Yes.

5. Determine which of the following are valid identifiers. If invalid, explain why.

(a) record1 (e) $tax (h) name-and-address

(b) 1record (f) name (i) name_and_address

(c) file-3 (g) name and address (j) 123 - 45 - 6789

(d) return

*Valid – a,f,i

*Invalid = b – cannot start with a number

c,j,h – cannot contain dashes

g – cannot contain spaces

d – cannot use reserved keywords

e – cannot use symbols

6. State whether each of the following is true or false. If false, explain why.

a) Function printf always begins printing at the beginning of a new line.

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.

e) All variables must be given a type when they’re defined.

f) C considers the variables, number and NuMbEr to be identical.

g) A program that prints three lines of output must contain three printf statements.

a) false – printf doesn’t move to a newline unless theres a \n

b) false – Compiler ignores comments

c) true

d) true

e) true

f) false

g) false

7. What does the following code print?

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 );

c) Scanf( "%d", anInteger );


d) printf( "Remainder of %d divided by %d is\n", x, y, x % y );

e) print( "The sum is %d\n," x + y );

f) Printf( "The value you entered is: %d\n, &value );

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 );

e) printf( "%d = %d", x + y, y + x );

f) z = x + y;

g) scanf( "%d%d", &x, &y );

h) /* printf( "x + y = %d", 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.

a) C operators are evaluated from left to right.

b) The following are all valid variable names: _under_bar_ , m928134 , t5 , j7 , her_sales ,
his_account_total , a , b , c , z , z2 .

c) The statement printf("a = 5;"); is a typical example of an assignment statement.

d) A valid arithmetic expression containing no parentheses is evaluated from left to right.

e) The following are all invalid variable names: 3g , 87 , 67h2 , h22 , 2h

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;

Q2. Write a single C statement to accomplish each of the following:

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.

c) Multiply the variable product by 2 using the = and * operators.

d) Test if the value of the variable count is greater than 10. If it is, print “Count is greater
than 10.”

e) Decrement the variable x by 1, then subtract it from the variable total.

f) Add the variable x to the variable total, then decrement x by 1.

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);

Q3. Write single C statements that

a) Input integer variable x with scanf.

b) Input integer variable y with scanf.

c) Initialize integer variable i to 1.

d) Initialize integer variable power to 1.


e) Multiply variable power by x and assign the result to power.

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.

h) Output integer variable power with printf.

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;

printf("You are dead! \n " );

else

--numNeighbors;

if (numNeighbors >= 3 || numNeighbors == 4)

++numNeighbors;

printf("You are dead! \n " );

} else

--numNeighbors;

2) Describe the output produced by this poorly indented program segment:


int number = 4;

double alpha = -1.0;

if (number > 0)

if (alpha > 0)

printf("Here I am! \n" );

else

printf("No, I’m here! \n");

printf(“No, actually, I’m here! \n");

output: No, I’m here!

No, actually, I’m here!

3) Consider the following if statement, where doesSignificantWork,


makesBreakthrough,
and nobelPrizeCandidate are all boolean variables:

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

----------------------------------- ----------

0 through 100 5.00

More than 100 but not more than 500 8.00


More than 500 but less than 1,000 10.00

1,000 or more 12.00

- 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;
}
}

if(distance > 1000)


cost = 12;
else if(distance > 500)
cost = 10;
else if(distance > 100)
cost = 8;
else
cost = 5;

Switch

Input two numbers and display the outputs of the basic mathematic operations. The output screen
should be displayed as follows;

Enter two numbers ____ ____


1. +
2. –
3. *
4. /

Please enter your Choice ___

Int main()

Int num1, num2, op;

printf(“Enter two numbers”);

scanf(“%d %d”,&num1,&num2);

printf(“1. + \n 2. - \n 3. * \n 4. / \n”);

printf(“Please enter your choise”);

scanf(“%d”,&op);

switch(op)

case 1: printf(“Sum = %d”,num1 + num2);break;


case2: printf(“Differentation = %d”, num1 – num2);break;

case3: printf(“Multiplication = %d”, num1 * num2);break;

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.

Int num = 10,odd = 0,even = 0,input;

While(num > 0)

printf(“Enter a number: “);

scanf(“%d”,&input);

if(input % 2 == 0)

even++;

else

odd++;

num--;

printf(“Odd = %d Even = %d”,odd,even);

int odd = 0,even = 0,input = 0;

While(input != -99)

{
printf(“Enter a number: “);

scanf(“%d”,&input);

if(input % 2 == 0)

even++;

else

odd++;

num--;

printf(“Odd = %d Even = %d”,odd,even);

Do while loop

Rewrite the programs for the above while loop question 1 & 2 using do while loop

int num = 10, even = 0,odd = 0,input ;

Do

Printf(“Enter a number: “);

scanf(“%d”,&input);

if(input % 2 == 0)

even++;

else

odd++;

num--;

while(num > 0);

printf(“Odd = %d Even = %d”,odd,even);


int even = 0,odd = 0,input = 0;

Do

Printf(“Enter a number: “);

scanf(“%d”,&input);

if(input % 2 == 0)

even++;

else

odd++;

num--;

while(input != -99);

printf(“Odd = %d Even = %d”,odd,even);

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;

for(i = 0; I < 10; i++)

printf(“Enter %d number: “,i+1);


scanf(“%d”,&num);

sum += num;

avg = sum / 10;

printf(“The average = %f”,avg);

int i,j;

for(i = 1; i <= 5; i++)

for(j = 0; j < i; j++)

printf("*");

printf("\n");

Write a C program for the followings;

Declare two 3 x 3 square matrices and display the matrix sum.

#include <stdio.h>

#include <stdlib.h>

int main()
{

int arr1[3][3],arr2[3][3],arr3[3][3],i,j;

for(i = 0; i< 3; i++)

for(j = 0; j < 3; j++)

printf("Enter value for arr1[%d][%d] = ",i,j);

scanf("%d",&arr1[i][j]);

printf("Enter value for arr2[%d][%d] = ",i,j);

scanf("%d",&arr2[i][j]);

arr3[i][j] = arr1[i][j] + arr2[i][j];

for(i = 0; i< 3; i++)

{ printf("|");

for(j = 0; j < 3; j++)

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;

printf("Enter number 1: ");

scanf("%f",&a);

printf("Enter number 2: ");

scanf("%f",&b);

printf("The sum of entered values is: %.2f\n",a+b);

printf("The difference of entered values is: %.2f\n",a-b);

5. Write a function that accepts 2 numbers as parameters and calculate and display
sum and difference.

void sumdiff(float a, float b)

printf("The sum of entered values is: %.2f\n",a+b);

printf("The difference of entered values is: %.2f\n",a-b);

6. Write a function that accepts 2 whole numbers as parameters and calculate and
return the product.

int prod(int a, int b)

return a * b;

}
7. Write a function that accepts 2 whole numbers as parameters and calculate and
return the quotient.

int quotient(int a, int b)


{
return a / b;
}

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;

printf("Enter number 1: ");

scanf("%f",&a);

printf("Enter number 2: ");

scanf("%f",&b);

printf("The sum of entered values is: %d\n",a+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.

double val(int a,float b)

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.

a) double hypotenuse(double side1,double side2)


{
return sqrt((side1 * side1) + (side2 * side2));
}
b) int smallest(int x ,int y, Int z)
{
int min = x;

if(min > y)
min = y;

if(min > z)
min = z;

return min;
}

c) void instructions()
{
Printf(“Instructions”);
}

d) float intToFloat(int a)
{
return a;

Potrebbero piacerti anche