0 ratings0% found this document useful (0 votes) 8 views67 pagesC Program +2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
\l Review the concept of C Program
C isa general-purpose high level language that was originally developed by Dennis Ritehne
for the
UNIX operating system, It was first implemented on the Digital Equipment Corporation
PDP-I1
Computer in 1972.
C isa general-purpose high level language that was originally developed by Dennis Ritehie
for the
UNIX operating system. It was first implemented on the Digital Equipment Corporation
PDP-11
Computer in 1972.
Cisa general-purpose high level language that was originally developed by Dennis Ritchie
for the
UNIX operating system. It was first implemented on the Digital Equipment Corporation
PDP-11
Computer in 1972.
Cisa general-purpose high level language that was originally developed by Dennis Ritchie
for theUNIX operating system. Jt was first implemented on the Digital Equipmen;
PDP-11
Computer in 1972.
C is a general-purpose high level language that was originally developed by Dz
for the
UNIX operating system. It was first implemented on the Digital Equipment «
PDP-11
Computer in 1972.
C isa general-purpose high level language that was originally developed by Dennis
for the UNIX operating system. It was first implemented on the Digital Eqy;
Corporation PDP-I1 computer in 1972. The C language is highly efficient progra,
language and easy to understand. It has both the properties of high level and low
language, so it is also term as Middle level language.
Input /Output Function
The C programming language provides standard library functions to read any given
and to display data on the console. The printf() and scanf() functions are knox
formatted /O functions because they can take any type of format of data from th
devices.
Formatted 1/0 Functions
Formatted 1/O functions are used to take various inputs from the user and dis
multiple outputs to the user. These types of I/O functions can help to display the 0.
to the user in different formats using the format specifiers. These I/O supports all:
types like int, float, char, and many more.
printf):
printf() function is used in a C program to display any value like float, integer, charac:
string, etc on the console screen. It is a pre-defined function that is already declare’
the stdio.h(header file).
Syntax
print{(“Format Specifier”, varl, var2, ..., varn);
seanf():
scanf() function is used in the C program for reading or taking any value from i
keyboard by the user, these values can be of any data type like integer, float, charac
string, and many more. This function is declared in stdio.h(header file), that’s why it is a?
4 pre-defined function. In scanf() function we use &(address-of operator) which is used!"
store the variable value on the memory location of that variable.
Syntax:
scanf(“Format Specifier”, &varl, &var2, ..u, &varn);formatted Input/Output functions
unformatted I/O functions are used only for character data type or character array/string
and cannot be used for any other datatype. These functions are used to read single input
from the user at the console and it allows to display the value at the console.
The following are unformatted I/O functions
1) getch()
2) getche()
3) getchar()
4) putchar()
5) gets()
6) puts()
7) putch()
getch:
getch() function reads a single character from the keyboard by the user but doesn’t
display that character on the console screen and immediately returned without pressing
enter key. This function is declared in conio.h(header file). getch() is also used for hold
the screen.
Syntax:
getch);
or
variable-name = getch();
2) getche():
getche() function reads a single character from the keyboard by the user and displays it
on the console screen and immediately returns without pressing the enter key. This
function is declared in conio.h(header file).
Syntax:
getche();
or
uel
variable_name = getche();
3) getchar():
The getchar() function is used to read only a first single character from the keyboard
whether multiple characters is typed by the user and this function reads one character at
one time until and unless the enter key is pressed. This function is declared in
stdio.h(header file)
Syntax:
Variable-name = getchar();
4) putchar():
The putchar() function is used to display a single character at a time by passing that
character directly to it or by passing a variable that has already stored a character. This
function is declared in stdio.h(header file)
Syntax:
Co Frogramming [ESE
roved by CDC, Nepal5)
6)
7)
putchar(variable_name);
gets():
gets() function reads a group of characters or strings from the keyboarq by i
these characters get stored in a character array, This function allows us to y,
separated texts or strings. This function is declared in stdio.h(header file),
Syntax:
char strflength of string in number}; /Declare a char type variable of any lenyy,
Bets(str);
puts():
In C programming puts() fun
which is already stored
file).
Syntax:
puts(identifier_name );
Let's sce an example to read a string using gets() and print it on the console using puts
#include
#include
it main()
mn is used to display a group of characters or
a character array. This function is declared in stdio.h+-
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Y our name is: ");
puts(name); //displays string
return 0;
i
putch():
Putch() function is used to display a single character which is given by the user and
ae Prints at the current cursor location. This function ig declared in conio.h(be*
ile)
Syntax:
putch(variable_name);
Control Structures / Statements In C Language
The structure which regulate the order in which
control structure.
(i) Toalter the flow of a program
(i) Test the logical conditions
(ii) Control the flow of execution as per the selection these condi oe
program using decision-making statements, tions can be placed in
Program statements are executed are call
Computer Science [Grade ~ XII) =
Approved hoyLUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS.
wage SI
aking statements
ang!
" pecision
simple if ‘Statement
3 if-else Statement
) Nested if-else statement
9 else - if Ladder
°) switch statement
simple if statement
Tt is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will executed or not.
The general syntax is =
ifftest expression)
{
Statement block
}
Statement
») if-else statement
The if ... else statement is an extension of the simple if statement. It is used when there are
two possible action, It is used to select one alternative action among two alternative based
on result of condition.
The general form is :
ifftest expression)
{
Statement] ;
}
else
{
Statement2;
}
©) Nested if-else statement
Nested if statements mean if statement inside
if (condition!)
{
// Executes when condition] is true
if (condition2)
{
// Executes when condition2 is true
}
i
C= Programming
rowed by CDC, Nepal
another if statement. ]Am: pape) ett wma A Pttmmcet
4
om Can BNE CNC M
Feed + phos
ot peed |
/
athe
Aho My
t
4A ptf pete
40 HY
powell | totaled Band Hp
1 aad ad « eehmsanad OIA sth bt Powabal M Aetmnrwad paoors
het
det
PAA) He pataelad Ponet 1 | bot op
tot
PAR | bt pr noted Hane |),
‘
potato bi,
}
Opel
14 aetetlled theoed 19
Le rotated howe UI howe
whe Hhadder
We prorat etnwonng, Wehbe heletted 10 whee beeen #8 Hrten Hl beddet Move moet
aot wr4 weds totes bie proetha wetiend brewedd 11 Hellot ond paoradsnane
ere
Crened sh epbdee fit Weahaae dt Aadethetd be
Uta diol )
/
folalarnntd |)
)
hee NL condition l)
‘
Maoherneid])
!
Hee Mt onuldon)
{statement;
\
else
Definult_ Statements
}
{OTHE program to Find largest fom three numbers given by user to explain working of i
°)
else-if statement or ladder
Hincludesstdio.h>
int main)
{
int a,b,c;
printf("Enter three numbers: \n");
seanf("%d%d%d", &a, &b, &c);
iffa>b && a>c)
{
printf("Largest = %d", a);
}
else if(b>a && b>c)
{
printf("Largest = %d', b);
}
else
{
printf("Largest = %d", c);
return(0);
}
switch statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called
switch variable. Here, We can define various statements in the multiple cases for the
different values of a single variable.
The syntax of switch statement in c language is given below:
switch(expression)
{
case valuel:
/code to be executed;
break; //optional
case value2;
Approved by CDC, Nepal T-Programming [QEON‘eode to be executed;
break; //optional
default:
code to be executed if all cases are not matched;
}
'
Loop control statements
a) for Loop
b) while Loop
©) do-while Loop
Loop Type Description
1.| While In while loop, a condition is evaluated before processing 1 body q
Loop the loop.
If a condition is true then and only then the body of a loop iy
executed,
2] Do-While | Ina do...while loop, the condition is always executed after the body’
Loop ofa loop.
Itis also called an exit-controlled loop.
3] For Loop [in a for loop, the initial value is performed only once, then the)
condition tests and compares the counter to a fixed value after each)
iteration, stopping the for loop when false is returned,
While Loop
The syntax of while loop in c language is given below:
while(condition)
{
Ieode to be executed
}
Deno
#include
int main()
{
int i=1;
while(i<=10)
{
printf("%d \n",i);
im;
}
return 0;
‘Computer Science [Grade XII)p)
°
while
syntax of do-while loop
do
{
//Statements
}while(condition test);
Program to add numbers until the user enters zero
Hinclude
int main()
{
double number, sum = 0;
// the body of the loop is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
} while(number != 0.0);
printf("Sum = %.2If",sum);
return 0;
}
for loop
The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{
I statements inside the body of loop
}
(RETPrint numbers from 1 to 10
#include
int main()
{
inti;
for (i= 1; i< 11; +4)
{
printf("%d ", i);
}
return 0;
}
Approved by CDC. Nepal
Co Programming ESSNested For Loop in C
Loop inside another loop is called Nested Loop
Hinclude
int main)
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %d\n",i i);
}
}
return 0;
}
Output:
0,0
01
0,2
0,3
1,0
11
1,2
1,3
3. Unconditional control statements
a) goto Statement
b) break Statement
©) continue Statement
a) goto
It is used after the normal sequence of program execution by transfering te:
some other part of program.
The syntax for the goto statement is as follows —
‘Syntax Forward jump ‘backward jump
goto label; —___ bbe stmt =
abel ; stmt, _ ‘goto label: ss
[I Caepae Se [oe ainclude stilio, Le
maint)
{
print("Hello");
goto Hy
print{("How are");
1: printi("you");
}
Output
Hello you
by break
It is a keyword which is used to terminate the loop (or) exit from the block.
The control jumps to next statement after the loop (or) block.
break is used with for, while, do-while and switch statement,
When break is used in nested loops then, only the innermost loop is terminated,
The syntax for break statement is as follows ~
Syntax
' ‘Stmtl:
‘Sumr;
break;
‘Stmt3;
‘Sunt;
Following is the C program for break statement ~
#include
main()
i++)
printf ("%d", i);
if (i==3)
ws :
}
PeoeT by CIN, NepalOutput
When the above program is executed, it produces the following output ~
123
continue
The continue statement in C programming works somewhat like the brea,
Instead of forcing termination, it forces the next iteration of the loop to ty
skipping any code in between,
The syntax for the continue statement is as follows —
Syntax
i —
Stmtl;
‘Stmt2:
continue; —
‘sumt3;
Sunt:
Following is the C program for the continue statement —
#include
main()
{
inti;
for (i=1; i<
t
if j==2)
continue;
printf("%d", i)
3
}
Output
‘When the above program is executed, it produces the following output —
12345
Revision for Lab
1. Write a program to check whether a number is odd or even
2. Write a program to read the radius of a circle and display its area,
4. Write a program to find smallest among the three numbers.
5. Write a program to find sum of first N natural numbers.
6.
7.
Write a program to print all prime numbers between 1 to 100.
‘Write a program to sort N integer numbers into ascending order,write a program to find the factorial of a number.
‘write a program to check whether a word is palindrome or not.
10. Write a program to read marks in computer of 40 students and count number of
student with marks greater than or equal 80.
11. Write a C program to input 10 numbers and display the largest and smallest among
them.
12. Write a program to display the name of the day in a week, depending on the number
entered through the keyboard using the switch-case statement.
13. Write a program to enter elements for 3x3 matrix and find the sum horizontally and
vertically.
14, Write a program to count the numbers of vowels and consonants in a given text.
15. Write a program to input the name of 30 students and arrange them in alphabetical
order.
We can construct a program from smaller pieces or components. These smaller pieces are
called modules such that each piece is more manageable than the original program. In C,
these modules are functions. These modules are building blocks of C and the place where
all program activity occurs. Programs combine user-defined functions with library
functions to develop a complete program and C standard library has a wide variety of
functions
What is Function?
‘A function is a named, independent section of a program that performs a specific, well-
defined task and can optionally return a value to the calling program. Each function has a
unique name and has can perform its task without interference from or interfering, with
other parts of the program.
Every C program consists of one or more functions. One of these functions is the main
function. Execution of a program will always begin by carrying out the instructions in
main, If a program contains multiple functions, their definitions may appear in any order,
though they must be independent of one another.
A function will carry out its action whenever the function is called from some other portion
of the program. Same function can be called fom several different parts of the program.
Generally, a function will process information that is passed to it from the calling portion
of the program and return a single value. Information is passed to the function via special
identifiers called arguments and returned via the return statement
Advantages of Functions
a) Manageable Program Development
b) Allows a program to be broken down into a number of smaller, self- contained
components which makes simple in coding
= C= Programming©) Reduce complexity of program coding
d) Large program can be easily developed using it.
©) Many programmers can work on a single project at same time.
f) The debugging process becomes easy. We can debug program function,
debugged functions are glued to develop bugs free program development,
rode written only once
f function used
void main() void main()
{ {
function();
Fede writin twice
Fig: Proper use of function in a program
How a Function Works?
AC program does not execute the statements in a function until the function is
another part of the program. When a function is called, the program can send the &
information in the form of one or more arguments. An argument is program data nex
the function to perform its task. The statement is the function then execute, pera
whatever task each was designed to do. When the function statements have fin
execution passes back to the same location in the program in the form of retum value
Following figure shows a program with three functions, each of which is called on.
time function is called, execution passes to that function. When the function is ft
execution passes back to the place from which the function was called. The functs
called as many times as needed, and function can be called in any order.
Fig: How function works?
‘Computer Science [Grade - XID,ctured Programming
PFe term ‘structured programming’ has come to mean a collection of principles and
practices that are directed towards developing correct programs which are easy to
understand and maintain.
Some programmers insist that they have been using this technique for a long time. This
may well be true, but the recent emergency of this technique has evolved from an attempt
pt to formalize the process of designing programs in the same manner as the logic design
has been formalized. The techniques used are, in general, not new but the formal basic
definitely is.
Advantages of structured programming language are given below:
a) It is easy to write a program because complex problems are broken into a number of
smaller tasks.
b) _ It is easy to debug a program.
The objectives of structured programming are to provide methodologies such as:
a) Programs are developed quickly and with fewer mistakes.
b) Programs are read and understand easily.
c) A portion of a program can be modified without upsetting the functions of other
portions.
The principles of structured programming are as follows.
a) Structuring of control flow.
b) Decomposing a program into ‘modules’ or ‘partitions’
c) Top down approach towards program designing.
The Top Down Approach
The process of designing a program consisting of a hierarchical structure of modules can be
viewed as top down.
The top-down approach towards program design starts with the specification of the
function to be performed by a program and then breaks it down into progressively
subsidiary function. The division of the function progress with increasing levels of details.
Each function at each level is ultimately realized in the form of a module.
The top down structure can be viewed as a tree structure, a typical example of which is
shown below. Each box in this figure is a module. The topmost module denoted by 1
represents the program which can be called the main-line module or main-control module.
In this case, the main control-module is divided into three subordinate modules denoted by
2,3 and 4, The modules 2 and 4 require further divisions and in this process, the terminal
modules are 5, 6, 7 and 8. The functions of these terminal modules are assumed be
simple enough to be easily programmed in the source language.Module]
5
[Mes Module Mole]
1 8
fig: A typical top down approach
The top down approach has the following advantages.
Icimitates the human tendency to solve a problem by outlining the broad concepts.
then subsequently going into the details.
The details of a module can be worked out with no (or minimum) change of the pr,
outlined concepts regarding its functions.
The programmer never losses sight of the assumptions made at the previous lev,
development of modules can take place in parallel.
Writing a Function
Writing a function is depending upon the program but actual defining a function, ;
body of function and calling function are given below:
= Function prototype
= Function definition
= Call the function
Function Prototype (Function Header)
Function prototype is a declaration statement that specifies the function name, the
and types of its arguments and the return type of the function. Prototype only nee
function definition comes after use in program. They are generally written at the beg
ofa program, ahead of any user-defined function. It is written in the following form.
Data_type function_name(argl, arg2, arg3, ..., argn);
Where Data_type is the type of data that may return value or not. The return type
char, int, long, float, double. The non-return type is void. Function_name is the ma
function and argl, arg2, arg3,.... , argn are types of arguments that are to be passed in
function.
For example, the function with the prototype
double power(double x, int n);
Takes in one doubleand one intargument and returns a double.
Function prototype is identical to the function header, with a semicolon 2
Argument name can be different than that of the function definition.
double power(double val, int exponent),
Parameter names can be omitted
[double power(double, iat},
ewjon Definition
he main functioning body of function is called Function definition, It has two parts:
«Function header
+ Body or Function block
Function header is same as function prototype without semicolon. The body or function
block contains statements within curly brackets, It declared by the following way.
data_type function-name( parameter-list)
{
declarations and statements;
Details of syntax is as follows:
function-name: any valid identifier
data_type: data type of the result (can be omitted, defaults int), void — indicates that the
function returns nothing
parameter-list: comma separated list, declares parameter variables. A type must be listed
explicitly for each parameter
The function body will contain the statements that define the action to be taken by the
function. The statements inside the body can be expression statements, compound
statements, control statements and so on. Variables can be declared inside blocks (can be
nested). All variables declared inside functions are local variables (Known only inside the
function).
int area(int length , int breadth) /*Function header*/
{
statements;
}
Thoname of Theparamers dene the pes of
ree Ot tefunction values passedito the function when
Soe |scalled, and they identify their names
inthe body ofthe function
doubTe power (double x, int n)
{
double result = 1.0;
‘The function. ‘inti;
body's between
‘the braces for (i =0; i 10)
{
EY Computer Science Gate=xm Approved bye!" |gome Examples of Program
The program to find the cube of given number is given below.
[#include
#include
long cube(long x); /* function prototype */
int main()
{
long answer, input;
printf("Enter an integer value: ");
scanf("%ld", &input);
answer = cube(input); /* function call */
printf("\nThe cube is %ld.\n", answer);
return 0;
}
long cube(long x)
long x_cubed; Co
x cubed =x "x "x; ("Function definition’
return x_cubed;
} -
Program to find the area of circle
#include
#include
#define pi 3.14
float area(float);
void main()
{
clrser();
float a,r;
printf(“Enter radius of circle\n”);
scanf(“%f",&r);
a=area(r);
printf(“‘\nArea=%d”, a);
getch();
}
float area(float r)
{
float A;
Apitr*r;
return(A);torial of a given number
sacha
Program to find th
| Hinelude
#include
| int factorial(int);
| void main()
.
| clrser():
im a.f:
| printi(*\nEnter a number to find factorial:");
| scanfi“%ed".&a);
| ffactorial(a);
| printf(“\nFactorial of given number=%d",f);
getch():
int factorial(int x)
t
int i, fact;
| fact=|
| for(i=lsi<=x;it+)
return fact;
}
The Return Keyword
‘The return keyword is used to return the program control from a function to th:
function. In general terms, the return statement is written as
return expression;
‘The value of expression is returned to the calling function of the program. No exe
present if'a function return type is void.
A function definition can contain multiple return statements. However, only +
executed.
void func(int n)
f
if(n<1)
{
printf("Number is not posit
return;
}
if (n%2 == 0)
printf(""Number is even");
else
‘Computer Science [Grade — XI)
aTputs("Number is odd");
1
int maximum(int a, int b)
if(a>b)
return a;
clse
return b;
1
Argument
The mechanism used to convey information to a function is the argument
Actual Argument and Formal Argument
Any variable declared in the body of a function is said to be local to that function. If the
variables are not declared cither or arguments or inside function body are considered
“global” to the function and must be defined externally. Arguments defined inside the
function are called formal arguments where as the argument from which the arguments
have been passed to a function is known as actual arguments.
The arguments are placed between parentheses following the function name in the call
printf("%glt", power(8.0, i); __]
When a function is called the value of the arguments is copied to
parameters in the function definition.
je correspondins
parr eate 20, 23), Teagumentsinatuncsoncainan'>
PrintfC'xa\t", Power(6.0, 2)) esses isarintan
double power(double x, intn) |
{ |
double result = 1.0;
Thevaiuestois | int 43 Trecodeininedady ole
reumedvinenthe funcaenesecaes nine
funcben completes . ‘upumentvatves paced
execuiton for (i= 0; 1
#include
void add(int,int);
void main()int a,b;
clrser();
printf("Enter the value of a:");
scanf("%d",&a);
printf("Enter the value of b:");
scanf("%d",&b);
add(a,b);
getch();
}
void add(int x, int y)
‘
{
int ¢;
c=xty;
printf{"The value of sum is:%d",c);
}
Body of function;
}
Program to find the sum of two numbers by this method is given below.
tassing Arguments Return Value
In this method, the arguments are passed inside a function, the arguments may be any type
and it returns value. It is written in the form:
return_data_type function_name(arguments)
i
Body of function;
int myfunction(arguments)
{
Body of function;
}
Program to find the sum of two numbers by this meth
#include
#include
int add(int, int);
4
‘tproved by CDC, Nepal
od is given. below.vou! maind)
ANE AS
olrser()
printt("Enter the value of a");
seantt dl" ayy
printt("Enter the value of b:");
soantt od");
| weadd(a.b);
print" Phe value of sum is:od",x);
}
int add(int x, int y)
Returning values from function
Function can return value but arguments are pass
inside a function or not depa
upon the characteristics of function that is described by the followings.
No Passing Arguments no Return Value
In this method, the arguments are not passed inside a function, and it does not retum)
All necessary declarations, input, process and output are written inside a function
written in the form:
non_return_data_type function_name()
t
}
Body of function;
#includesstdio.h>
H#include
void add(void);
void main()
{
clrser();
add();
getch();
}
void add(void)
{
int a,b,c;
rrprinti"Enter the value of
scanf("%d",&a);
printf("Enter the value of b:
scanf("%d" ,&b);
c=atb;
printf("The value of sum is:%d",c);
}
void myfunction()
{
Body of function;
}
}
Program to find the sum of two numbers by this method is given below.
No Passing Arguments and Retura Value
In this method, the arguments are not passed inside a function, and it returns value. All
necessary declarations, input, process are written inside a function. It is written in the form:
Retum_data_type function_name()
Body of function;
}
Example:
int myfunction()
{
Body of function;
}
Program to find the sum of two numbers by this method is given below,
Finclude
#inelude
int add(void);
void main()
{
int x;
clrscr();
x=add();
Red by COC NET C= Programing EMgetch();
}
int add(void) |
{ |
int a,b,c; |
printf{"Enter the value of a:");
scanf("%d" &a);
printf{"Enter the value of b:");
scanf("%d",&b);
c=atb;
return ¢;
1
}
Recursion
Recursion is the process by which function calls itself repeatedly until some py
condition has been satisfied. it is possible for the functions to call themselves. A funy
called ‘recursive’ if a statement within the body of a function calls the same fay
Sometimes called ‘circular definition’, recursion is thus the process of defining son,
in terms of itself.
A program to demonstrate factorial function using recursion.
#include
#include
Jong int factorial(long int n);
‘void main()
t
Jong int answer,n;
clrser();
printf("Enter the num
seanf("%ld" &n);
answer=factorial(n);
printf("The factorial of %ld! is %ld",n,answer);
getch();
}
Jong int factorial(long int n)
{
long int fact=1;
if{as=1)
return n;
else;
return n*factorial(n-1);
}
[oeam to find the product of any two numbers using recursion.
Finclude |
#include i
int product(int,int);
void main()
{
|
|
int a,b.x; |
|
|
progt
clrser();
printf("Enter the value of a:");
scanf{"%d" a); |
printf("Enter the value of b:");
scanf("%d",&b);
x=product(a,b);
printf("The value of product is:%d",x);
}
int product(int x, int y)
{
if(¥=1)
return x;
else
return x+product(x,y-1);
). What if I need to return more than one value from a function?
{n.Many times you will need to return more than one value from a function, or, more
commonly, you will want to change a value you send to the function and keep the change
afier the function ends.
. How do I know what a good function name is?
ins.A good function name describes as specifically as possible what the function does,
(. When variables are declared at the top of the listing, before main(), they can be used
anywhere, but local variables can be used only in the specific function. Why not just
declare everything before main()?
‘ns,Variable scope is discussed on previous chapter
(. What other ways are there to use recursion?
Ans.The factorial function is a prime example of using recursion, The factorial number is
needed in many statistical calculations. Recursion is just a loop; however, it has one
difference from other loops. With recursion, each time a recursive function is called, a new
set of variables is created. This is not true of the other loops that you will learn about in the
next chapter.
‘wowed by CDG, Nepal ToPreammng EONQ Does main() have to be the first function in a program?
Ans.No. It is a standard in C that the main() function is the first function to execute; j,,
can be placed anywhere in your source file. Most people place it first so that jy
locate.
Q. What are member functions?
Ans.Member functions are special functions used in C++ and Java. They are part o
which is a special type of structure used in C+ and Java.
Will you use structured programming when writing your C programs?
1.
2. How does structured programming work?
3, Howdo C functions fit into structured programming?
4. What must be the first line of a function definition, and what information does it co,
5. How many values can a function return?
6. Ifa function doesn't return a value, what type should it be declared?
7. What's the difference between a function definition and a function prototype?
8. Whats a local variable?
9, How are local variables special?
10. Where should the main() function be placed?
roca
iS
1. Write a header for a function named do_it() that takes three type char argumen:
returns a type float to the calling program.
Write a header for a function named print_a_number() that takes a single type int ar
and doesn't return anything to the calling program.
3. What type value do the following functions return?
a) int print_error( float err_nbr);
b) long read_record( int rec_nbr, int size ;
4, BUGBUSTER:What's wrong with the following listing?
Hinclude
void print_msg( void );
main()
{
v
print_msg( "This is a message to print")
return 0;
}
void print_msg( void )
{
‘Computer Sciputs( "This is a message to print")
return 0;
'
BUGBUSTER: What's wrong with the following function definition?
int twice(int y);
return (2 * y);
}
Rewrite Listing 5.4 so that it needs only one return statement in the larger_of() function.
Write a function that receives two numbers as arguments and returns the value of their
product.
Write a function that receives two numbers as arguments. The function should divide the
first number by the second. Don't divide by the second number if it's zero. (Hint: Use an if
statement.)
Write a function that calls the function?
|. Write a program that uses a function to find the average of five type float values entered by
the user.
. Write a recursive function to take the value 3 to the power of another number. For example,
if 4 is passed, the function will return 81.
Yes! (Well, OK, this is a trick question, but you better answer "yes" if you want to become
a good C programmer.)
Structured programming takes a complex programming problem and breaks it into a
umber of simpler tasks that are easier to handle one at a time.
After you've broken your program into a number of simpler tasks, you can write a function
to perform each task.
The first line of a function definition must be the function header. It contains the function's
name, its return type, and its parameter list.
A function can return either one value or no values. The value can be any of the C variable
types.
A function that returns nothing should be type void.
‘A function definition is the complete function, including the header and all the function's
statements, The definition determines what actions take place when the Function executes.
The prototype is a single line, identical to the function header, but it ends with a semicolon,
The prototype informs the compiler of the function's name, return type, and parameter list.
4. A local variable is declared within a function.
3. Local variables are independent from other variables in the program.
'0. main) should be the first function in your listing.
ein