You are on page 1of 25

COURSE CODE: SCAX1001

COURSE NAME: COMPUTER APPLICATIONS IN BUSINESS


CHAPTER NAME: ‘C’ LANGUAGE
SUBJECT COORDINATOR: MRS.JANCY

Unit –II
Control Structure
Decision Making And Branching Looping:
In c the following are the control or decision making statements:
If statement
Switch statement
Goto statement
If statement

It is used to control the flow of execution of statement.


Syntax: if(condition)
Evaluate the condition first and then depending on whether the value of the expression is true or false it
transfers the control to a particular segment.
Different types:

Simple if
if …..else

Nested if……..else
else…….if
Simple if:
Syntax: if(condition)
{
statement _block;
}
statement_x;
If the condition is true, the statement block will be executed. Otherwise, statement_block will be skipped
and the execution will jump to statement_x.
When the condition is true both statement block and statement x will be executed in sequence.

Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
1
a=30;
b=20;
if(a>b)
{
a=a+b;
}
printf(“%d”,a);
getch();
}
The output is: 50.
In this program, value of a is 30 and value of b is 20. Check the condition (a>b) if it’s true the
control execute the statement a=a+b and print the value of a. Otherwise the control execute only one statement
that statement is print the value of a.

if….else:
Syntax:
if(condition)
{
true _block statement;
}
else
{
false _block statement;
}
statement_x;
if condition is true, true _block statements will be executed. Otherwise, false _block statements will be executed.

Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
a=30, b=20;
if(a>b)
{
printf(“a is greatest”);
}
2
else
{
printf(“b is greatest”);
}
printf(“\n
Welcome”); getch();
}
The output is: a is greatest
Welcome
If condition is true, print the statements “a is greatest” and “Welcome”. Otherwise print the statements “b
is greatest” and “Welcome”.
Nested – if statements
Here more than one if….else statements are nested.
Syntax:
if( condition1)
{
if(condition2)
{
statement_1;
}
else
{
statement_2;
}
}
else
{
statement_3;
}
statement_x;
When both the conditions 1 and 2 are true, it executes the statement_1 and statement_x.
If condition1 is false, it execute the statement_3 and statement x.
If condition2 is false, it execute the statement_2 and statement x

else if ladder
Syntax :
if(condition1)
statement1; else
if(condition2)
statement2; else
if(condition3)

3
statement3;
else
default_statement;
statement_x;
The conditions are evaluated from the top. If a true condition is found, the statement associated will be executed and
the control is transferred to statement_x. if all the conditions are false, default_statement will be executed.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int avg;
printf(“Enter the average:”);
scanf(“%d”,&avg);
if(avg>79)
printf(“Grade=Honours”);
else if(avg>59)
printf(“Grade=First Class”);
else if(avg>49)
printf(“Grade=Second
Class”); else if(avg>39)
printf(“Grade=”Third Class”);
else
printf(“Grade=Fail”);
getch();
}

The Switch statement:


 If we use else-if ladder, the program becomes complex. So we use switch statement. 

 Multiway decision statement. 

 Tests the value of a given variable against a list of case values and when a match is found , block
of statement associated with that case is executed. 
Syntax :
switch(expression/variable)
{
case val-1: block-1;
break;
case val-2: block-2;
4
break;
case val-3: block-3;
break;
default: default_block;
break;
}
statement_x;
The expression is an integer or character expression. Val-1, val-2, val-3…..are called case_labels.
Each case_label should be unique. The value of expression is compared against, val-1, val-2… if a match is
found; the block of statements of that case will be executed. If there is no_match default_block will be
executed. Default is optional. The break statement signals to exit from switch statement.

Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int x;
printf(“Enter the x value:”);
scanf(“%d”,&x);
switch(x)
{
case 1: printf(“one”);
break;
case 2: printf(“two”);
break;
case 3: printf(“three”);
break;
default: printf(“invalid”);
break;
}
}
Output: Enter the x value: 1
one.
Enter the x value: 4
invalid
In this program, the value of x is 1. The value of x is compared against, 1, 2, 3, a match is found; the
block of statements of case 1 will be executed. Second time it getting another one value, that value is 4. There is
no_match default_block will be executed. It print the statement is invalid.
5
LOOPING:
looping statements execute the body of the loop repeatedly until some conditions are
satisfied. There are 2 types of loops.
Entry controlled loop
Exit controlled loop
In entry controlled loop the conditions are tested first if the conditions are not satisfied the body of
the loop will not be executed.
In exit controlled loop the conditions are tested at the end of body of body of loop, so the body of loop
is executed for the first time.
C language has 3 looping statements. They
are, While statement
Do statement

For statement

While statement:
Syntax :
while(condition)
{
body of the loop
}
while is an entry controlled loop. Condition is evaluated first. If it is true loop is executed. This process is
repeated until the test condition becomes false. The body of loop may have one or more statements. Braces
are needed only if the body has more than 1 statement.
Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
while(i<=5)
{
printf(“Welcome”);
i++;
}
getch();
}
Output: Welcome
Welcome
6
Welcome
Welcome
Welcome

Do statement
Syntax:
do
{
body of the loop;
}whil(condition);
This is an exit controlled loop. The body of the loop is executed first. Then the condition is evaluated. If it is
true then the body of loop is executed again. This process continues until the test condition becomes false. So
the body of loop is executed at least once.

Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int
i=10; do
{
printf(“Welcome”);
i++;
} while (i<=5);

getch();
}
Output: Welcome

For statement

Syntax:
for(initialization part; condition part;increment/decrement part)
{
body of the loop;
}

7
This is an entry controlled loop. Initialization of variables is done first using assignment
statements. Condition is evaluated next. If it is true body of the loop is executed. Then the increment part is
evaluated condition is evaluated and the process repeats until the test condition becomes false.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
printf(“Welcome”);

}
getch();
}
Output: Welcome
Welcome
Welcome
Welcome
Welcome

Unconditional Statement
The goto statement:
C uses goto statement to branch from one point to another point unconditionally. Goto statement
requires a label to identify the place label is any valid variable name.
Syntax : goto labelname;
labelname is referred to identify the location. goto statement used to transfer control to another
location in a program.

foreword jump backword jump


goto label; label: statement;
: :
: :
label: statement; goto label;
8
label: can be written either before or after the goto statement. During the running of the program,
when goto statement is met, control will jump to the statement immediately following the label. This happens
unconditionally.
Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int x;
lb:
printf(“Enter the x
value:”); scanf(“%d”,&x);
goto lb;
}

Break statement
If you want to jump out of the loop during the execution of loop we can use break statement.
Syntax: break;

Continue statement
Transfer the control to the next iteration of the nearest enclosing do, for or while statement.
Syntax: continue;
These 3 types are unconditional statements.

ASSIGNMENT QUESTIONS

1. what is meant by conditional and unconditional statement.


2. List the types of conditional control statement.
3. What is meant by looping statement.
4. Write the syntax for the following
(i) If.. else
(ii) Elseif ladder
(iii)Nested if
9
(iv)switchcase
5. What is the difference between while and do..while.
6. Write the syntax for goto.
7. What is the difference between break and continue.
8. In a for loop, if the condition is missing,then?
[A] it is assumed to be present and taken to be false
[B] it is assumed to be present and taken to be true
[C] it result in the syntax error
[D] execution will be terminated abruptly.
9. Break statement can be simulated by using ?
[A] goto
[B] return
[C] exit
[D] any of the above statement

10. Which of the following comment about for loop are correct?
[A] Using break is equivalent to using a goto that jumps to the statement immediately following the loop
[B] Continue is used to by pass the remainder of the current pass of the loop
[C ] if comma operator is used,then the value returned is the value of the right operand
[D] All of above

11. In a for loop, if the condition is missing, then infinite looping can not be avoided by
a [A] Continue statement
[B] goto statement
[C] return statement
[D] break statement

12. Write a program to print the following pattern.


1
12
123
1234
12345

EXAMPLE PROGRAM

1. C Program to Check if a given Integer is Odd or Even


2. C Program to Check if a given Integer is Positive or Negative
3. C Program to Find the Biggest of 3 Numbers
4. C Program to Calculate the Sum of Odd & Even Numbers
5. C Program to Reverse a Number & Check if it is a Palindrome
6. C Program to Find the Number of Integers Divisible by 5
7. C Program to Read Two Integers M and N & Swap their Values
8. C Program to Reverse a Given Number
9. C Program to Find if a given Year is a Leap Year
10. C Program to Convert a Given Number of Days in terms of Years, Weeks & Days
11. C Program to Display the Inventory of Items in a Store
12. C Program to Find the Sum of first 50 Natural Numbers using For Loop
13. C Program to Accept two Integers and Check if they are Equal
14. C Program to Compute the Sum of Digits in a given Integer
15. C Program to Find the Sum of two Numbers
10
16. C Program to Find Multiplication of two Numbers
17. C Program to find whether a Number is Prime or Not
18. C Program to find Product of 2 Numbers
19. C Program to Compute First N Fibonacci Numbers
20. Print out the squares of the first 10 integers

21. Print out all integers from -11 down to -20.

22. Print out all integers from 5 down to -5.


23. Ask the user for an integer and print out that integer’s times table.
24. Print the times table for 8 in one column

25. Show the output for the following C code

1. for(i = 2; i <= 6; i = i + 2)
printf("%d\t", i + 1);

2. for(i = 2; i != 11; i = i + 3)
printf("%d\t", i + 1);
3. for(i = 2; i == 2; i = i + 1)
printf("%d\t", i + 1);
3. for(i = 2; i == 2; i = i + 1)
printf("%d\t", i + 1);
4. for(i = 2; i <= 6; i = i + 2)
printf("%d\t", i + 1);
26. Print out $$$$$$ on seven consecutive lines.

REFERENCE LINKS
http://www.cquestions.com/2012/02/c-questions-and-answers.html
http://edugrip.blogspot.in/2012/09/c-language-multiple-choice-questions.html

Functions

A function is a block of code that has a name and it has a property that it is reusable i.e. it can be
executed from as many different points in a C Program as required.The name of the function is unique in a C
Program and is Global. It means that a function can be accessed from any location with in a C Program. We pass
information to the function called arguments specified when the function is called. And the function either returns
some value to the point it was called from or returns nothing.

We can divide a long C program into small blocks which can perform a certain task. A function is a
self contained block of statements that perform a coherent task of same kind.

C functions are classified into 2


categories: 1. Library functions.
Library functions are predefined functions. It is not written by the
user. Eg: printf(), scanf(), sqrt(), etc…

11
2. User_define functions.
This function should be written by the
user. Eg: add(), f1(), f4(), etc…
Advantages: Length of source program can be reduced.

Function
definition Syntax:
Datatype Functionname(argument list)
{
Local variable
declaration; Executable
stmt1; Executable stmt2;
------------
----------
return(expression);
}

 All parts are not essential some may be absent. 



 Functionname is similar to other variables in c. 

 The argument list contains valid variable names separated by commas. 

 List is surrounded by commas. Eg: power(x,n) 

Return values:
A function may or may not send back values to the calling function. The value is returned thru
return statement. The function can return only one value per call.
Syntax : return; (or) return(expression)

Eg1 return(x*y);

Eg2 if(x<=0)
return(0);
else
return(1);
We can specify the return type of a function in the function
header. Eg double product(x,y)
It means that the return type is double.
Function declaration:
Syntax: Datatype Functionname(number of parameters)
12
Eg: int add(int,int)
Calling a function:
A function can be called by using the function name in a stmt.
Syntax: Functionname(number of
parameters); Or
variable = Functionname(number of parameters);
Eg add(10,2);
Or
x=add(10,5);
When the compiler finds a function call control is transferred to that function.

Eg program:
#include<stdio.h>
#include<conio.h>
void main()
{
int add(int,int); Function declaration
printf(“Functions”);
x=add(“%d”,x); Function call
printf(“value of x is: %d”,x);
}
int add(int x,int y) Function header
{
int z;
z=x+y; Function defination return(z);

In the program, x takes the value 10, y takes value 2.add these two values and stored in variable is z
and returned to add() which is then returned to x and print the value of x.
Category of function:
Functions , depending on the arguments , and return values , are classified as
1. Functions with no argument and no return value.
2. Functions with argument and no return value.
3. Functions with no argument and one return value.
4. Functions with argument and one return value.
5. Functions with argument and multiple return values.

13
1. Functions with no argument and no return value

Here there is no data transfer between the calling function & the called function. A function does not
receive any data and it does not return any value.

Function1() no input Function2()


{ {
--------------- ---------------

--------------- ---------------
Function2(); no output
} }

Eg
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
sample();
getch();
}
sample()
{
printf(“welcome“);
return;
}
The output is: welcome

2. Functions with argument and no return value.

Function1() argument Function2(f) function to read date


We make calling
{ {
from the terminal and pass it on to the called
--------------- ---------------
function.
One way data communication.
--------------- ---------------
Function2(a); no return
values 14}
}
The argument in the function call is called actual argument and the values in the called function are called
formal arguments. The actual and formal arguments should match in number type and order.
If in case the actual arguments are more than formal arguments, then the extra actual arguments are discarded. If
actual arguments are less, then the extra formal argument will be initialized to garbage values. When a function
call is made, only a copy of the values of actual argument is passed into function.

Main()
{ actual arguments
----
Fun1(a1,a2……am)
}
Fun1(f1,f2…….fn)

Formal arguments
{
--------------
---------
--------------
}
Eg:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter the values for a&b ”);
scanf(“%d%d”,&a,&b);
15
mul(a,b); a & b are actual arguments
getch();
}
void mul(int p,int q) p & q are Formal arguments
{
int m;
m=p*q;
printf(“The value of m is%d”,m);
}
The output is: Enter the values for a&b 10 20
The value of m is 200

3. Functions with no argument and one return value


Passes no arguments but the called function returns a value of the function call/calling function.

Function1() Function2(f)
{ {
--------------- ---------------

--------------- ---------------
Function2(a); result Return(e);
} }

Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int c;
clrscr();
c=add();
printf(“The value of c
is%d”,c); getch();

}
int add()
{
16
int x,y,z;
printf(“Enter the values for x &
y”); scanf(“%d%d”,&x,&y);
z=x+y;
return(z);
}
The output is: Enter the values for x & y 10 20
The value of c is 30

4. Functions with argument and one return value.


Passes arguments but the called function returns a value of the function call/calling function.
Two way communication.

Function1() argument Function2(f)


{ {
--------------- ---------------

--------------- ---------------
Function2(a); result Return(e);
} }

Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
clrscr();
x=int div(10,2);
printf(“The value of x
is%d”,x); getch();

}
int div(int a, int b)
{
int c;
c=a/b;
17
return(c);
}
The output is: The value of x is 5.

5. Functions with argument and multiple return values


Passes arguments and the called function returns a value of the function call/calling function. Two
way communication.

Function1() argument Function2(f)


{ {

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

--------------- ---------------
Function2(a); result Return(e);
} }
Eg:
#include<stdio.h>
#include<conio.h>
void maths(int x,int y,int *s,int
*d); void main()
{
int x=20,y=10,s,d;
clrscr();
maths(x,y,&s,&d);
printf(“The value of s is%d”,s);
printf(“\n The value of d
is%d”,d); getch();
}
void maths(int a,int b,int *sum,int *diff)
{
*sum=a+b;
*diff=a-b;
}
The output is: The value of s is 30.

The value of d is 10

18
In the program, *s denotes address of s and &s denotes value of s. value of a+b is stored in address of
s. value of a-b is stored in address of d and finally printed.
Recursion:
A function calling itself is called recursion.
Eg:
main()
{
printf(“example”);
main();
}

File Management In C
 File is a technique to store the information in the Secondary Storage Device (SSD). Informations
are permanent. 

 The informations available in the program are stored in the memory without using a file.. 

 Place on the disk where a group of related data is stored and data can be read whenever necessary 

File operations 

Naming, opening, reading from, writing to, closing 

The four steps needed for writing a file program


Step 1: Declaring the filepointer
Declaring the file pointer by using the format is
FILE*filepointername;
 filepointername denotes the pointer which points to the address of the latest information stored
in the file. 

 Initially, the filepointer value is null since there is no data in the file. When the data is written
in the file, the file pointer moves to the lastly accessed data. 

Step 2: Opening a file


If we want to perform an operation on a file, the file must be opened. To open a file by using
the format is
filepointername = fopen(“filename”,”mode”);
where the mode may be 3 types , we can use anyone at time. They are
w for writing an information into the file
r for reading an information from the file
a for appending an information into the file. When file is opened in the
19
append mode, the file is opened for writing without deleting the
already data if present

Note:
w – a file with specified name is created if the file contents deleted, if the file
exists. r – if exists file is opened with the current content safe otherwise error.
a – file opened with the current contents safe. a file created if not exists .
. Step 3: Input and output operation
After the file is open, we can perform the input & output operation.
Input / Output Operations for file
Character Function: Used to read & write character
functions. getc() & putc()
getc() – Read the single character from the text file and assigned to c.
c= getc(fp)
putc() - Handles one char at a time. Writes a char to the file opened with write mode
putc(c,fp)
fp - filepointer
The getc will return an end of file markers EOF when end of file has been reached. So
reading should be terminated when EOF is encountered
Integer Function: Used to read & write integer
functions. getw() & putw()
getw() – Read the integer value from the file and assigned to
n. n= getw(fp)
putw() - Writes a integer to the file opened with write mode
putw(n,fp)
Mixed Data File Input and Output: Used to read and write more than one different data at time.
Like character , float and integer.
fprintf and fscanf
 Can handle a group of mixed data. 

 Similar to printf & scanf. 
Syntax :
fscanf(fp,”format specification”,&variable);
fprintf(fp,”format specification”,variable);
Eg:
fprintf(f1,”%s%d%f”,name, age,7.5);
fscanf(f2,”%s%d”,item,&quantity);
There is no & symbol for string variable.
Step 4: Close a file
20
After the operation is performed on a file ,the file must be cosed.
Syntax : fclose(file-pointer);
 file must be closed as soon as all operations are over. 

 All outstanding information flushed out from buffers, links are broken. 

 Prevents any accidental misuse. 

 Close the file when we want to reopen the same file in different mode. 
File input/output function in c library

fopen() – Creates a new file opens.


fclose() – Closes which has been opened for
use. getc() – Reads a char from file.
putc() – Writes a char to file.
fscanf() – Reads a set of data values from a
file. fprintf() – Write a set of data values into a
file getw() – Read an integer.
putw() – Write an integer.
fseek() – Used to move the filepointer to the specified location randomly.accessing a file randomly.
Syntax: fseek(filepointer,offset,position);
Offset – Specifies the number of positions to be moved from the current
location. Offset may be positive or negative
Offset – positive – moving forward.
Negative - backward.
Position – Position may be 0,1,2
0 – if the move from the beginning of the file. 1 –
fp is to be moved from the current position. 2 –
fp is to be moved from nd of the file.
Eg: fseek(f1,4,0) – moves the fp to the 5 th byte in the file from beginning of the file(forwardmore).
fseek(fp,OL,O) - Goto begin
fseek(fp,m,o) – Move to (m+1)th byte.
fseek(fp,m,1) – Go forward by m bytes.
fseek(Fp,-m,1)- Go backward current
fseek(Fp,-m,2) – Go backward from end.
If open is success return 0, otherwise -1.
ftell() – It returns the current position in file. (in terms of bytes)
Syntax: N=ftell(fp);
N will be 0.
 First byte will be number as 0 , second as 1 ,….. 

 Helps in reading a file more than once, without having to close & open the file. 
21
When a file is opened rewind is done
implicitly.rewind() – Used to move the filepointer to the beginning
of the file.
Syntax: rewind(fp);

Error Handling During Input/Output:


Error which may occur during input/output operations on a
file. 1.trying to read beyond EOF.
2. trying to use a file that has not been opened.
3. trying to perform an op. when the file is opened for another type of operation.
4. opening a file with an invalid filename
5. attempting to write to a write. Protected file .
If we fail to check such errors a programs behave
abnormally. feof:
 Test an end of file condition 

 Returns nonzero int if all data from the specified file has been read & returns
zero otherwise. 

Eg:
if(feof(fp)) printf(“end
of data”);
ferror()
Report the states of file.
Returns nonzero if an error occurs up to that pt. zero otherwise.
Eg:
if(ferror(fp)!=0)
printf(“error”);

NULL pointer:
 While using fopen, if the file cannot be opened then it returns a null pointed. 

 Used to test whether the file has been opened or not. 
Eg
if(fp==NULL)
Printf(“File cannot be opened”);
Eg:2
If((fp2 =fopen(filename,”r”))==NULL)
Printf(“cannot open”);
Eg program:
// Creating a text file
22
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp=fopen(“sample.txt”,”w”);
while((c=getc(fp))!=”EOF”)
putc(c,fp);
fclose(fp);
}

ASSIGNMENT QUESTIONS

1. What is C function?
2. Uses of C functions
3. C function declaration, function call and definition with example program
4. How to call C functions in a program?
1. Call by value
2. Call by reference
5. C function arguments and return values
1. C function with arguments and with return value
2. C function with arguments and without return value
3. C function without arguments and without return value ===
4. C function without arguments and with return value
6. Types of C functions
1. Library functions in C
2. User defined functions in C
7. What is file pointer in C?
8. What is the purpose of type FILE?
9. What is the purpose of function fopen() and fclose()?
10. Describe the syntax of function fopen()?
11. What is the purpose of functions fread() and fwrite()?
12. What file modes can be used by the function fopen()?
13. What are functions fprintf() and fscanf()?
14. What are getc() and putc() functions?
15. What does SEEK_SET, SEEK_CUR and SEEK_END mean in the declaration of fseek().
16. C Program to read name and marks of students and store it in file.
17. C Program to read name and marks of students and store it in file. If file already exists, add information to
it.
18. C Program to write members of arrays to a file using fwrite().
19. Explain the steps to write a file program.
23
20. Write the syntax for fseek().

REFERENCE LINK http://www.cquestions.com/2012/02/c-questions-and-


answers.html http://edugrip.blogspot.in/2012/09/c-language-multiple-choice-
questions.html
http://www.peoi.org/Courses/Coursesen/cprog/frame13.html

24

You might also like