[go: up one dir, main page]

0% found this document useful (0 votes)
296 views42 pages

Question Solution of CIT-111

The document provides information about a programming course including: 1. Definitions of a program and programming language and differences between a compiler, assembler, and interpreter with examples. 2. A C code sample to calculate the sum of digits of a number. 3. Errors in code samples and their corrections. 4. Questions about C programming concepts like loops, data types, and output of code snippets.
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)
296 views42 pages

Question Solution of CIT-111

The document provides information about a programming course including: 1. Definitions of a program and programming language and differences between a compiler, assembler, and interpreter with examples. 2. A C code sample to calculate the sum of digits of a number. 3. Errors in code samples and their corrections. 4. Questions about C programming concepts like loops, data types, and output of code snippets.
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/ 42

Course Code: CIT-111

Course Title: Programming Language

1. a) Define program and programming language.


Write the difference between compiler, assembler
and interpreter with example.

Answer:
Program: Program is the process of creating a set of
instructions that tell a computer how to perform a
task.
Programming can be done using a variety of
computer programming languages, such as
JavaScript, Python, and C++.

Programming Language: A programming language is


any set of rules that coverts strings or graphical
program elements in the case of visual programming
languages, to various kinds of machine code output.
Difference between compiler, assembler and
interpreter:

Compiler Interpreter Assembler


Software that Software that Software that
converts translates a converts
programs high level programs
written in a high language written in a
level language program into assembly
into machine machine language into
language. language. machine
language.
Converts the Converts the Converts
whole high level whole high assembly
language level language language
program to program to program to
machine machine machine
language at a language line language .
time. by line.
Used by C, C++. Used by Ruby, Used by
Perl, Python, assembly
PHP. language.

b). Write a C code of sum of the digits of a number.


(if the input 4050 then output will be 9)
Answer:
C program to find sum of digits of a number-

#include<stdio.h>
int main()
{
int n, t, sum=0, r;

printf(“Enter a number\n”);
scanf(“%d”,&n);

t = n;

while (t != 0)
{
r = t%10;
sum = sum+r;
t = t/10;
}
Printf(“Sum of digits on %d = %d\n” , n, sum);

return 0;
}
c). (i) Find the errors and correct the error.

1. #include<stdio.h>
2. {
3. int main(void)
4. while(.)
5. {
6. printf(“hello”);
7. }
8. return 0;
9. }

Answer:
1. #include<stdio.h>
2. int main(void)
3. {
4. printf(“hello”);
5. }
6. return 0;
(ii). How many times CSE PSTU will print:

1. #include<stdio.h>
2. int main()
3. {
4. int x;
5. for(x=-1; x<=10; x++)
6. {
7. if(x<5)
8. continue;
9. else
10. break;
11. printf(“CSE PSTU”);
12. }
13. return 0; }

Answer:
0 times CSE PSTU will print.

d). Fill in the blanks in each of the following


statements.
a) In counter-controlled iteration, a(n)____ is used to count the
number of times a group of instructions should be repeated.
Answer: control variable or counter.
b) The______ statement, when executed in an iteration
statement, causes the next iteration of the loop to be
performed immediately.
Answer: continue
c) The_____ statement, when executed in an iteration
statement or a switch, causes an immediate exit from the
statement.
Answer: break
d) The is_____ used to test a particular variable or expression
for each of the constant integral values it may assume.
Answer: switch selection statement

e).Write a C program to count the total number of vowel or


consonant in a word.

Answer:
A C program to count the total number of vowel or
consonant in a word-

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define str_size 100 //Declare the maximum size
of the string

void main()
{
char str[str_size];
int i, len, vowel, cons;
printf("\n\nCount total number of vowel
or consonant :\n");
printf("---------------------------------------
-------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);

vowel = 0;
cons = 0;
len = strlen(str);

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


{

if(str[i] =='a' || str[i]=='e' ||


str[i]=='i' || str[i]=='o' || str[i]=='u' ||
str[i]=='A' || str[i]=='E' || str[i]=='I' ||
str[i]=='O' || str[i]=='U')
{
vowel++;
}
else if((str[i]>='a' && str[i]<='z') ||
(str[i]>='A' && str[i]<='Z'))
{
cons++;
}
}
printf("\nThe total number of vowel in the
string is : %d\n", vowel);
printf("The total number of consonant in
the string is : %d\n\n", cons);
}

2.Define expression and statement. Distinguish


them with example.
Answer:
Expression:
An expression represents a single data item--usually a number.
The expression may consist of a single entity, such as a constant
or variable, or it may consist of some combination of such
entities, interconnected by one or more operators. Expressions
can also represent logical conditions which are either true or
false. However, in C, the conditions true and false are
represented by the integer values 1 and 0, respectively. Several
simple expressions are given below:
a+b
x=y
t=u+v
x <= y
++j

Statement:

A statement causes the computer to carry out some definite


action.
There are three different classes of statements in C: expression
statements, compound statements, and control statements.

b) Write a program for reversing an odd number


where user will enter the input from the keyboard.

Answer:
A program for reversing an odd number where
user will enter the input from the keyboard-

#include<stdio.h>
int main()
{
int n, reverse=0, remainder;
printf(“Enter an odd number: ”);
scanf(“%d” ,&n);
while(n != 0)
{
remainder = n%10;
reverse = reverse*10 + remainder;
n /= 10;
}
printf(“Reversed number = %d” , reverse);

return 0;
}

C) (i). Find the error(s) if any and corrected the


code

1. #include<stdio.h>
2. void main()
3. {
4. int x = 10;
5. int y = 15;
6. printf(“%d”,(x,y)) }

Answer:
1. #include<stdio.h>
2. void main()
3. {
4. int x = 10;
5. int y = 15;
6. printf(“%d,%d”,x,y) }

(ii) Find the output out of the following code-

#include<stdio.h>
int main()
{
int a = 10, b = 25;
a = b-- - a--;
b = --b - --a;
printf(“%d %d\n”,a,b);
}

Answer:
a = 25 – 10 = 15
b = 23 – 14 = 9

e)(i) Find the output of the following code-

1. #include<stdio.h>
2. int main()
3. {
4. int m = -10, n=20;
5. n = (m<0)? 0:1;
6. printf(“%d %d”, m, n);
7. }

Answer:
The output of the following code-
-10 0

(ii) What’s wrong with the following while


iteration statement (assume z has value 100),
which is supposed to calculate the sum of the
integers from 100 down to 1?

while(z>=0) {
sum += z;

Answer:
while (z >= 0)
{
sum += z;
z--;
}
Explanation: Since the while structure is controlled by the
variable z being greater than or equal to 0, z must be
decremented in order for the loop continuation
condition to become false at some point. For this reason,
we added z-- inside the body of the while loop. Note that
the code is now blocked together with curly braces,
because there is more than one statement in the body of
the while loop.

3.(a) Classify Data Types with Example.


Answer:
A data type, in programming, is a classification that
specifies which type of value a variable has and
what type of mathematical, relational or logical
operations can be applied to it without causing an
error. A string, for example, is a data type that is
used to classify text and an integer is a data type
used to classify whole numbers.
Data Type Used for Example
String Alphanumeric Hello world, Alice
characters
Integer Whole numbers 7, 12, 999
Float Number with a 3.15, 9.06, 00.13
decimal point
Character Encoding text 97 ( in ASCII, 97 is
numerically a lower case ‘a’)
Boolean Representing TRUE, FALSE
logical values

b).(i). Find the output of the following code:


1. #include<stdio.h>
2. int main()
3. {
4. int m = 100, n=0;
5. while(n==0)
6. {
7. if(m<10) break;
8. M = m-10;
9. }
10. return 0;
11. }
Answer:
No output will show the following code.

(ii). Find the output of the following code-

1. #include<stdio.h>
2. int main() {
3. int check = 2;
4. switch(check) {
5. case 1:
6. printf(“Compter”);
7. case 2:
8. printf(“Science”);
9. case 3:
10. printf(“Engineering”);
11. default:
12. printf(“PSTU”);
13. }
14. return 0;
15. }

Answer:
The output of the following code-
ScienceEngineeringPSTU

C). Explain the difference among For loop, While loop,


Do while loop with an example.
Answer:
The diference among For loop, While loop, Do while
loop-
For loop While loop Do while loop
It is known as It is known as It is known as exit
entry controlled entry controlled controlled loop.
loop. loop
If the condition is If the condition is Even if the
not true first time not true first time
condition is not
than control will than control will
true for the first
never enter in a never enter in atime the control
loop. loop. will enter in a
loop.
There is no There is no There is
semicolon; after semicolon; after semicolon; after
the syntax of the the syntax of the the syntax of the
for loop. while loop. do while loop.
Initialization and Initialization and Initialization and
updating is the updating is not updating is not
part of the the part of the the part of the
syntsax. syntsax syntsax
Syntax: Syntax: Syntax:
for(initialization; while(condition) Do
condition;
{ {
updating)
Statements; Statements;
{
} }
Statements;
while(condition);
}

d) Calculate grade using switch statement in C. Grade


like A+>=80, A>=70, B>60, C>50, D>=40, F<39
Answer:
#include<stdio.h>
int main()
{
int score;

printf("Enter score( 0-100 ): ");


scanf("%d", &score);

switch( score / 10 )
{

case 10:
case 9:
printf("Grade: A+");
break;

case 8:
printf("Grade: A");
break;

case 7:
printf("Grade: B");
break;
case 6:
printf("Grade: C");
break;

case 5:
printf("Grade: D");
break;

default:
printf("Grade: F");
break;

return 0;
}

4.a) Define function briefly, describe the function call


and return procedure using an example of muiltifuntion
program.
Answer:
Function:
A function is a group of statements that together perform a task.
Every C program has at least one function, which is main(), and
all the most trivial programs can define additional functions.
The function call and return procedure:

A function can be called by simply using the function name


followed by a list of actual parameters (or arguments), if any,
enclosed in parentheses. Example:

main()

int y;

y = mul (10,5); /* Function Call */

printf(“%d\n”, y);

When the compiler encounters a function call, the control is


transferred to the function mul(). This function is then executed
line as described and a value is returned when a return
statement is encountered. This value is assigned to y. This is
illustrated as follows:

main()
{

int y;

_____ y = mul (10,5); /* Function Call */ ________

| printf(“%d\n”, y); |

| } |

| int mul (int x, int y) ___________________|

| {

| int p; /* local variable */

| p = x*y; /* x = 10 , y = 5*/

| ______ return (p);

b). Write a program to print prime numbers between


two integers using function.
Answer:
A program to print prime numbers between two integes
using function-
#include <stdio.h>
int main ()

int num1, num2, i, j, flag;

printf("Enter two numbers: ");

scanf("%d %d", &num1, &num2);

printf("Prime numbers between %d and %d


are:\n", num1, num2);

// Displaying prime number between num1 and


num2

for (i = num1 + 1; i < num2; ++i)

flag = 0; //flag is set to 0

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

if (i % j == 0)
{

flag = 1;

break;

if (flag == 0) //if flag == 0, then


display i

printf("%d\t", i);

return 0;
}

c). Define recursion. Write down the advantages and


disadvantages of recursion. Describe the scope,
visibility, and lifetime of variables.
Answer:
Recursion: When a function calls a copy of itself then the
process is known as Recursion. To put it short, when a
function calls itself then this technique is known as
Recursion and function is known as a recursive function.
The advantages of Recursion:
 For a recursive function, you only need to define the
base case and recursive case, so the code is simpler
and shorter than an iterative code.
 Some problems are inherently recursive, such as

Graph and Tree Traversal.


The disadvantages of Recursion:
 A recursive program has greater space
requirements than an iterative program as each
function call will remain in the stack until the base
case is reached.
 It also has greater time requirements because
each time the function is called, the stack grows and
the final answer is returned when the stack is popped
completely.

The scope, visibility and lifetime of variables:

 Scope is defined as the availability of a variable


inside a program, scope is basically the region of
code in which a variable is available to use.
There are four types of scope:
o file scope,

o block scope,
o function scope and
o prototype scope.

 Visibility of a variable is defined as if a variable


is accessible or not inside a particular region of
code or the whole program.
 Lifetime of a variable is the time for which the
variable is taking up a valid space in the system's
memory, it is of three types:
o static lifetime,

o automatic lifetime and

o dynamic lifetime.

d). Write a program to find the sum of N natural


numbers using recursion. Use N=5 as your test data and
demonstrate the calls and returns in details.
Answer:
A program to find the sum of N natural numbers using
recursion-
#include<stdio.h>
int addNumbers (int N);
int main() {
int N;
printf(“Enter a positive integer: ”);
scanf(“%d” , &N);
printf(“Sum = %d”, addNumbers (N));
return 0;
}
int addNumbers (int n) {
if (n != 0)
return n + addNumbers (n-1);
else
return n;
}

5.(a). How pointer is initialized? Is there any arithmetic


operation permitted on pointers? Describe with
examples.
Answer:
Initialization of Pointers:
The initializer is an = (equal sign) followed by the expression
that represents the address that the pointer is to contain. The
following example defines the variables time and speed as
having type double and amount as having type pointer to
a double. The pointer amount is initialized to point to total:
double time, speed, *amount = &total;

The compiler converts an unsubscripted array name to a pointer


to the first element in the array. We can assign the address of
the first element of an array to a pointer by specifying the name
of the array. The following two sets of definitions are
equivalent. Both define the pointer student and
initialize student to the address of the first element in section:
int section[80];
int *section = section;
A pointer can also be initialized to null with any integer constant
expression that evaluates to 0. Such a pointer is a null pointer
and it does not point to any object. For more information about
the null pointer.
The following examples define pointers with null pointer values:
char *a = 0;
char *b = NULL;
Pointers variables are also known as address data types
because they are used to store the address of another
variable. The address is the memory location that is
assigned to the variable. It doesn’t store any value.
Hence, there are only a few operations that are allowed
to perform on pointers in C language. The operations are
slightly different from the ones that we generally use for
mathematical calculations. The operations are:
1. Increment/Decrement of a Pointer
2. Addition of integer to a Pointer
3. Subtraction of integer to a Pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers of the same type

(b). Write a program to pass pointers to functions.


Answer:
A program to pass pointers to functions-
#include <stdio.h>
void salaryhike(int *var, int b)
{
*var = *var+b;
}
int main()
{
int salary=0, bonus=0;
printf("Enter the employee current
salary:");
scanf("%d", &salary);
printf("Enter bonus:");
scanf("%d", &bonus);
salaryhike(&salary, bonus);
printf("Final salary: %d", salary);
return 0;
}

c). What is call by value and call by reference? Describe


with examples. Write down the common mistakes
when working with pointers.
Answer:
Call by value: A copy of the variable is passed to the
function.
In the example below, we are simply swapping two
numbers. Although the swapping took place inside
the function, as you can see from the output, the
output says the opposite. This happens because we
have sent a copy of the variable instead of its exact
address.
#include<stdio.h>
void swap(int n1, int n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}
int main() {
int x = 20;
int y = 68;
printf(“The numbers before swapping n1 and
n2 %d %d \n” , x, y);
swap(x, y);
printf(“The numbers after swapping n1 and n2
%d %d \n” , x, y);
return 0;
}
Call by reference: An address of the variable is
passed to the function.
In this example, the output shows the correct result.
This happens because we have sent the exact address
of the variable.
#include<stdio.h>
void swap(int *n1, int *n2)
{
int temp = *n1;
*n1 = *n2;
*n2 = temp;
}
int main() {
int x = 20;
int y = 68;
printf(“The numbers before swapping n1 and
n2 %d %d \n” , x, y);
swap(x, y);
printf(“The numbers after swapping n1 and n2
%d %d \n” , x, y);
return 0;
}

The common mistakes when working with pointers:


An invalid pointer reference occurs when a pointer’s
value is referenced even though the pointer doesn’t
point to valid block. One way to create this mistake
is to say p=q; when q is uninitialized. The pointer p
will then become uninitialized as well, and any
reference to *p is an invalid pointer reference.

d). Write a function using pointers to exchange the


values stored in two locations in the memory.
Answer:
The program shows how to contents of two locations
can be exchanged using their address locations. The
function exchange() receives the addresses of the
variables x and y and exchanges their contents.
void exchange (int *, int *); /*prototype*/
main()
{
int x, y;
x = 100;
y = 200;
printf(“Before exchange : x = %d y = %d\n\n” , x, y);
exchange(&x, &y);
printf(“After exchange : x = %d y = %d\n\n” , x, y);
}
exchange (int *a , int *b)
{
int t;
t = *a; /* Assign the value at address a to t */
*a = *b; /* put b into a */
*b = t; /* put t into b */
}
Output:
Before exchange: x = 100 y = 200
After exchange : x = 200 y = 100

6.a). What is file? Why file is necessary? Explain how


the file open and file close functions handled.
Answer:
File: A file represents a sequence of bytes, regardless of
it being a text file or a binary file. C programming
language provides access on high level functions as well
as low level (OS level) calls to handle file on your storage
devices.
Why file is necessary?
• When a program is terminated, the entire data is lost.
Storing in a file will preserve your data even if the
program terminates.
• If you have to enter a large number of data, it will take
a lot of time to enter them all. However, if you have a file
containing all the data, you can easily access the
contents of the file using a few commands in C.
• You can easily move your data from one computer to
another without any changes.
Process of the file open and file close functions:
Opening a file is performed using the fopen() function
defined in the stdio.h header file.
The syntax for opening a file in standard I/O is:
ptr = fopen(“fileopen”, “mode”);
For example,
fopen(“E:\\cprogram\\newprogram.txt”, “w”);
fopen(“E:\\cprogram\\oldprogram.bin”,”rb”);
The file (both text and binary) should be closed after
reading/writing.
Closing a file is performed using the fclose() function.

Fclose(ptr);

Here, fptr is a file pointer associated with the file to be


closed.
b). A file named NUMB contains a series of integer
numbers. Write a program to read these numbers and
then write all ‘odd’ numbers to a file to be called ODD
and all ‘even’ numbers to a file to be called EVEN.
Answer:
The program is shown below uses three files
simultaneously and therefore, we need to define three
file pointers f1, f2, f3.
First, the file NUMB containing integer values is created.
The integer values are read from the terminal and are
written to the file NUMB with the help of the statement
Putw(number, f1)
When we type -1, the reading is terminated and the file
is closed. The next step is to open all the three files,
NUMB for reading, ODD and EVEN for writing. The
contents of NUMB file are read, integer by integer, by the
function getw(f1) and written to ODD or EVEN file after
an appropriate test. The statement
(number = getw(f1)! = EOF
reads a value, assigns the same to number, and then
tests for the end-of- file mark.
Finally, the program displays the contents of ODD and
EVEN files. It is important to note that the files ODD and
EVEN opened for writing are closed before they are
reopened for reading.

#include<stdio.h>
main()
{
FILE *f1, *f2, *f3;
int number, i;
printf(“Contents Of NUMB file\n\n”);
f1 = fopen(“NUBM” , “w”; /*Create NUMB file */
for(i=1; i<=30; i++)
{
scanf(“%d” , &number);
if(number == -1) break;
putw(number, f1);
}
fclose(f1);
f1 = fopen(“NUMB” , “r”);
f2 = fopen(“NUMB” , “w”);
f3 = fopen(“NUBM”, “w”);

/* Read from NUMB file */


while ((number = getw(f1)) ! = EOF)
{
if (number %2 ==0)
putw(number, f3); /* Write to EVEN file */
else
putw(number, f2); /* Write to ODD file */
}
fclose(f1);
fclose(f2);
fclose(f3);
f2 = fopen(“ODD”, “r”);
f3 = fopen(“EVEN”, “r”);
printf(“\n\nContents of EVEN file\n\n”);
while(number = getw(f2) ! = EOF)
printf(“%4d”, number);

printf(“\n\nContests of EVEN file\n\n);


while((number = getw(f3)) ! = EOF)
printf(“%4d”, number);
fclose(f2);
fclose(f3);
}

Output:
Contents of NUMB file
111 222 333 444 555 666 777 888 999 000 121 232 343
454 565 -1
Contents of ODD file
111 333 555 777 999 121 343 565
Contents of EVEN file
222 444 666 888 0 232 454

c). How does structure differ from union? Describe with


memory representation. Show the different ways of
assigning values to structure members.
Answer:
Both structure and union are user-defined types in C
programming that hold multiple members of different
data types. Structures are used when we need to store
distinct values for all the members in a unique memory
location, while unions help memory efficiently.
The different ways of assigning values to structure
members-
1. Using Dot(.) operator var_name. member_name
= value;
2. All members assigned in one statement struct
struct_name var_name = {value for member1,
value for member2…. So non for all the
members}
3. Designed initializers

d). Define a structure called complex consisting of two


floating-point numbers x and y and declare a variable p
of type complex. Assign initial values 0.0 and 1.1 to the
members.
Answer:
A complex number has two parts: real and imaginary.
Structures can be used to realize complex numbers in C,
as shown below:
#include<stdio.h>
int main()
{
struct complex { /*Declaring the complex number
datatype using structure*/
float x,y;
};
Struct complex p = {0.0, 1.1};
}

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

You might also like