0% found this document useful (0 votes)
35 views22 pages

C++ Unit 1-Qb With Ans

Uploaded by

karen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views22 pages

C++ Unit 1-Qb With Ans

Uploaded by

karen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

HINDUSTHAN COLLEGE OF ENGINEERING AND TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY


18IT2202/ Programming in C & C++

UNIT I BASICS OF C PROGRAMMING


Fundamentals of C Programming - Structure of C program – Constants-Variables- Data types –
Expressions using operators in C- Managing Input/output operations-Branching & Looping –
Arrays-One dimensional & Two dimensional Arrays.

PART A

1. Define programming paradigm.


Programming paradigm is a style or way of programming. The are
procedural, functional, object-oriented, logic programming.
Some of the programming languages are
 Fortran
 Cobol
 Basic
 Pascal
 C

2. Give two examples for assignment statements.


Syntax for assignment :variable = expression / value ; Example :
x=100;
y= a+b;

3. Distinguish between character and string.

No. Character String


i. It is a single character. It is a sequence of characters.
ii. It is enclosed by single quotes. It is enclosed by double quotes.
iii. Example : ‘C’ Example : “Computer”

4. What are keywords? Give an example


 Keywords are reserved words, they have standard and predefined meaning.
 Keywords cannot be used as normal identifiers.
 Example : auto, break, char, continue, else, if, switch, struct, union.

1
5. What do you mean by variables in ‘C’?
A variable is an identifier that is used to represent some specified type of
information.
Syntax :

data_typevariable_name;
Example: intmarks;

6. Identify the use of ternary or conditional operator.


 ?: is known as conditional operator.It evaluates the first expression if
the condition is true otherwise the second expression is evaluated.
 Syntax : condition ? exp1 : exp2;

7. What is a compilation process?


Compiler converts source code into executable code. It includes
 Pre-processor
 Compilation
 Assembly
 Linking
8. Differentiate between an expression and a statement in C.

No. Expression Statements


i. Expression consists of It is defined as a set of declaration or
operators and operands. sequence of actions.
ii. Example: a=29; Example: Assignment statement
b=a+77; Mark=73;

9. What is the output of the programs given below?


#include
<stdio.h>ma
in( )
{
int a = 20, b = 10, c = 15,
d=5; int e;
e = (a + b) * c / d;
printf("Value of (a + b) * c / d is : %d\n", e );
}
OUTPUT :
Value of (a + b) * c / d is : 90

10. Generalize the types of I/O statements available in‘C’.


Unformatted Input / Output statements
 Input : getc(), getchar(), gets(), getche(),getch()
 Output :putc(), putchar(),puts().
Unformatted Input / Output statements
 Input : scanf(),fscanf()
 Output :printf(),fprintf()
11. Discover the meaning of Cpre-processor
1. The preprocessor contains any operations in the processing language, it
will be transformedfirst.
2. The preprocessing language consistsof
 Inclusion of headerfile
 Macroexpansion
 Conditional compilation
 Linecontrol
 Diagnostics

12. Invent the difference between ++a anda++.


 ++a is known as pre increment where the value is incremented by one
and then the operation is done.
 a++ is known as post increment where the operation is done first and
then the value is incremented byone.

13. Differentiate switch( ) and nested-ifstatement

No. Switch( ) Nested if


i. The switch( ) can test only The if can evaluate relational or
constant values. logical expressions.

ii. In switch( ) case nested if can be In nested if statements, switch( ) case


used. can be used

14. Summarize the various types of Coperators.


 Arithmaticoperators
 Relationaloperators
 Logical operators
 Increment or decrementoperators
 Conditional or Ternaryoperators
 Bitwiseoperators
 Special operators (sizeof, & and * , . and-->)

15. Recommend the suitable example for infinite loop usingwhile.


#include<st
dio.h> void
main()
{
inti = 1;
while( i<10 )
{
printf(“%d\n”,i);
}
getch( );
}

Here we are not updating the value of i. so after each iteration value of
i remains same. As a result, the condition (i<10) will always true so it will
print infinity loop.

16. What is a globalvariable?


Global variables are declared at the beginning of the program and it can be
used inside any part of the program.

a=10;
main( )
{
print(“Value of a : %d”,a);
}

17. Differentiate break and continuestatement.

No Break Continue
i. Takes the control to outside of Takes control to the beginning of the
the loop. loop.

ii. It used in both looping and It is used only in looping


switch statements. statements.

18. List out the features ofArrays.


 An array is used to represent a collection of elements of same datatype.
 The elements in an array can be accessed by usin the baseaddress.
 The elements are stored in continuous memory locations,
 The starting memory location is known as the array name and it is
known as thebase address ( index ) of thearray.

19. Define a float array of size 5 and assign 5 values toit.


main( )
{
float a[5] = {26.9, 32.4, 84.2, 20.0, 78.1};
}

20. Identify the main elements of an arraydeclaration.


 Arrays are declared like variable declaration but the array
declarationhas size of thearray.

Syntax :data_typearray_name[size]; [OR]


data_typearray_name[array_size]={list_of_values};

Example for array declaration :

int marks[6];

21. Point out an example code to express two dimensionalarray.


 A two dimensional array is created by specifying its row and columnsize.

Examples :int matrix[2][2];


inta[3][2];
22. How to create a two dimensionalarray?
Two dimensional arrays are stored in a row-column matrix, where the left
index indicates the row and right matrix indicates the column.

Syntax :data_typearray_name[row_size][column_size];

Example : int mat[3][3];

23. What are the different ways of initializingarray?


 Values can be assigned to an array by normal declaration otherwise
they hold garbagevalues.
 Arrays can be initialized in following two ways:
i. At compiletime
ii. At Runtime

24. What is the use of ‘\0’ and‘%s’?


 ‘\0’ is the escape sequence for null character it is automatically
added at the end of thestring.
 ‘%s’ is a format specifier for string. It is used in scanf( ) and
printf( ) functions to get the string input or to print stringoutput.
25. Define Multi-dimensional array.
 Multi-dimensioned arrays have two or more index values which
specify the element in the array.
Declaration:
int m1[10][10];
static int m2[2][2] = { {0,1}, {2,3} };

PART B QUESTIONS(14 marks)


1. i).Describe the structure of a C Program with example.(Pg.No:11-12)
ii).List the different data types available in C. .(Pg.No:28-31)
2. i).What are constants? Explain the various types of constants in C. (Pg.No:24-27)
ii).Write the operations of compilation process .(Pg.No:13-16)
3. Explain the different types of operators available in C. .(Pg.No:49-58)
4. Describe the various looping statements used in C with suitable examples.(Pg.No:145-
152)
5. Explain about various decision making statements available in C with
illustrative programs. .(Pg.No:107-130)
6. i).Write a C program to print the Fibonacci series of a given number. (Pg.No:154)
ii).Write a C program to solve the quadratic equation and to find a Factorial of a given
number.

Quadratic Equation:

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

int main(){
float a,b,c;
float d,root1,root2;

printf("Enter a, b and c of quadratic equation: ");


scanf("%f%f%f",&a,&b,&c);

d = b * b - 4 * a * c;
if(d < 0){
printf("Roots are complex number.\n");

printf("Roots of quadratic equation are: ");


printf("%.3f%+.3fi",-b/(2*a),sqrt(-d)/(2*a));
printf(", %.3f%+.3fi",-b/(2*a),-sqrt(-d)/(2*a));

return 0;
}
else if(d==0){
printf("Both roots are equal.\n");

root1 = -b /(2* a);


printf("Root of quadratic equation is: %.3f ",root1);

return 0;
}
else{
printf("Roots are real numbers.\n");

root1 = ( -b + sqrt(d)) / (2* a);


root2 = ( -b - sqrt(d)) / (2* a);
printf("Roots of quadratic equation are: %.3f , %.3f",root1,root2);
}

return 0;
}

OUTPUT:
Enter a, b and c of quadratic equation: 2 4 1
Roots are real numbers.
Roots of quadratic equation are: -0.293, -1.707

FACTORIAL:

#include <stdio.h>

int main()
{
int c, n, fact = 1;

printf("Enter a number to calculate its factorial\n");


scanf("%d", &n);

for (c = 1; c <= n; c++)


fact = fact * c;

printf("Factorial of %d = %d\n", n, fact);

return 0;
}

OUTPUT:
Enter a number to calculate its factorial: 6
Factorial of 6: 720

7. i).Write a C program to check whether a given number is prime number or not. .


(Pg.No:154)
ii).Write a C program to find mean, median and mode.

#include<stdio.h>
main()
{
int i,j,a[20]={0},sum=0,n,t,b[20]={0},k=0,c=1,max=0,mode;
float x=0.0,y=0.0;
printf("\nEnter the limit\n");
scanf("%d",&n);
printf("Enter the set of numbers\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
x=(float)sum/(float)n;
printf("Mean\t= %f",x);

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
if(n%2==0)
y=(float)(a[n/2]+a[(n-1)/2])/2;
else
y=a[(n-1)/2];
printf("\nMedian\t= %f",y);

for(i=0;i<n-1;i++)
{
mode=0;
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
mode++;
}
}
if((mode>max)&&(mode!=0))
{
k=0;
max=mode;
b[k]=a[i];
k++;
}
else if(mode==max)
{
b[k]=a[i];
k++;
}
}
for(i=0;i<n;i++)
{
if(a[i]==b[i])
c++;
}
if(c==n)
printf("\nThere is no mode");
else
{
printf("\nMode\t= ");
for(i=0;i<k;i++)
printf("%d ",b[i]);
}
}
8. What is an array? Discuss how to initialize a one dimensional and two dimensional
arrays with suitable example? .(Pg.No:183-202)

Part C
1.i). Write a C Program to remove the duplicate numbers present in an array & display the
remaining numbers.
#include<stdio.h>
int main() {
int arr[20], i, j, k, size;

printf("\nEnter array size : ");


scanf("%d", &size);

printf("\nAccept Numbers : ");


for (i = 0; i < size; i++)
scanf("%d", &arr[i]);

printf("\nArray with Unique list : ");


for (i = 0; i < size; i++) {
for (j = i + 1; j < size;) {
if (arr[j] == arr[i]) {
for (k = j; k < size; k++) {
arr[k] = arr[k + 1];
}
size--;
} else
j++;
}
}

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


printf("%d ", arr[i]);
}

return (0);
}

output:

Enter array size : 5


Accept Numbers : 1 3 4 5 3
Array with Unique list : 1 3 4 5

ii). Write a C program to multiply two 3*3 matrices.

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k;
printf("Enter first matrix element (3*3) : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("Enter second matrix element (3*3) : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&mat2[i][j]);
}
}
printf("Multiplying two matrices...\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum=0;
for(k=0; k<3; k++)
{
sum = sum + mat1[i][k] * mat2[k][j];
}
mat3[i][j] = sum;
}
}
printf("\nMultiplication of two Matrices : \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%d ", mat3[i][j]);
}
printf("\n");
}
getch();
}

Output:

2. i)State the need for user define functions. Explain call by value & call by reference
methods using examples.
 C allow programmers to define functions. Such functions created by the user are
called user-defined functions.
Need of User defined functions:
 Every program must have a main function.
 It is possible to code any program utilizing only main function,it leads to a number
of problems.
 The program may become too large and complex and as a result the task of
debugging ,testing and maintaining becomes difficult.
 if a program is divided into functional part ,then each part may be independently
coded and later combined into single unit.
 these subprograms called “functions” are much easier to understand,debug & test.
 there are times when some types of operation or calculation is repeated at many
points throughout a program.
 in such,situations,we may repeat the program statements whenever they are
needed.
 another approach is to edsign a function that can be called and used whenever
required.
 this saves both time & space.

Call by value

In call by value, original value can not be changed or modified. In call by value, when you
passed value to the function it is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function
only but it not change the value of variable inside the caller method such as main().

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

void swap(int a, int b)


{
int temp;
temp=a;
a=b;
b=temp;
}

void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}

OUTPUT:

Value of a: 200
Value of b: 100

Call by reference

In call by reference, original value is changed or modified because we pass reference


(address). Here, address of the value is passed in the function, so actual and formal arguments
shares the same address space. Hence, any value changed inside the function, is reflected
inside as well as outside the function.

#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}

OUTPUT:

Value of a: 200
Value of b: 100
3.i).Write a C program to enter marks of five subjects and calculate total, average and
percentage.
#include <stdio.h>

void main()
{
float sub1, sub2, sub3, sub4, sub5;
float tot, avg, per;

printf("Enter marks of 5 subjects\n");


scanf("%f%f%f%f%f", &sub1, &sub2, &sub3, &sub4, &sub5);

tot = sub1 + sub2 + sub3 + sub4 + sub5;


avg = tot / 5;
per = (tot / 500.0) * 100;

printf("Total marks = %.2f\n", tot);


printf("Average marks = %.2f\n", avg);
printf("Percentage = %.2f", per);
}
OUTPUT:
Enter marks of 5 subjects:
75 92 66 77 85
Total marks:395.00
Average Marks: 79.00
percentage: 79.00

ii). write a C program to read a character from keyboard and print it in reverse case.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[50],b[50];
int i,j,n,totword=1,totchar=0,totline=1;
clrscr();
printf("\n Please Give The STRING : ");
scanf("%s",a);
for(j=strlen(a)-1;j>=0;j--)
printf("%c",a[j]);
getch();
}

OUTPUT:
Please Give The STRING : SYNTAX
XATNYS

4.i). Write a C program to find power of any number x ^ y. .(Pg.No:147)


ii). Write algorithm and a C program using unions, to prepare the employee pay roll of a
company

#include<stdio.h>
#include<conio.h>
UNION emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
} e[10] ;
void main()
{
int i, n ;
clrscr() ;
printf("Enter the number of employees : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the employee number : ") ;
scanf("%d", &e[i].empno) ;
printf("\nEnter the name : ") ;
scanf("%s", e[i].name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", &e[i].bpay, &e[i].allow, &e[i].ded) ;
e[i].npay = e[i].bpay + e[i].allow - e[i].ded ;
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", e[i].empno,
e[i].name, e[i].bpay, e[i].allow, e[i].ded, e[i].npay) ;
}
getch() ;
}

Output:

Enter the number of employees : 2


Enter the employee number : 101
Enter the name : Arun
Enter the basic pay, allowances & deductions : 5000 1000 250
Enter the employee number : 102
Enter the name : Babu
Enter the basic pay, allowances & deductions : 7000 1500 750
Emp.No. Name Bpay Allow Ded Npay
101 Arun 5000 1000 250 5750
102 Babu 7000 1500 750 7750
5).Write a C program to convert days into years, weeks and days.
logic:
 Input days from user. Store it in some variable say days.
 Compute total years using the above conversion table. Which is years = days / 365.
 Compute total weeks using the above conversion table. Which is weeks = (days - (year *
365)) / 7.
 Compute remaining days using days = days - ((years * 365) + (weeks * 7)).
 Finally print all resultant values years, weeks and days
#include <stdio.h>

int main()
{
int days, years, weeks;

/* Input total number of days from user */


printf("Enter days: ");
scanf("%d", &days);

/* Conversion */
years = (days / 365); // Ignoring leap year
weeks = (days % 365) / 7;
days = days - ((years * 365) + (weeks * 7));

/* Print all resultant values */


printf("YEARS: %d\n", years);
printf("WEEKS: %d\n", weeks);
printf("DAYS: %d", days);

return 0;
}
OUTPUT:
ENTER DAYS: 373
YEARS:1
WEEKS: 1
DAYS:1

ii). What are the advantages of using default arguments? Explain with example
program.
Advantages:
 Time complexity will be reduced.
 Efficiency of program execution is fast.
 Reduces complex coding.
#include <iostream>
using namespace std;
//Default argument must be trailer.
int sum(int x, int y=10, int z=20)
{
return (x+y+z);
}

int main()
{
cout << "Sum is : " << sum(5) << endl;
cout << "Sum is : " << sum(5,15) << endl;
cout << "Sum is : " << sum(5,15,25) << endl;
return 0;
}
Output:
Sum is :35
Sum is :40
Sum is :45

You might also like