Академический Документы
Профессиональный Документы
Культура Документы
*stream)
#include <stdio.h>
int main()
FILE *fp;
char str[60];
fp = fopen("file.txt" , "r");
if(fp == NULL)
return(-1);
puts(str);
fclose(fp);
1
return(0);
#include<stdio.h>
int main()
{
/* 2D array declaration*/
int disp[3][5];
2
printf("Enter value for disp[%d][%d]:",
i, j);
scanf("%d", &disp[i][j]);
}
}
return 0;
}
Initialization of 2D Array
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR
3
Things which you must consider while
initializing 2D array –
You must remember that when we give values
during one dimensional array declaration, we
don’t need to mention dimension. But that’s not
the case with 2D array; you must specify the
second dimension even if you are giving values
during the declaration. Let’s understand this with
the help of few examples –
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second
dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned
above*/
int abc[2][] = {1, 2, 3 ,4 }
4
Store Data into 2D array
...
int abc[5][4];
.....
/*loop for first dimension which is 5 here*/
for(i=0; i<=4; i++)
{
/*loop for second dimension of array which is
4 in this example*/
for(j=0;j<=3;j++)
{
printf("Enter value for abc[%d][%d]:", i,
j);
scanf(“%d”, &abc[i][j]);
}
}
In above example, I have a 2D array – abc of
integer type. I have used nested for loops to store
data. Conceptually you can consider above array
like this –
5
However the actual representation of this array in
memory would be something like –
6
Pointers & 2D array
7
So abc[0] would represent the address of first
element in the first row (if we consider the above
first diagram).
similarly abc[1] would have the address for second
row. To understand it better, lets write a program
–
#include <stdio.h>
int main()
{
int abc[5][4] ={
{0,1,2,3},
{4,5,6,7},
{8,9,10,11},
{12,13,14,15},
{16,17,18,19}
};
for (int i=0; i<=3; i++)
{
printf("%d ",abc[i]);
}
return 0;
}
8
If we consider the memory representation of
above diagram then the output would be –
88202 88218 88234 88250 88266
The above are the addresses of abc[0][0], abc[1]
[0], abc[2][0], abc[3][0] and abc[4][0].
9
Types of functions
10
Syntax of Defining a function
11
Above terms are confusing? – Do not worry I’m
not gonna end this post until you learn all of
them
So let’s discuss a problem theoretically – Suppose
you want to create a function which would add
two integer variables.
Let me split the problem so that it would be
easy to learn –
Function will sum up two numbers so it’s name
should be sum, addition, etc… I’m taking name as
addition. The signature would look like –
return_type addition(argument list)
My function is going to add two integer variables,
which means I need two integer variable as input,
my function signature would be – I got my
argument list –
return_type addition(int num1, int num2)
The result of the sum of two integers would be
integer only. Hence function should return an
integer value – I got my return type – It should be
integer –
12
int addition(int num1, int num2);
So you got your function prototype or signature.
Now you can add logic to that in the below
example-
int main()
13
{
int var1, var2;
printf("enter number 1: ");
scanf("%d",&var1);
printf("enter number 2: ");
scanf("%d",&var2);
return 0;
}
Example2:
/* function return type is void and doesn't have
parameters*/
void introduction()
{
printf("Hi\n");
printf("My name is Chaitanya\n");
14
printf("How are you?");
/* there is no return statement inside this
function, since its
* return type is void */
}
int main()
{
/*calling function*/
introduction();
return 0;
}
Output:
Hi
My name is Chaitanya
How are you?
Few Points to Note:
1) main () in C program is also a function.
2) Each C program must have at least one
function, which is main ().
3) There is no limit on number of functions; A C
program can have any number of functions.
15
4) A function can call itself and it is known as
“Recursion“. I have written a separate post for it.
Terminologies –which you shouldn’t forget
return type: Data type of returned value. It can
be void also, in such case function doesn’t return
any value.
Note: for example, function’s return type
is char, then function should return a value of
char type and while calling this function the
main() function should have a variable of char
data type to store the returned value.
Structure would look like –
int main()
{
16
…
char c1 = abc('a', 'x');
…
}
Further readings
1) Function – Call by value method – In the call
by value method the actual arguments are copied
to the formal arguments, hence any operation
performed by function on arguments doesn’t
affect actual parameters.
2) Function – Call by reference method – Unlike
call by value, in this method, address of actual
arguments (or parameters) is passed to the formal
parameters, which means any operation
performed on formal parameters affects the value
of actual parameters.
17
Formal arguments: while declaring a function,
the arguments list of parameters we specify are
known as formal parameters.
Actual arguments: The parameter’s value (or
arguments) we provide while calling a function is
known as actual arguments.
For example:
int sum(int a, int b)
{
int c=a+b;
return c;
}
int main(
{
int var1 =10;
int var2 = 20;
int var3 = sum(var1, var2);
printf("%d", var3);
return 0;
}
18
In the above example variable a and b are the
formal parameters (or formal arguments). Variable
var1 and var2 are the actual arguments (or actual
parameters).
Call by Value
int main()
{
19
int num1=20;
int num2 = increment(num1);
printf("num1 value is: %d", num1);
printf("num2 value is: %d", num2);
return 0;
}
Output:
20
printf("Before swapping: num1 value is %d and
num2 value is %d", num1, num2);
}
Output:
21
After swapping: num1 value is 35 and num2 value is
45
After swapping: num1 value is 35 and num2 value is
45
Why values remain unchanged even after the
swap?
The reason is same – function is called by value for
num1 & num2. So actually var1 and var2 gets
swapped (not num1 & num2). As in call by value
actual parameters are just copied into the formal
parameters.
22
Consider a small C program first
–
int main()
{
/* Pointer to the file */
FILE *fp1;
/* Character variable to read the content of
file */
char c;
23
}
fclose(fp1);
return 0;
}
The above program is opening a
file MYFILE.C in r mode, reading the content of the
file and displaying it on the console. lets
understand the each operation in detail –
Opening a file
24
fp = fopen("MYABC.C", "r");
Above code will open a file MYABC.C in r mode
(read only mode). The address of the first
character is stored in pointer fp.
How to track whether file has opened
successfully?
As I discussed above, If file is not being open then
the pointer will be having NULL so the below code
would help you to track the status –
..
FILE fpr;
fpr = fopen("FILENAME.C", "r");
if (fpr == NULL)
{
puts("Error while opening file");
exit();
}
25
the need of the program-
Mode “r”: It is a read only mode, which means if
the file is opened in r mode, it won’t allow you to
write and modify content of it. When fopen()opens
a file successfully then it returns a pointer to the
location, where the file has been loaded otherwise
returns NULL.
Pointer location: On successful opening of file,
the fopen() function returns a pointer, which
points to the first character of the file.
Mode “w”: It is a write only
mode. fopen() creates a new file when the
specified file doesn’t exist and if it fails to open
file then it returns NULL.
Mode “a”: Using this mode Content can be
appended at the end of an existing file. Like Mode
“w”, fopen() creates a new file if it file doesn’t
exist. On unsuccessful open it returns NULL.
Pointer location: At the last character of the file.
Mode “r+”: This mode is same as mode “r”;
however you can perform various operations on
the file opened in this mode. You are allowed to
read, write and modify the content of file opened
26
in “r+” mode.
Pointer location: First character of the file.
Mode “w+”: Same as mode “w” apart from
operations, which can be performed; the file can
be read, write and modified in this mode.
Mode “a+”: Same as mode “a”; you can read and
append the data in the file, however content
modification is not allowed in this mode.
Reading a File
In order to read, the file must be
opened. fopen() returns the address of the file’s
element based on the mode, in which it has been
open.
In our example, we have opened a file MYFILE.C in
r mode. Pointer fp1 is having the address of the
first element of the file. We have used a
functionfgetc() to read the file.
fgetc ( ): This function reads the character from
current pointer’s position and upon successful
reading moves the pointer to next character in the
file. Upon reaching to the end of the file this
function returns EOF (End of File). We have
27
used EOF in our program to determine the end of
the file. This is almost similar to getc() function.
In general, below code is sufficient for reading a
file in r mode –
..
char ch;
while(1)
{
/* reading the current character in variable
ch and
* moving the pointer forward to point next
character*/
ch = fgetc(fp);
28
/*here I can use any logic, I may write the
content in another file
*or I can display it on console*/
printf("%c", ch);
}
..
29
FILE fpw = fopen("MYFILE2.C", "w");
Closing a file
Code –
fclose(fp);
fclose( ) function is used for closing an opened
file. As an argument you must provide a pointer of
FILE type, which is currently pointing to a file.
30
Now you have understood all the three main
operations on the file, Let’s use all three in one C
program – I’ll copy content of FILE1.C to FILE2.C
#include <stdio.h>
int main()
{
char ch;
31
fpw= fopen("FILE2.C", "w");
32
return 0;
}
#include <stdio.h>
int main()
{
FILE *fpr;
/*Char array to store strings */
char str[100];
33
/*Opening the file in "r" mode*/
fpr = fopen("FILER.TXT", "r");
34
now – Do you see fgets function in above example?
Let’s talk about it in detail –
In general –
char *fgets(char *s, int rec_len, FILE *fpr)
s – Array of characters to store strings.
rec_len – Length of the input record.
fpr – Pointer to the input file.
Why I used if(fgets(str, 10, fpr)==NULL as a logic
to determine end of the file?
In previous tutorial we have used ch==EOF to get
to know the end of the file. Here we have used
this logic because fgets returns NULL when there
is no more records are available to be read.
35
int fputs ( const char * s, FILE * fpw );
Sample program –
#include <stdio.h>
int main()
{
FILE *fpw;
36
/*Stored the input string into array – str*/
gets(str);
37
Point to note about fputs:
fputs by default doesn’t add new line after writing
each record, in order to do that manually – you
can have the below statement after each write to
the file.
fputs("\n", fpw);
38
{
char ch;
39
puts("Output binary file is having issues
while opening");
}
return 0;
}
40
Switch case statements mostly used when we
have number of options (or choices) and we may
need to perform a different task for each choice.
Structure of switch case would look like this –
switch (variable or an integer expression)
{
case constant:
//C code
;
case constant:
//C code
;
default:
//C code
;
}
Actual code would be like this –
int main()
{
int num=2;
switch(num+2)
{
case 1:
41
printf("Case1: Value is: %d", num);
case 2:
printf("Case1: Value is: %d", num);
case 3:
printf("Case1: Value is: %d", num);
default:
printf("Default: Value is: %d", num);
}
return 0;
}
Output:
Default: value is: 2
Explanation: In switch I gave an expression, you
can give variable also. I gave num+2, where num
value is 2 and after addition the expression
resulted 4. Since there is no case defined with
value 4 the default case got executed.
So what exactly a switch does?
It evaluates the value of expression or variable
(based on whatever is given inside switch braces),
then based on the outcome it executes the
corresponding case.
42
43
Twist in a story – Introducing
Break statement
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
case 2:
printf("Case2 ");
case 3:
printf("Case3 ");
case 4:
printf("Case4 ");
default:
printf("Default ");
}
return 0;
44
}
Output:
Case2 Case3 Case4 Default
Is that what you guessed? If yes then you can skip
the below paragraph otherwise read it carefully –
I passed a variable to switch, which had the value
2 so the control jumped to the case 2, However
since there are no such statements in the above
program which could break the flow. That’s the
reason after case 2 program execution happens in
a flow and all subsequent cases and default
statements got executed.
Break statement
45
Whenever a break statement is encountered in the
switch body, the execution flow would directly
come out of the switch.
Example:
I’m taking the same above example but I will use
break statements –
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
46
break;
default:
printf("Default ");
}
return 0;
}
Output:
Case 2
Why didn’t I use break statement after default?
The control would itself come out of the switch
after default so I didn’t use it, however if you still
want to use the break after default then you can
use it, there is no harm in doing that.
47
2) You can also use characters in switch case. for
example –
int main()
{
char ch='b';
switch (ch)
{
case 'd':
printf("CaseD ");
break;
case 'b':
printf("CaseB");
break;
case 'c':
printf("CaseC");
break;
case 'z':
printf("CaseZ ");
break;
default:
printf("Default ");
}
48
return 0;
}
Output:
CaseB
3) The expression provided in the switch should
result in a constant value otherwise it would not
be valid.
For example:
Valid expressions for switch –
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions –
switch(ab+cd)
switch(a+b+c)
49
void recursion() {
int main() {
recursion();
Number Factorial
The following example calculates the
factorial of a given number using a recursive
function −
50
#include <stdio.h>
if(i <= 1) {
return 1;
int main() {
int i = 15;
return 0;
Factorial of 15 is 2004310016
Fibonacci Series
51
The following example generates the
Fibonacci series for a given number using a
recursive function −
#include <stdio.h>
int fibonaci(int i) {
if(i == 0) {
return 0;
if(i == 1) {
return 1;
int main() {
int i;
52
printf("%d\t\n", fibonaci(i));
return 0;
Opening Files
53
You can use the fopen( ) function to create
a new file or to open an existing file. This
call will initialize an object of the type FILE,
which contains all the information necessary
to control the stream. The prototype of this
function call is as follows −
Mode Description
54
r+ Opens a text file for both reading and writing.
w+ Opens a text file for both reading and writing. It first tru
zero length if it exists, otherwise creates a file if it does n
Closing a File
To close a file, use the fclose( ) function.
The prototype of this function is −
55
file, closes the file, and releases any
memory used for the file. The EOF is a
constant defined in the header file stdio.h.
Writing a File
Following is the simplest function to write
individual characters to a stream −
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fclose(fp);
57
/tmp directory and writes two lines using
two different functions. Let us read this file
in the next section.
Reading a File
Given below is the simplest function to read
a single character from a file −
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
59
fgets(buff, 255, (FILE*)fp);
fclose(fp);
1 : This
2: is testing for fprintf...
60