0% found this document useful (0 votes)
10 views55 pages

Notes Complete Book

The document provides an introduction to programming concepts, specifically focusing on C language, including definitions of key terms like computer program, programming language, and programmer. It explains the structure of a C program, the role of integrated development environments (IDEs), and the importance of syntax and comments. Additionally, it covers data types, variables, constants, and user interaction functions like printf and scanf, along with examples and explanations of operators.

Uploaded by

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

Notes Complete Book

The document provides an introduction to programming concepts, specifically focusing on C language, including definitions of key terms like computer program, programming language, and programmer. It explains the structure of a C program, the role of integrated development environments (IDEs), and the importance of syntax and comments. Additionally, it covers data types, variables, constants, and user interaction functions like printf and scanf, along with examples and explanations of operators.

Uploaded by

w45198834
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name: __________________ Subject: Computer

Class: M-II / Section: ______ Date:

Chapter # 1
Introduction To
Programming
Q1: Define computer program.
Ans: The set of instructions given to the computer are known as a
computer program or Software.

Q2: What is computer programming?


Ans. The process of feeding or storing these instructions in the computer
is known as computer programming.

Q3: Who is programmer?


Ans. The person who knows how to write a computer program correctly Is
known as a programmer.

Q4: Who and when C language was developed?


Ans. C language was developed by Dennis Ritchie between 1969 and 1973 at Bell
Laboratories.

Q5: What is programming language?


Ans. Programmers write computer programs in these special languages (C.
C++ Java etc.) called programming languages. Java, C. C++, C#,
Python are some of the most commonly used programming languages.

Q6: What is Programming Environment?


Ans. A collection of all the necessary tools for programming makes
up a Programming environment. It is essential to setup a
programming environment before we start writing programs. II works
as a basic platform for us to write and execute programs.

Q7: What is Integrated Development Environment (IDE)?


Ans. The software that provides a programming environment to facilitate
programmers in writing and executing computer programs is known as an
Integrated Development Environment (IDE). An IDE has a graphical user
interface (GUI), meaning that a user can interact with it using windows and
buttons to provide input and get output.
Q8: Writer down the IDEs for C programming language.
Ans. 1) Visual Studio 2) Xcode 3) Code::Blocks 4) Dev C++

Q9: What is the purpose of text editor? (OR) What is text editor?
Ans. A text editors is a software that allows programmers to write and
edit computer Programs. All the IDEs have their own specific text editors.

Q10: What la the purpose of complier In C language? (OR) What is


compiler?
Ans. A compiler is software that is responsible for conversion of a
computer program written in some high level programming language to
machine language code.

Q11: What is syntax?


Ans. The set of rules used to write an accurate program is known as
syntax of the language. Syntax can be thought of as grammar of a
programming language.

Q12: What is syntax error?


Ans. While programming, if proper syntax or rules of the programming
language are not followed, the program does not get compiled. In this case, the
compiler generates an error. This kind of errors is called syntax errors.
Q13: What do you know about reserved words? (OR)Write
down the name of some reserved words.
Ans. Every programming language has a list of words that are
predefined. Each word has its specific meaning already known to the
compiler. These words are known as reserved words or keywords.
Some names of reserved words are as follows: auto, let, else, switch
and return.

Q14: Write down the name of main parts of structure of a C program.


Ans. A program can be divided into three main parts:
1. Link section or header sector):
2. Main section
3. Body of main {} function:

Q15: What is link section or header section?


Ans. White writing programs in C language, we make extensive use of
functions that are already defined in the language. But before using
the existing functions, we need to include the files where these
functions have been defined. These files are called header files. We
include these header files in our program by writing the include
statements at the top of program.

Q16: Write down the general structure of an include statement.


Ans. General Structure of an include statement is as
follows;
#Include<headerfile_name›

Q17: Explain the general structure of an include statement.


Ans. General Structure of an include statement is as follows;
#Include<header file_name>
Here header file name can be the name of any header file in the
above example. We have included file stdio.h that contains
information related to Input and output functions. Many other header
files are also available for example file math.h contains all
predefined mathematics functions.

Q18: What is main section of C language?


Ans. It consists of a main function. Every C program must contain a
main() function and it is the starling point of execution.

Q19: What is the body of main() section?


Ans. The body of main() is enclosed in the curly braces {}. All the
Statements inside these curly braces make the body of main function.

Q20: Write down the three key points to write C Language program
correctly.
Ans. (i) The sequence of statements in a C language program should
be according to the sequence In which we want our program to be
executed.
(ii) C language is case sensitive. It means that if a keyword is defined
with all small case letters, we cannot capitalize any letter i.e. int is different
from Int
(iii) Each statement ends with a semi-colon; symbol.
Q21: What are comments? Also write example.
Ans. Comments are the statements in a program that are ignored by the
compiler and do not get executed. Usually comments are written in natural
language.
Example: In English language, in order to provide description of our code.

Q22: Write down the purpose of writing comments?


Ans. Comments can be considered as documentation of the program. Their purpose
is.
1) It facilitates other programmers to understand our code.
2) It helps us to understand our own code even after years of writing it. We
do not want these statements to be executed, because it may cause syntax
error as the statements are written in natural language

Q23: How many types of comments are?


Ana. In C programming language, there are two types of comments:
1, Single-line Comments 2. Multi-line Comments
Q24: What is the difference between single -line comments and multi-
line comments?
Ans. Single-line comments start with //Anything after // on the same line, is
considered a comment. For example, //This is a comment.
Multi line comments start with /* and end at */. Anything between /* and */ is
considered a comment, even on multiple lines. For example,
/* this is
a multi- line comment*/

Q25: What do you know about constants?


Ans. Constants are the values that cannot be changed during the execution
of a program e.g. 5, 75.7, 1500 etc. in C language, there are three types of
constants:
1. Integer Constants
2. Real Constants
3. Character Constants

Q26: How you can explain Integer constants?


Ans. These are the values without a decimal point e.g. 7, 1256. 30100. 53555, -54,-
2349 etc. It can be positive or negative. If the value is not preceded by a sign, it is
considered as positive.

Q27: Differentiate between Real Constants and Character Constants?


Ans. The differences are as follows:

Real Constant Character Constant

These are the values including a decimal Any single small case letter, upper case
point letter, digit, punctuation mark, special symbol
e.g 3 .14, 15 3333, 75.0, -1575.76, - enclosed within " is considered a character
7941.2345 constant e.g. 'S. '7' . 'a' . 'X' , '.' etc.
etc. They can also be positive or
negative,

Q28: What are Variables?


Ans. A variable is actually a name given to a memory location, as the
data is physically stored inside the computers memory. The value of a
variable can be changed in a program. It means that, in a program, if a
variable contains value 5, then later we can give it another value that
replaces the value 5.
Example'. height, Average, Weight, _var1.
Q29: How many Data Type of a Variable are?
Ans. The data types of variable are as under:
1. integer— int (signed/unsigned)
2. Floating Point — float
3. Character — char

Q30: Define Integer?


Ans. Integer data type is used to store integer values (whole numbers).
Integer lakes up 4 bytes of memory. To declare a variable of type
integer, we use the keyword int

Q31: What is difference between Signed let and Unsigned int?


Signed Int Unsigned Int

A signed int can store both positive and An unsigned int can store only positive
negative values ranging from values
,.2,147,483,648 to 2,147,483,647. By and its value ranges from 0 to
default, type int is considered as a +4204,067,295.
signed integer. Keyword unsigned Int is used to declare
an
unsigned integer.

Q32: What is Floating Point data?


Ans. Float data type is used to store a real number (number with floating
point) up to six digits of precision. To declare a variable of type float,
we use the keyword float. A float uses 4 bytes of
memory. Its value ranges from 3.4x10-38 to 3.4x1038.

Q33: What is the purpose of character- char data type?


Ans. To declare character type variables in C, we use the keyword
char. It takes up just 1 byte of memory for storage. A variable of char
type can store one character only.

Q34: Write down the any two rules for naming variables.
1. A variable name can only contain alphabets r uppercase or
lowercase) digits and
underscore sign.
2. Variable name must begin with a letter or an underscore, it cannot begin
with a digit.
Q35: What is difference between Variables and Constants?
Ans. The difference between variables and constants are as follows:
Variable Constant
A variable is actually a name given Constants are the values that
to a memory location, as the data is cannot be changed in a program e.g.
physically stored inside the computers 5. 75.7, 1500 etc. In C language, there
memory. The value of a variable can are three types of constants:
be changed In a program It means
that, in a program, if a variable 1. Integer Constants
contains value 5. then later we can 2. Real Constants
give it another value that replaces the 3. Character Constants
value 5. Some examples of valid
variable names are height. Average.
Weight, _va 1 .

Q36: What is variable declaration?


Ans. Declaring variable includes specifying its data type and giving it a
valid name. Following syntax can be followed to declare a variable
Data_ type variable_ name;

Some examples of valid variable declarations are as follows:


Unsigned Int age;
float height;

Q37: What is variable Initialization?


Ans. Assigning value to a variable for the first time is called variable
initialization. C language allows us to initialize a variable bath at the time
of declaration, and after declaring it.

Q38: Write down structure for initializing variable.


Ans. For initializing a variable at the time of declaration, we use the following
general structure.
data_type variable_name = value;
Chapter # 2
User Interaction
1, Define a computer.
Ans. A computer is a device that takes data as input, process that
data and generates the output.

2. Define printf function?


Ans. printf is a built-in function in C programming language to snow
output on screen. Its name comes from "print formatted- that is used to
print the formatted output On screen, All data types can be displayed with
printf function.

3. Whet is format specifier?


Ans. Format specifiers are used to specify format of data type during input
and output operations. Format specifier is always preceded by a percentage
(%) sign

4. Write down the format specifiers against different data types In C


language.
Ans. Format specifiers against different data types in C language are as follows
Data typo Format Specifier
int %d or %i
float %f
char %c

5. If float height...5.8; int age e. 36; What will be the output


of following statement: print(i-My age is %d and my height is
M. age. height);
Ans. Output: My age is 35 and my height is 5.80

6. What will be the output of following code:


eincludeestdio.h>
void main()
{
printf("Sum of 23 and 45 is %d", 23 + 46);

Ans. Output Sum of 23 and 45 is 68

7. What is the purpose of scanf()?


Ans. scanf is a bull-in function in C language that takes input from user
into the variables. We specify the expected input data type in scanf
function with the help of format specifier. If user enters integer data
type, format specifier mentioned in scanf must be %d or %i.

8. What is common mistake in scanf function?


Ans. It is a very common mistake to forget & sign in the scanf
function Without & sign, the program gets executed but does not
behave as expected.

9. What is the use of getch()?


Ans. Getch() function is used to read a character from user The character
entered by user does not get displayed on screen This function is generally
used to hold the execution of program because the program does not continue
further until the user types a key

10. Which library function is used to include getch()?


Arts: To use this function, we need to include the library <conio.h> in the
header section of program.

11. What is statement terminator?


Ans. A statement terminator is identifier for compiler which identifies
end of a line. In C language semi colon (;) Is used as statement
terminator. If we do not end each statement with a ; It results into error.

12. What Is the purpose of escape sequence In C language?


Ans. Escape sequence are used in printf function Inside the double
quotes (" "). It forces printf to change its normal behaviour of showing
output.

13. What Is Formation of escape sequence?


Ans. Escape sequence consists of two characters. The first character is
always back slash (\) and the second character varies according to the
functionality that we want to achieve. Back slash (\) is called escape
character which is associated with each escape sequence to notify about
escape.

14. What is the purpose of \n?


Ans. After escape character, \n specifies movement of the cursor to start of
the next line. This escape sequence Is used to print the output on multiple
lines.

15, What is the purpose of Tab (\t)?


Ane. Escape sequence \t specifies the I/O function of moving to the next
tab stop horizontally. A tab stop Is collection of 8 spaces. Using \t
takes cursor to the next tab stop. This escape sequence is used when
user presents data with more spaces.

16. What Is an operator?


Ans. An operator in a programming language is a symbol that tells the
compiler or interpreter to perform specific mathematical, relational or
logical operation and produce final result,

17, Write down the name of basic operator?


Ans: C language offers numerous operators to manipulate and process
data. Following is the list of some basic operator types:
• Assignment operator
• Arithmetic operator
• Logical operator
• Relational operator

19. What is assignment operator?


Ans. Assignment operator is used to assign a value to a variable, or assign
a value of variable to another variable. Equal sign (=) is used as
assignment operator in C.

19. Write a program that swaps the values of two


Integer variables.
Ans.
#include<stdio.h>
#include<canio.h>
void main()
clrscr();
int a = 2, b = 3, temp;
temp = a;
a = b;
b = temp;
printf(“Value of a after swapping: %d\n”,a);
printf(“Value of b after swapping: %d\n”,b);
getch();
}

20. What is the use of an arithmetic operator?


Ans. Arithmetic Operators are used to perform arithmetic operations on data
21. What Is Division operator?
Ans. Division operator (/) divides the value of left operand by the value of right
operand
e.g. Float result = 3.0 / 2.0;
After the statement, the variable result contains the value 1.5

22. What Is Multiplication operator?


Ans. Multiplication operator (*) Is a binary operator which performs the product
of two numbers.
e.g. int multiply = 5*5;
After the execution of statement, the variable multiply contains value 25.

23. What Is an Addition operator?


Ans. Addition operator (+) calculates the sum of two operands.
e.g. int add =10 + 10;
Resultant value in variable add is 20.

24. Why the statement a = a + 1; and a--; are used in C language?


Ans. The statement a = a + 1, is used to increase the value of variable a by
1. In C Language, this statement can also be written as a++; or ++a;
similarly, a - - or - - a; used to decrease the value of a by 1.

25. What is Subtraction operator?


Arm. Subtraction operator (-) subtracts right operand from the left operand.
e.g. int result = 20 - 15;
After performing subtraction, value 5 is assigned to the variable result.

26. What Is Modulus operator?


Ans. Modulus operator (%) performs divisions of left operand by the
right operand and returns the remainder value after division. Modulus
operator works on integer data types.
Int remaining =14 % 3;
As, when we divide 14 by 3, we get a remainder of 2, so the value
stored in variable remaining is 2.

27. What is common mistake while writing arithmetic statement Is C


language?
Ans. While writing arithmetic statement is C language. a common
mistake Is to follow the usual algebraic rules e.g. writing 6*y as 6y. and
writing x*x*x as x3 etc. It results in a compiler error.
28. Why relational operators are used in C language?
Ans. Relational operators compare two values to determine the
relationship between values. Relational operators identify either the values
are equal, not equal, greater than or less than one another C language
allows us to perform relational operators on numeric and char type data.

29. What Is difference between Assignment operator and equal to operator?


Ans. In C language. equal to operator Is used to Check for equality of two
expressions, whereas assignment operator assigns the result of expression
on right side to the variable on left aide. Double equal operator (==)
checks whether right and left operands are equal or not. Single equal operator
(=) assigns right operand to the variable on left side.

30. What Is difference between logical operator and arithmetic operator?

Logical operator Arithmetic Operator


Logical operators perform operations Arithmetic Operators are used to
on Boolean expression and produce a perform arithmetic operations on data.
Boolean expression as a result Division operator, multiplication
The result of a relational operation operator and modulus operator is some
is a Boolean expression, so logical arithmetic operator.
operators can be performed to
evaluate more than one relational
expression

31. What Is difference between Division operator and Multiplication


operator?

Ans
Division Operator Multiplication Operator
Division operator (/) divides the value Multiplication operator (*) is a binary
of left Operand by the value of right operator which performs the product of
operand. Example: two numbers. Example:
float result = 3.0 /2.0; int multiply = 5*5

32. Define logical operator?


Ans. Logical operators perform operations on Boolean expression
and produce a Boolean expression as a result. The result of a
relational operation is a Boolean expression, so logical operators can
be performed to evaluate more than one relational expression.
33. Writs down the name of logical operator.
Ans. The logical operators are as follows
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT

34. What Is AND operator (&&)? Also write its truth table.
Ans. AND operator && takes two Boolean expressions as operands
and produces the result true if both of its operands are true. it returns
false if any of the operands is false. The truth table for AND operator is
shown below:

Expression 1 Operator Expression 2 Result


False && False False
False && True False
True && False False
True && True True

35. What is OR operator (||)?


Ans. OR operator accepts Boolean expression and returns true if at least one of the
operands Is true.

36. Draw the truth table for OR operator.


Ans. The truth table for OR operator is shown below:
Expression 1 Operator Expression 2 Result
False || False False
False || True True
True || False True
True || True True

37. What is NOT operator (!) Also draw truth table


Ans. NOT operator negates or reverses the value of Boolean expression
it makes it true, if it is false and false if it is true. The truth table for Not
operator is given below.

Expression Operator Result


True ! False
False ! True
38. Differentiate between Unary and Binary Operators
Ans
Unary Operator Binary Operator
Unary operators are applied over one Binary operators require two
operand only e.g. logical not (l) operands to perform the operation e.g.
operator has only one all the arithmetic operators, and
operand. Sign operator (-) is another relational operators are binary
example of a unary operator e.g. -5 operators. The logical operators &&
and || are also binary operators.

39. What is Operators' Precedence?


Ares. If there are multiple operators in an expression, the question arises that
which operator Is evaluated first. To solve this issue, precedence has
been given to each operator. An operator with higher precedence Is
evaluated before the operator with lower precedence In case of equal
precedence, the operator at left side is evaluated before the operator at
right side.

40. Describe the operator precedence of different operators?

41. Define Ternary operator?


Ans: The operator offers Three operands in C programming Language is called
ternary operator

42. Differentiate between scanf and getch()?


scanf getch()
scanf is a built-in function in C language that Getch() function is used to read a
takes Input from user into the variables. We character from user The character
specify the expected input data type In entered by user does not get displayed
scanf function with the help of format specifier on screen. This function is generally
if user enters integer data type, format used to hold the execution of
specifier mentioned in scanf must be %d or program because the program
%i. does not continue further until the user
types a key. To use this function we need to
Include the library conio.h in the header
section of program

43. What is the difference between == operator and = operator ?


Ana: In C language. == operator is used to check for equality of two
expressions, where as = operator assigns the result of expression on
right side to the variable on left side. Double equal operator (==) checks
whether right and left operands are equal or not. Single equal operator (=)
assigns right operand to the variable on left side.

44. Write tree of clrscr();


Ans: This function is used to clear the output screen of C language editor
Syntax: clrscr();
Programming Exercise
Exercise 1
The criteria for calculation of wages in a company are given below:
Basic Salary = Pay Rate Per Hour X Working Hours of Employee
Overtime Salary = Overtime Pay Rate X Overtime Hours of Employee
Total Salary = Basic Salary + Overtime Salary
Write a program that should take working hours and overtime hours of
employee as input. The program should calculate and display the total
salary of employee.
Program
#include<stdio. h>
#include<conio.h>
void main()
{
clrscr();
int
wh,oh,rate_per_hour,otrate,basicsalary,overtime_salary,total_salary;
printf("Enter Working Hours of Employ:");
scanf("%d",&wh);
printf("Enter overtime working hours:");
scanf("%d",&oh);
printf(''Enter rate per hours:");
scanf("%d",&rate_per_hour);
printf("Enter over Time rate per hour:");
scanf("%d",&otrate);
basic salary = wh*rate_per hour; overtime salary = orotrate;
total salary = basic_salary+overtime_salary;
printf("Total salary is = %d",total_salary);
getch();
}
Output
Enter Working Hours of Employ: 20
Enter overtime working hours: 10
Enter rate per hours: 20
Enter over Time rate per hour: 10
Total Salary is = 500

Exercise 2:
Write a program that takes Celsius temperature as input, converts the
temperature into Fahrenheit and shows the output. Formula for conversion
of temperature from Celsius to Fahrenheit is F=(9C/5)+32
Program
#include<stdio.h>
#include<conio.h> int main()
{
clrscr();
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f ", &celsius);
//celsius to fahrenheit conversion formula
fahrenheit = (celsius * 9 / 5) + 32;
printf("Celsius =%.2f Fahrenheit=%.2f ", celsius,fahrenheit);
getch();
}
Output
Enter temperature in Celsius: 37
Celsius = 37.00 Fahrenheit = 98.60

Exercise 3:
Write program that display the following output using single printf
statement:
* * * *
1 2 3 4
Program
#include <stdio.h>
void main()
{
printf(" *\t*\t*\t*\n1\t2\t3\t4");

}
Output
* * * *
1 2 3 4

Exercise 4:
Write a program that displays the following output using single
printf statement:
I am a Boy
I live in Pakistan
I am a Proud Pakistani
Program
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf("l am a boy \n I live in Pakistan \n I am a Proud Pakistani");
getch();
}
Output
I am Boy
I live in Pakistan
I am a Proud Pakistani

Exercise 5:
A clothing brand offers 15% discount on each item. A lady buys 5 shirts
from this brand. Write a program that calculates total price after
discount and amount of discount availed by the lady. Original prices of
the shirts are:
Shirt1 = 432
Shirt2 = 320 Shirt3 = 270 Shirt4 = 680
Shirt5 = 520
Note: Use 5 variables to store the prices of shirts
Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int shirt1 = 423, shirt2 = 320, shirt3 = 270, shirt4 = 680, shirt5 = 520;
float totalprice, totaldiscount, finalprice;
printf("First Shirt price: %d \t \t Discount is %.2f \t Payable price: %.2 f \n",shirtl,
(shirt1*0.15), (shirt1-(shirt1*0.15)));
printft("Second Shirt price:%d\t Discount is %.2f \t Payable price:%.2f
\n",shirt2,(shirt2*0.15), (shirt2-(shirt2*0.15)));
printf("Third Shirt price: %d \t \t Discount is %.2f \t Payable price: %.2f \n",shirt3,
(shirt3*0.15), (shirt3-(shirt3*0.15)));
printft("Fourth Shirt price: %d \t Discount is %.2f \t Payable price: %.2f \n",shirt4,
(shirt4*0.15), (shirt4-(shirt4*0.15)));
printf("Fifth Shirt price: %d \t \t Discount is %.2f \t Payable price: %.2f \n",shirt5,
(shirt5*0.15), (shirt5-(shirt5*0.15)));
printf("\n\n_______________________________________________________________\n");
totalprice = shirt1 + shirt2 + shirt3 + shirt4 + shirt5;
totaldiscount =
(shirt1*0.15)+(shirt2*0.15)+(shirt3*0.15)+(shirt4*0.15)+(shirt5*0.15);
finalprice = (shirt1-(shirt1*0.15))+(shirt2-(shirt2*0.15))+(shirt3
(shirt3*0.15))+(shirt4 -(shirt4*0.15))+(shirt5-(shirt5*0.15));
printf("Total price: %.2f \t Total Discount is %.2f \t Final price: %.2f \n",totalprice,
totaldiscount, finalprice);
getchO;
}
Output
First Shirt Price 423 Discount is 63.45 Payable price: 359.55
Second Shirt Price 320 Discount is 48.00 Payable price: 272.00
Third Shirt Price 270 Discount is 40.50 Payable price: 329.50
Fourth Shirt Price 680 Discount is 102.00 Payable price: 578.00
Fifth Shirt Price 520 Discount is 78.00 Payable price: 442.00
____________________________________________________________________________
Total Price: 2213.00 Total Discount is 331.95 Final price: 1881.05

Exercise 6:
Write a program that swaps the values of two integer variables without help of
any third variable.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b; //a=30 (10+20)
b=a-b; //b=10 (30-20)
a=a-b; //a=20 (30-10)
printf(“After swap a=%d b=%d",a,b);
getch();
}
Output
Before swap a = 10 b = 20
After swap a = 20 b = 10

Exercise 7:

Write a program that takes a 5 digit number as input, calculates and


displays the sum of first and last digit of number.

Program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int number;
printf("Enter a number with length 5 digits: ");
scanf("%d",&number);
printf("The sum of first and 5th digit is: %d", (number / 10000) + (number %10));
getch();
}

Output
Enter a number with length 5 digits: 12345
The sum of first and 5th digit is: 6

Exercise 8:
Write a program that takes monthly income and monthly expenses of the user
like electricity bill,
gas bill and food expense. Program should calculate the following:
• Total monthly expenses • Yearly saving
• Totally yearly expenses • Average saving per month
• Monthly savings • Average expense per month
Program
#include<stdio.h>
#include<conio.h>
void main()
{

clrscr();
int monthly_income, electricity_bill, gas_bill, food_expense, monthly_Expenses,
monthly_savings;
printf("Please enter your Monthly Income: ");
scanf("%d",&monthly_income);
printf("Please enter you Monthly Expenses: ");
printf(“\n\n\tYour Electricity Bill: ");
scanf("%d",&electricity_bill);
printf("\nYour Gas Bill: ");
scanf("%d",&gas_bill);
printf("\tYour Food Expense: ");
scanf("%d",&food_expense);
monthly_Expenses = electricity_bill + gas_bill + food_expense;
printf (“\n\n\tTotal Monthly Expenses are: %d", monthly_Expenses);
printf(“\n\tTotal Yearly Expenses are: %d", (monthly_Expenses)*12);
monthly_savings = monthly_income-monthly_Expenses;
printf("\n\n\t Your Monthly savings is: %d", monthly_savings);
printf(“\n\n\t Your Yearly savings is: %d", monthly_savings*12);
printf("\n\n\t Average saving per month: %d", monthly_savings);
printf(“\n\n\t Average expense per month: %d", monthly_Expenses); \
getch();
}
Output
Please enter your Monthly Income: 63000
Please enter your Monthly Expenses
Your Electricity Bill : 2300
Your Gas Bill : 500
Your Food Expense : 22000
Total Monthly Expenses are : 24800
Total Yearly Expenses are : 297600
Your Monthly Saving is : 38200
Your Yearly Saving is : 458400
Average saving per month : 38200
Average expense per month 24800

Exercise 9:
Write a program that takes a character and number of steps as input from
user. Program should then jump number of steps from that character.
Sample output:
Enter character: a
Enter steps: 2
Enter character: c
Program
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
char c;
int steps;
printf("Enter character: ");
scanf("%c",&c);
printf(“\nEnter Steps: ");
scanf("%d",&steps);
int x = c + steps;
printf(“\nNew Character: %c",x);
getch();
}
Output
Enter character: a
Enter steps: 2
New Character: c
Exercise 10:
Write a program that takes radius of a circle as input. The program should
calculate and display the area of circle.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float radius;
printf("Please enter the radius of circle: ");
scanf(" %f ",&radius);
printf("\n Area of circle is: %.2f ", 3.14*radius*radius);
getch();
}
Output
Please enter the radius of circle: 20
Area of circle is: 1256.00
Chapter # 3
Conditional Logic
1. What do you know about Control Statements?
Ans: In order to solve a problem, control statement is used to control the flow of execution
of a program Sometimes there is also need to execute one set of instructions if a particular
condition is true and another set of instructions if the condition is false.

2. What are the types of control statements?


Ans: There are three types of control statements in C language.
Sequential Control Statements.
Selection Control Statements
Repetition Control Statements

3. What is sequential control?


Ans: Sequential control is the default control structure in C language. According to the
sequential control, all the statements are executed in the given sequence.

4. What are Selection Statements?


Ans: The statements which help us to decide which statements should be executed next,
on the basis of conditions, are called selection statements.

5. How many types of selection statement have?


Ans: There are two types of selection statements.
if statement
if-else statement

6. What Is the use of it statement?


Ans: C language provides if statement, In which we specify a condition, and associate a
code to It. The code gets executed if the specified condition turns out to be true, otherwise
the code does not get executed.

7. Write dawn the Structure of If statement.


Ans: if statement has the following structure in C language:
if (condition)
{
Associated Cede
}
8. What is the purpose of If in If statement structure?
Ans: In If statement structure, if is a keyword that is followed by a condition inside
parentheses (). A condition could be any valid expression Including arithmetic
expressions, relational expressions, logical expressions, or a combination of these.

9. Why if-else Statement Is used In C language?


Ans: It executes the set of statements under if statement if the condition is true,
otherwise executes the set of statements under else statement

10. Write down the general structure of if-else statement?


Ans: General structure of the if-else statement is as follows

if (condition)
{
Associated Code
}
else
{
Associated Code
}
Associated code of If statement is executed if the condition is true otherwise the code
associated with else statement is executed

11. Define compound statement.


Ans: A set of multiple instructions enclosed in braces is called a block (enclosed in curly
braces) or a compound statement.

12. How you can close If and if else statement?


Ans: If there are more than one instruction under if statement or else statement, enclose them
in the form of a block (enclosed in curly braces). Otherwise, the compiler considers
only one instruction under it and further instructions are considered independent.

13. What is Nested Selection Structures?


Ans: Conditional statements within conditional statements are called nested selection
structures

14. Write general structure for nested selection structure?


Ans: Following general structure Is true for nested selection structure
if {condition 1 Is true)
if (condition 2 is true)
Associated code
else
if (condition la true)
Associated code

15. Write the If-else-if statement structure?


Ans: C language also provides an if-else-if statement that has the following structure
if (condition 1)
{
Code to be executed If condition 1 Is true;
}
else if {condition 2)
{
Code to be executed if condition 1 N false but condition 2 It true;
}
_______________________________________________________________________________________

else if (condition N)
{
Code to be executed If all previous conditions are fates but condition
N Is true;
}
else
{
Code to be executed If ail the conditions are false;
}
16. What common mistakes that we do in compound statement?
Ans: In compound statements, it is a common mistake to omit one or two braces while
typing. To avoid this error, it is better to type the opening and closing traces first and then
type the statements in the block (enclosed in curly braces).

17. Write use of nested selection structure?


Ans: Nested selection structure is used for decision making in C language.

18. Define Condition?


Ans: A condition could be any valid expression including arithmetic expressions,
relational expressions, and logical expressions or a combination of these.

19. Draw a flow chart to shows the basic flow of if statement.

20. Draw the flow chart for the structure of If-else statement.

Programming Exercises
Exercise # 1
Write a program that takes two Integers as Input and tells whether first one Is a factor of
the second one?
Program

#include<stdio.h>
#include<conio.h>
#include <math.h>
int main()
{
clrscr();
int n1, n2;
printf( "Input the first integer : " );
scanf("%d", &n1);
printf( "Input the second integer " );
scanf("%d", &n2);
if(n1% n2 == 0)
printf( “\n%d is a Factor of %d. \n", n1, n2 );
else
printf( “\n%d is not a factor of %d. \n", n1, n2 );
getch();
}

Output
Input the first integer : 9
Input the second integer : 3
9 is a Factor of 3.

Exercise # 2
Write a program that takes a number as Input and displays "YES" If the input
number is a multiple of 3, and has 5 in unit's place e.g. 15,75.
Program
#include<stdio. h>
#include<conio.h>
#include <math.h>
int main()
{
clrscr();
int n1;
printf( "Input Any number :" );
scanf("%d", &n1);
if(n1%3==0)
printf( "YES %d ,%d",n1,n1*5);
getch();
}

Output
Input Any number : 15
YES 15 , 75

Exercise # 3
Following is the list of discounts available in "Grocery Mart".

Total Bill Discount


1000 10%
2500 20%
5000 35%
10000 50%

Write a program that takes total bill as Input and tells how much discount
the user has got and what is the discounted price?
Program
#include<stdio.h>
#include<conio.h>
#include <math.h>
int main()
{
cIrscr();
int total_bill;
printf( “Enter your Total Bill: “);
scanf("%d", &total_bill);
if(total_bill >=1000 && total_bill <= 2499)
printf("Discount = %d\nDiscounted Price =%f ",10,total_bill*0.1);
else if(total_bill >= 2500 && total_bill <= 4999)
printf("Discount = %d\nDiscounted Price =%f ",20,total_bill*0.2);
else if(total_bill >= 5000 && total_bill <= 9999)
printf(''Discount = %d\nDiscounted Price =%f ",35,total_bill*0.35);
else if(total_bill >= 10000)
printf("Discount = %d\nDiscounted Price =%f ",50,total_bill*0.5);
getch();
}

Output
Enter your Total Bill : 10000
Discount = 50
Discount Price = 5000.000000

Exercise # 4
Write a program that takes as Input, the original price and sale price of a product and tells
whether the product Is sold on profit or loss. The program should also tell the profit/loss
percentage.

Program
#include <stdio.h
#include<conio.h>
#include <math.h>
int main()
{
clrscr();
int cp,sp,amt;
/* Input cost price and selling price of a product*/
printf("Enter cost price: ");
scanf(''%d", &cp);
printf(“Enter selling price: ");
scanf("%d", &sp);
if(sp>cp)
{
/* Calculate Profit */
amt = sp - cp;
printf("Profit = %d", amt);
}
else if(cp>sp)
{
/* Calculate Loss */
amt = cp - sp;
prinff("Loss = %d", amt);
}
Else
{
/* Neither profit nor loss */
printf("No Profit No Loss.");
}
getch();
}

Output
Enter cost price : 1000
Enter selling price : 1500
Profit = 500

Exercise # 5
Write a program that takes as Input, the lengths of 3 sides of a triangle and
tells whether it Is a right angle triangle or not For a right angled triangle,
Hypotenuse2 = base2 + height2.
Program
#include<stdio.h>
#include<conio. h>
#include<math.h>
int main()
{
clrscr();
int x,y,z;
printf("Input the three sides of a triangle :\n");
scanf("%d %d %d",&x,&y,&z);
if((x*x) + (y*y) == (z*z) || (x*x) + (z*z) == (y*y) || (y*y) + (z*z) == (x*x) )
{
printf("It is a right angle triangle!\n"):
}
else
{
printf("It is not a right angle triangle!\n");
}
getch();
}

Output
Input the three sides of a triangle :
7
3
5
It is not a right angle triangle!

Exercise # 6
Following is the eligibility criteria for admission in an IT University.
• At least 60% marks in Matric.
• At least 65% marks in Intermediate (Pre-Engineering or ICS).
• At least 65% marks in entrance test.
Write a program that takes as Input, the obtained and total marks of
Matric, Intermediate and Entrance Test. The program should tell
whether the student Is eligible or not.
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
clrscr();
int omm,tmmomi,tmi,ome,tme;
printf("Enter Your obtained marks in Matric :");
scanf("%d",&omm);
printf("Enter Total marks in Matric");
scanf("%d",&tmm);
printf("Enter Your obtained marks in Intermediate :");
scanf("%d",&omi);
printf(“Enter Total marks in Intermediate :");
scanf("%d",&tmi);
printf("Enter Your obtained marks in Entrance :”);
scanf("%d",&ome);
printf("Enter Total marks in Entrance :");
scanf("%d",&tme);
if(((omm*100) / tmm) > 60 && ((omi*100) / tmi ) > 65 && ((ome*100) / tme ) >
65);
{
printf("You are Eligible for Admission");
}
else
{
printf("Not Eligible);
}
getch();

Output
Enter Your obtained marks in Matric : 833
Enter Total Marks in Matric : 1050
Enter Your obtained marks in Intermediate : 804
Enter Total Marks in Intermediate : 1100
Enter Your obtained marks in Entrance : 72
Enter Total Marks in Entrance : 100
Your are Eligible for Admission

Exercise # 7
Write a program that calculates the bonus an employee can get on the following
basis:
Salary Experience with Company Bonus Tasks Bonus

10000 2 Years 5 1500

10000 3 Years 10 2500

25000 3 Years 4 2000

75000 4 Years 7 3500

100000 5 Years 10 5000

The program should take as input, the salary, experience and number of
bonus tasks of the employee. The program should display the bonus on the
screen.

Program
#include<stdio.h>
#include<conio.h>
#include <math.h>
int main()
{
clrscr();
int salary,experience,bonus task;
printf("Enter Your salary: ");
scanf("%d",&salary);
printf("Enter Your Experience: ");
scanf("%d",&experience);
printf("Enter Your Bonus task:");
scanf("%d",&bonus_task);
if(salary == 10000 && experience == 2 && bonus_task == 5)
printf("Bonus is = %d",1500);
if(salary == 10000 && experience == 3 && bonus_task == 10)
printf("Bonus is = %d",2500);
if(salary == 25000 && experience == 3 && bonus_task == 4)
printf("Bonus is = %d",2000);
if(salary == 75000 && experience == 4 && bonus_task == 7)
printf(''Bonus is = %d",3500);
if(salary == 100000 && experience == 5 &&: bonus_task == 10)
printf("Bonus is = %d",5000);
getch();
}

Output
Enter your salary: 10000
Enter Your Experience: 2
Enter your Bonus task: 5
Bonus is = 1500
Chapter # 4
Data and Repetition
1. Define Data Structures.
Ans: Data structure is a container to store collection of data items in a
specific layout.

2. What is an Array?
Ans: An array is a data structure that can hold multiple values of same
data type and stores all the values at consecutive locations inside the
computer memory.

3. How we can declare an array of type int?


Ans: If we want to declare an array of type int that holds the daily wages
of a laborer for seven days, then we can declare it as follows
int daily_wage[7];

4. How we can declare an array of float type?


Ans: The example of the declaration of a float type array that holds marks of 20
students are given below.
float marks[20];

5. What is an Array Initialization?


Ans: Assigning values to an array for the first time, is called array initialization. An
array can be initialized at the time of its declaration, or later.

6. How we can initialize an array?


Ans: Array initialization at the time of declaration can be done in the following manner.
Data_type array_name[N]={valuel, value2, value3………….,valueN};

7. Writs down the example to declaration and Initialization of a float array


to store the heights of seven persons.
Ans: float height[7] = {5.7, 8.2, 5.9, 6.1, 6.0, 5.5, 6.2};

8. Can you declare an array without assigning the size of an array?


Ans: No, we cannot declare an array without assigning size.

9. Write down the example to Initialize an array of characters to store five


vowels of English language.
Ans: char vowels[5]={‘a’,’e’,’i’,’o’,’u’};

10. How we can initialize an array if we do not Initialize at the time of


declaration?
Ans: If we do not initialize an array at the time of declaration. then we
need to Initialize the array elements one by one. It means that we cannot
initialize all the elements of array in a single statement.

11. Can we initialize all the elements of array in a single statement? Explain it
with example.
Ans: No, we cannot initialize all the elements of array in a single
statement. The error show in following example.
void main()
{
int array[5];
array[5] = {10, 20, 30, 40, 50};
}
ERROR: initialization whole array after declaration not allowed

The compiler generates an error on the above example code, as we try to initialize the
whole array in one separate statement after declaring it.

12. How we can access array elements?


Ans: Each element of an array has an index that can be used with the
array name as
Array_name[index] to access the data stored at that particular index.

13. What is Important feature using variables as array indexes?


Ans: A very important feature of arrays is that we can use variables as array indices e.g.
Consider the following program;
#include<stdio h>
void main()
{
int array [5] = {10, 20, 30, 40, 50};
Int i;
Printf(“Please enter the index whose value you went to display”);
Scanf(“%d”,&i);
printf("The value is %d”, array[i]);
}

14. What Is Loop?


Ans: If we need to repeat one or more statements, then we use loops.
Example: If we need to write Pakistan thousand times on the screen,
then instead of writing printf (“Pakistan"); a thousand times, we use
loops.

15. What structures of loop provided by C language?


Ans: Following three structures are provided by C language.
1. For loop
2. While loop
3. Do While loop

16. What is the General structure of loops?


Ans: If we closely observe the process that humans follow for repeating a
task for specific number of times then it becomes easier for us to
understand the loop Structures that C language provides us for controlling
the repetitions.

17. Write down the General syntax of for loop.


Ans: In C programming language, for loop has the following general
syntax:
for (Initialization; condition; Increment/decrement)
{
Code to repeat
}

18. Draw a flowchart of for loop structure.

19. What part of for loop executed first?


Ans: Initialization is the first part to be executed in a for loop.

20. Find the output of below prograrnt


Ans.
int main()
{
int i=0, x=0;
do
{
If(i%5==0)
Cout<<x;
x++;
}
++i;
}
while(I<10);
cout<<x;
getch ();
}
Output
012

21. Find the output of below program


Ans:
int main()
{
int i=0, x=0;
for(i=1;i<10;i*=2)
{
x++;
cout<<x
}
cout<<x
getch ();
}
Output
12344

22. Define an Iteration.


Ans: Iteratioin is the process where a set of Instructions or statements are
executed repeatedly for a specific number of times until a condition becomes false.

23. What Is the general structure of Nested Loops?


Ans: We can observe that Code to repeat could be any valid C language code
It can also be another for loop e g. the following structure is a valid loop
structure.
for (initialization; condition; Incrernent/decrement)
{
for (Initialization; condition; Incremen/decrement)
{
Code to repeat
}
}

24. What Is nested loop structures?


Ans: When we use a loop inside another loop, it is called nested loop structure.

25. When do we use nested loops?


Ans: When we want to repeat a pattern for multiple times, then we use nested
loops, e.g if 10 times we want to display the numbers from 1 - 10. We can do
this by writing the code of displaying the numbers from 1 -10 in another loop that
runs 10 times.

26. What is difference between Loops and Arrays?


Ans: A variable can be used as array Indexes, so we can use loops to perform
different operations on arrays If we want to display the whole array, then instead
of writing all the elements one by one, we can loop over the array elements by
using the loop counter as array index.

27. How many times a white loop should be printed?


Ans: int main()
{
int i=1;
i=i-1;
while(i)
{
cout<<”it’s a while loop”;
i++;
}
getch();
}
Output:
Infinite Times

28. How we can use a loop to take input from user In an array of size 10?
Ans.: int a [10].
for (int i=0; i<10; i++)
scanf("%d'', &[i]);

29. Write down the code to display the elements of an


array haying 100 elements.
Ans: The followIng code can be used to display the elements
of an array having 100 elements
for (int i=0; i<100; i++)
printf("%d'', a[i]);

30. Write down the code to add all the elements of an array having 100
elements.
Ans: The following code can be used to add all the elements of an array having
100 elements.
int sum = 0;
for (int i=0; i<100; i++)
sum =sum + a[1];
printf(“The sum of all the elements of array Is %d”, sum);

31. Write down the example of while loop


Ans:
#include<stdio.h>
inr main()
{
int count=1:
while (count <= 4)
{
printf("%d ", count);
count++;
}
getch();
}
Output:
1234

32. Define counter Variable In for loop?


Ans: A counter variable is a variable that keeps track of the number of times a
specific piece of code is executed

33. Describe use of counter variable In for loop?


Ans: For loop use the counter variable whose values is increase or decrease
with each repetition of the loop.

34. Is loop a data structure? Justify your answers.


Aria: A loop is not a data structure because data structure means it is a specific
layout of computer memory to store collection of data items while loop is used to
repeat a set of statements.

35. Define while loop?


Ans: A while loop in C programming language repeatedly executes a set of
statements or instructions as long as the given condition is true.

36. Describe the structure of while loop?


Ans: while (condition)
{
Statement or set of statements:
}

37. What Is the advantage of Initialization array at the time of


declaration?
Arks: The following are the advantages of initializing an array at the time of
declaration.
I. Save time
2 Save memory
3. CPU friendly
4. Define the size
Programming Exercises
Exercise # 1
Use the loops to print the following patterns on console.

Program
#include <stdio.h>
#include<conio.h>
int main()
{
clrscr();
int i, j;
for(i=1;i<=3;i++)
{
for(j=1;j<=5;j++)
printf("*'");
printf(" \n");
}
getch();
}

Output:
*****
*****
*****

(2)
Use the loops to print the following patterns on console.
A
BC
DEF
GHIJ
KLMN
Program
#include <stdio.h>
#include<conio.h>
int main()
{
cIrscr();
char ch=’A’;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i; j++)
printf("%c",ch++);
printf(“\n);
}
getch();
}

Output:
A
BC
DEF
GHIJ
KLMN

Exercise # 2:
Write a program that takes two positive integers a and b as input and displays the
value of ab.

Program
#include <math.h>
#include <stdio.h>
#include<conio.h>
int main()
{
cIrscr();
int a, b, result;
printf("Enter a base number: );
scanf("%d", &a);
printf("Enter an exponent: ");
scanf("%d", &b);
result = pow(a, b);
printf("%d^%d = %d", a, b, result);
getch 0;
}
Output
Enter a base number 2
Enter an exponent: 3
2^3=8

Exercise # 3:
Write a program that takes two numbers as input and displays their
Greatest Common Divisor (GCD) using Euclidean method.
Program
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int m, n;
printf(" Enter two integer numbers:”);
scanf ("%d \n %d", &m, &n);
while (n > 0)
{
int r = m % n;
m = n;
n = r;
}
printf ("GCD = %d \n",m);
getch 0;
}

Output
Enter two integer numbers: 5
15
GCD = 5

Exercise # 4
Write a program to display factorials numbers from 1 to 7. (Hint: Use
Nested Loops)
Solution:
#include<stdio.h>
#include <conio.h>
int main()
{
clrscr();
int i;
unsigned long int fact = 1;
for(int n=1;n<=7;n++)
{
for(i = n; i> 0; i--)
{
fact = fact * i;
}
printf("%d \t",fact);
fact=1;
}
getch();
}

Output
1 2 6 24 120 720 5040

Exercise # 5
Write a program that takes 10 numbers as input in an array and displays
the product of first and last element on console.
Program
#include <stdio.h>
#include <conio.h>
int main()
{
clrscr();
int num[10];
printf("Enter 10 Numbers :");
for(int i =0;i<10;i++)
{
scanf("%d\n",&num[i];
}
printf("Product of 1st and last number is =%d",num[0]*num[9]);
getch 0;
}

Output
Enter 10 Numbers :
9
8
7
9
6
5
26
6
5
4
Product of 1st and last number is = 36

Exercise # 6
Write a program that declares and initializes an array of 7 elements and
tells how many elements in he array are greater than 10.

Program
#include <stdio.h>
#include <conio.h>
int main()
{
clrscr();
int num[7]={9,13,11,12,14,15,16},count=0;
for(int i =0;i<7;i++)
{
if(num[i]>10)
count++;
}
printf("The Elements greater than 10 in array are :%d",count);
getch();
}

Output
The Elements greater than 10 in array are 5
Chapter # 5
Functions
1. What is problem solving?
Ans: The process of solving difficult and complex problem is called problem
solving. To solve a problem, one has to adopt a systematic strategy.

2. Define divide and conquer?


Ans. A complex problem is divided into small problems. The smaller problems
can be solved separately to find the solution of the problem and then integrating all
the solutions. In this way, it becomes easier for us to focus on a single smaller
problem at a time, instead of thinking about the whole problem all the time. This
problem solving approach is called divide and conquer.

3. What do you know about functions of C language?


Ans. A function is a block of statements which performs a particular task. Each
program has a main function which performs the tasks programmed by the
user. Similarly, we can write other functions and use them multiple times.

[Link] down the name of typos of Functions


Ans. There are basically two types of functions:
1) Built-In Functions
2) User Defined Functions

5. Define built in functions?


Ans: The functions which are already defined in C programming language are
called built-In functions. These functions are also called library functions. These
functions are available as a part of language

6. Define user defined functions?


Ans: The functions which are defined by the programmer to perform specific tasks
are called user-defined functions. These functions are written according to the exact
need of the user.

7. Write the advantages of Functions.


Ans. Following are the advantages of Functions.
1. Reusability
2. Separation of task
3. Readability
4. Handling the Complexity of the problem.

8. Define reusability?
Ans: Functions provide reusability of code. It means that whenever we
need to use the functionality provided by the function, we just call the function.
We do not need to write the same set of statements again and again.

9. Define separation of task?


Ans: Functions allow us to separate the code of one task from the code of
other tasks. If we have a problem in one function, then we do not need to
check the whole program for removing the problem We Just need to focus at
one single function.

10. Define readability?


Ans: Dividing the program into multiple functions, Improves the readability of
the program.

11. Define the term handling the complexity of the problem?


Ans: If we write the whole program as a single procedure, management of the
program becomes difficult. Functions divide the program into smaller units,
and thus reduce the complexity of the problem.

12. What is the use of functions signature?


Ans. Function signature is used to define the inputs and output of a function

13. What is parameter of function?


Ans: A functon is a block of statements that gets some inputs and provides
some output. Inputs of a function are called parameters of the function.

14. What do you mean by return value of a function?


Ans. A function is a block of statements that gets some inputs and provides
some output. Output of the function is called its return value. A function can
have multiple parameters, but it cannot return more than one value.

15. Write down the general structure of a function signature.


Ans. The general structure of a function signature is as follows

16. What is int square(int); functions signsture?


Ana. A function that take an Integer as input and returns its square.

17. What is int float perimeter (float, float); functions signature?


Ans. This function that takes length and width of a rectangle as input and
returns the perimeter of the rectangle.

18. What Is int largest (int, int, int); functions signature?


Ans. A function that takes three integers as input and returns the largest value
among them.

19. What is float area (float); functions signature?


Ans. A function that takes radius of a circle as input and returns the area of
circle.

20. What is int isvowel (char); functions signature?


Ans. A function that takes a character as input and returns 1, if the character is
vowel, otherwise return 0

21. What is the general structure of defining a Function?


Ans. The function signature does not describe how the function performs the task
assigned to it. Function definition does that, A function definition has the following
general structure
return_typefunction_name (data_type_var1, data_type var2…..,data_type varN)
{
Body of the function
}

22. Write down the example to define the function.


Ans. Following example defines a function showPangram0 that does not take
any input and does not return anything, but displays "A quick brown fox Jumps
over the lazy dog" on computer screen.
void showPangram() (Function Name)
{
Printf(“\n A quick brown fox jumps over the lazy dog.\n”);
}
As the above function does not return anything thus return type of the function is
void.

23. Can function return more than one values?


Ans. No, a function cannot return more than one values.

24. Write down the general structure to make a function call?


Ans. Following is the general structure used to make a function call.
Function_name(value1, value2,….. ,valueN);

25. Define arguments?


Ans: The values passed to the function are called arguments.

26. Differentiate between arguments and parameters of the function.


Ans. The values passed to the function are called arguments, whereas
variables in the function definition that receive these values are called parameters
of the function

27. Which points are Important for the arrangement of functions in a


program?
Ans. Following point must be kept in mind for the arrangement of functions in a
program:
1 If the definition of called function appears before the definition of
calling function, then function signature is not required.
2 If the definition of called function appears after the definition of calling
function, then function signature of called function must be written before
the definition of calling function.

28. How many arguments can be used in a function?


Ans. C language doesn't put any restriction on number of arguments but
arguments greater than 8 are not preferred.

29. What is the output of the following program?


main()
{
int x=20;
int y=10;
swap(x,y);
printf(“%d %d',y,x+2);
}
swap(int x, int y)
{
int temp;
temp =x;
x=y;
y=temp;
}

Output:
10 22 (duplicate copy of arguments are generated on calling a function)

30. What will bo the output of the following code ?


output()
{
printf("%p”,output);
}
Ans. Some address will be printed as function names are just addresses.
Similarly output() is also a function and its address will be printed

31. What will be the output of the following code?


main()
{
int I;
printf("%d,scanf("%d",&i)); // value 10 is given as input here
}
Ans.1 as scanf returns number of items read successfully. So, number of items
read is 1.
32. What will be the output of the C program?
#include<stdio.h>
int main()
{
function();
return 0;
}
void function()
{
printf("Function in C is awesome”);
Ans: Output: Compilation error

33. What will be the error of the C program?


void message ();
{
printf("Hope you are fine :");
return 23;
Ans: Errors: After function definition there is no semicolon.

34. Whet will be the error of the C program?


int max (int a; int b)
{
if (a>b)
return a;
return b;
}
Errors: Between parameters use comma instead of semicolon.

Programming Exercises
Exercise # 1
Write a function int square (int x); to calculate the square of an integer x.

Program:
#include <stdio.h>
void main()
int square ( int ); /* Function signature*/
int n;
printf("Enter an integer number. ");
scanf("%d", &n);
printf("Square of %d is %d", n, square (n)); /* square () is called in printf() */
getch();
}
/* function definition*/
int square (int x)
return x*x;
}

Output:
Enter an integer number. 5
Square of 5 is 25

Exercise # 2:
Write a function int power(int x, int y); to calculate and return xy.

Program
#include <stdio.h>
void main()
{
int power (int, int); /* Function signature */
int a, b, p;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
p = power (a, b); /* Function call!*/
printf("%d raised to the power %d is %d “, a, b, p);
getch();
}
/* function definition */
int power (int x, int y)
{
int res = 1;
for (int c = 1; c <= y; c++)
res = res * x;
return res ;
}

Output:
Enter first number: 3
Enter second number: 2
3 raised to the power 2 is 9

Exercise # 3
Write a function to calculate factorial of a number.

Program:
#include <stdio.h>
void main()
{
int Factorial(int); /* Function signature */
int n, res;
printf("Enter any positive integer value:");
scanf("%d", &n);
res=Factorial (n); /* Function call */
printf("The calculated factorial of input number %d is %d",n, res);
getch();
}
/* function definition */
int Factorial (int x)
int fact = 1;
for (int c = 1; c <= x; c++)
fact = fact * c;
return fact;
}

Output:
Enter any positive integer value: 5
The calculated factorial of input number 5 is 120

Exercise # 4
Write a function which takes values for three angles of a triangle and prints whether the given
values make a valid triangle or not. A valid triangle is the one, where the sum of three angles is
equal to 180.

Program:
#include <stdio.h>
void main()
{
void triangle (int, int, int); /* Function signature */
int al, a2, a3;
printf("Enter a value for the first angle: ");
scanf("%d", &al);
printf("Enter a value for the second angle: ");
scanf("%d", &a2);
printf("Enter a value for the third angle: ");
scanf("%d", &a3);
triangle (a1, a2, a3); /* Function call */
getch();
}
/* function definition */
void triangle (int x, int y, int z)
{
int sum;
sum =x + y + z;
if (sum == 180)
printf("it is a valid triangle.");
else
printf("It is not a valid triangle.");
}

Output:
Enter a value for the first angle: 50
Enter a value for the second angle: 40
Enter a value for the third angle: 60
It is not a valid triangle.

Exercise # 5
Write a function which takes the amount and the interest percentage and return the interest
amount.

Program:
#include <stdio.h>
void main()
{
float interest (float, float); /* Function signature */
float amount, interest_percentage, interest_amount;
printf("Enter amount: ");
scanf("%f",&amount);
printf("Enter interest percentage: ");
scanf("%f",& interest_percentage);
interest_amount = interest (amount, interest_percentage); /* Function call */
printf("The calculated interest amount is %f", interest amount);
getch();
}
/* function definition */
float interest (float amt, float per)
{
return amt * per / 100.0;
}

Output:
Enter amount: 50000
Enter interest percentage: 15
The calculated interest amount is 7500.000000

Exercise # 6
Write a function which takes a number as input and displays its digits with spaces in between.

Program:
#include<stdio.h>
void main()
{
void separate_digits (int); /* Function signature */
int num;
printf("Enter 5 digits number: ");
scanf("%d", &num);
separate_digits (num); /* Function call */
getch();
}
/* function definition */
void separate_digits (int n)
{
int rem;
for (int d =10000; n != 0; d = d/10)
{
rem=n/d;
n=n%d;
printf("%d \t", rem);
}
}

Output:
Enter 5 digits number: 45678
4 5 6 7 8

Exercise # 7
Write the function to print the table of a number.

Program
#include <stdio.h>
void main()
{
void table (int t);|
int n;
printf("Enter a number: ");
scanf("%d", &n);
table (n);
getch();
}
/* function definition */
void table (int t)
{
for (int c =1; c <=10; c++)
printf("%d * %d = %d\n", t, c, t* c);
}

Output:
Enter a number: 5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

You might also like