100% found this document useful (1 vote)
204 views83 pages

C Tutorial

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 83

C Tutorial – Learn C Programming with

examples
Learning C programming is easy if you follow the tutorials in the given order and
practice C programs along the way. This C tutorial is designed for beginners so
you won’t face any difficulty even if you have no prior knowledge in C language.

C Tutorial
Learn and practice these tutorials in the given order.

Learn C Basics First


Turbo C++ installation: compile and run first C program – Installation guide for
turbo C++. Also, refer this for getting to know the compilation and execution
steps of a C program.
First C Program – What all basic components work together to make a complete
program. Learn little basics of C building blocks.
Keywords in C – List of reserved words and their purpose for C language.

Decision Control Statements in C


If statement – Basic usage, flow and examples of if statements.
If-else statement – Use of If-else in a program. Flow diagram and examples.
Switch-case – How to use switch-case statements in C and what’s the role of
break while using this control structure.

Loops in C
For loop – Examples, flow diagrams and use of for loop in C.
while loop – A guide on While loop usage with flow diagrams and examples.
dowhile loop – All about do-while loop along with differences between while and
dowhile.

C – Loop control statements


Break statement – How and where to use break statement in a C program.
Continue statement – Its syntax, usage along with few C example programs.
Goto statement – How to use goto in a program and why it should be avoided
while developing an application in C.

Array Tutorials in C
Arrays – Array basics.
2D array – How to implement and use a 2D array in program.
Pointer to Array
Passing array to function – Learn passing of an array to a function as an
argument.

C – Strings
Strings and String functions – All about string and string functions. A complete
guide.

Functions in C
C functions – What’s the use of functions and how to implement them in a
program.
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.
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.

Structure
Structures in C – Complete guide for structures in C

Pointer in C Programming
C Pointers – What are pointers and how to use them.
Pointer to pointer – Tutorial on pointer to pointer (Double pointer).
Function Pointers – All about function pointers
Passing pointer to functions – Learn how to pass a pointer to a function.

File I/O
File I/O – Learn how to perform Input/Output operations on files in C. Also, get to
know the handling of text/binary files in a program.

Operator Precedence table


Operator Precedence – Includes various types of operators in C.

C Examples
C examples

C Tutorials on Library functions


strcat() | strncat() | strchr() | strcmp() | strncmp() | strcoll() | strcpy() | strncpy() | str
rchr() | strspn() | strstr() | strcspn() | strlen()

Next

How to install Turbo C++: Compile and Run


a C Program
First thing you need to understand is that computer (Machine) can only
understand Machine language (Stream of 0s and 1s). In order to convert your C
program source code to Machine code, you need to compile it. Compiler is the
one, which converts source code to Machine code. In simple words you can say
that a compiler converts human readable code to a machine readable format.

Install Turbo C++: Step by Step Guide


Download link: Download Turbo C++ for Windows

Step 1: Locate the TC.exe file and open it. You will find it at location C:\TC\BIN\.

Step 2: File > New (as shown in above picture) and then write your C program

#include<stdio.h>
int main()
{
printf("hello World!");
return 0;
}

Step 3: Save the program using F2 (OR file > Save), remember the extension
should be “.c”. In the below screenshot I have given the name as helloworld.c.

Step 4: Compile the program using Alt + F9 OR Compile > Compile (as shown in
the below screenshot).
Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C
program.

Step 6: Alt+F5 to view the output of the program at the output screen.

Compile and Run C program using gcc compiler


We have seen the steps to compile and execute a C program using Turbo C++.
We can also do the same using gcc compiler. The steps are as follows:

Source code Helloworld.c (file should always be saved with .c extension)

# include<stdio.h>
int main()
{
puts ("hello World");
return 0;
}
Compile it (it is basically converting a helloworld.c file to a helloworld file)

>gcc helloworld.c –o helloworld


>
The generated file would be helloworld.exe if you are compiling on windows.

Run the compiled program


Once you give the above command, a .exe file would have been created if you
are on windows then type the following command to run the source code.

For Windows

>helloworld
For Mac and Linux OS

>./helloworld
gcc compiler took the human readable format (helloworld.c file) and converted
into a machine code for Windows, Linux and Mac OS X.

C Program Structure – First C Program


A C program source code can be written in any text editor; however the file
should be saved with .c extension. Lets write the First C program.

First C Program
/* Demo Program written on BeginnersBook.com*/
#include<stdio.h>
int main()
{
int num;
printf("Enter your age: ");
scanf("%d", &num);
if (num <18)
{
printf("you are not eligible for voting");
}
else
{
printf("You can do this!!");
}
return 0;
}
Output:

Enter your age: 27

You can do this

Lets understand this Program:


Comment: Comment start with’ /*’ and end with ‘*/’. Comments are not
mandatory but still it’s a good practice if you use them, it improves the readability
of the code. A program can have any number of comments.

Include section: While writing program we use several keywords & statements
and functions such as printf(), scanf() etc. The file that has definitions of these
functions needs to be included in the program. In the above program we have
used stdio.h.There are several libraries and “stdio.h” is one of them, which is used
for reading the data from terminal and to display the data on terminal.

Display statements: printf function is used in couple of places in the above code.
Whatever you gives inside double quotes, it prints as it is at the console. You can
also use format specifiers such as %d, %c, %p to display the values of the
variables and pointers using printf.

Take input from the user: scanf function is used to take the input from the user.
When you run this program, it waits for a user input (age) and once user enters
the age, it does the processing of rest of the statements based on the age input
by user.

Main() function: It is the starting point of all the C programs. The execution of C
source code begins with this function.

More about main () Function in C program


The main () function should be present in all C programs as your program won’t
begin without this function.
Return type of main () function: The return type for main () function should
always be int.

Why it has a return type and what’s the need of it? The compiler should know
whether your program compiled successfully or it has failed. In order to know this
it checks the return value of function main (). If return value is 0 then it means that
the program is successful otherwise it assumes that there is a problem, this is
why we have a return 0 statement at the end of the main function.

Structure of main function: Function name is followed by return type. There


should be close parenthesis after function name. If there are parameters or
arguments then it must be within this parenthesis. The block of code inside
braces is function body. We will discuss more about functions in the separate
tutorial: Functions in C Programming.

C Keywords – Reserved Words


In C, we have 32 keywords, which have their predefined meaning and cannot be
used as a variable name. These words are also known as “reserved words”. It is
good practice to avoid using these keywords as variable name. These are –
Basics usage of these keywords –

if, else, switch, case, default – Used for decision control programming structure.

break – Used with any loop OR switch case.

int, float, char, double, long – These are the data types and used during variable
declaration.

for, while, do – types of loop structures in C.

void – One of the return type.

goto – Used for redirecting the flow of execution.

auto, signed, const, extern, register, unsigned – defines a variable.


return – This keyword is used for returning a value.

continue – It is generally used with for, while and dowhile loops, when compiler
encounters this statement it performs the next iteration of the loop, skipping rest
of the statements of current iteration.

enum – Set of constants.

sizeof – It is used to know the size.

struct, typedef – Both of these keywords used in structures (Grouping of data


types in a single record).

union – It is a collection of variables, which shares the same memory location


and memory storage.

volatile

Decision Control Statements in C

If statement in C programming with


example
When we need to execute a block of statements only when a given condition is
true then we use if statement. In the next tutorial, we will learn C if..else, nested
if..else and else..if.

C – If statement
Syntax of if statement:
The statements inside the body of “if” only execute if the given condition returns
true. If the condition returns false then the statements inside “if” are skipped.

if (condition)
{
//Block of C statements here
//These statements will only execute if the condition is true
}

Flow Chart of if statement

Example of if statement
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}

Variable x is less than y


Explanation: The condition (x<y) specified in the “if” returns true for the value of
x and y, so the statement inside the body of if is executed.
Example of multiple if statements
We can use multiple if statements to check more than one conditions.

#include <stdio.h>
int main()
{
int x, y;
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
if (x<y)
{
printf("x is less than y\n");
}
if (x==y)
{
printf("x is equal to y\n");
}
printf("End of Program");
return 0;
}
In the above example the output depends on the user input.

Output:

Enter the value of x:39

Enter the value of y:39

X is equal to y

C – If..else, Nested If..else and else..if


Statement with example
In the last tutorial we learned how to use if statement in C. In this guide, we will
learn how to use if else, nested if else and else if statements in a C Program.

C If else statement
Syntax of if else statement:
If condition returns true then the statements inside the body of “if” are executed
and the statements inside body of “else” are skipped.
If condition returns false then the statements inside the body of “if” are skipped
and the statements in “else” are executed.

if(condition) {
// Statements inside body of if
}
else {
//Statements inside body of else
}
Flow Chart of if else statement

Example of if else statement


In this program user is asked to enter the age and based on the input, the if..else
statement checks whether the entered age is greater than or equal to 18. If this
condition meet then display message “You are eligible for voting”, however if the
condition doesn’t meet then display a different message “You are not eligible for

#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible to do this");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible to do this");
}
return 0;
}
Output:

Enter your age:13


You are not eligible to do this

Note: If there is only one statement is present in the “if” or “else” body then you
do not need to use the braces (parenthesis). For example the above program
can be rewritten like this:

#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
printf("You are eligible for voting");
else
printf("You are not eligible for voting");
return 0;
}
C Nested If..else statement
When an if else statement is present inside the body of another “if” or “else” then
this is called nested if else.
Syntax of Nested if else statement:

if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Example of nested if..else
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n");
//Nested if else
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:

Input the value of var1:12


Input the value of var2:21
var1 is not equal to var2
var2 is greater than var1
C – else..if statement
The else..if statement is useful when you need to check multiple conditions within
the program, nesting of if-else blocks can be avoided using else..if statement.

Syntax of else..if statement:

if (condition1)
{
//These statements would execute if the condition1 is true
}
else if(condition2)
{
//These statements would execute if the condition2 is true
}
else if (condition3)
{
//These statements would execute if the condition3 is true
}
.
.
else
{
//These statements would execute if all the conditions return false.
}
Example of else..if statement
Lets take the same example that we have seen above while discussing nested
if..else. We will rewrite the same program using else..if statements.

#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2\n");
}
else if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else if (var2 > var1)
{
printf("var2 is greater than var1\n");
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}

Output:

Input the value of parameter 1:13


Input the value of parameter 3:22
parameter 1 is not equal to parameter 3

As you can see that only the statements inside the body of “if” are executed. This
is because in this statement as soon as a condition is satisfied, the statements
inside that block are executed and rest of the blocks are ignored.

Important Points:
1. else and else..if are optional statements, a program having only “if” statement
would run fine.
2. else and else..if cannot be used without the “if”.
3. There can be any number of else..if statement in a if else..if block.
4. If none of the conditions are met then the statements in else block gets
executed.
5. Just like relational operators, we can also use logical operators such as AND
(&&), OR(||) and NOT(!).

C – switch case statement in C Programming


with example
The switch case statement is used when we have multiple options and we need
to perform a different task for each option.

C – Switch Case Statement


Before we see how a switch case statement works in a C program, let’s checkout
the syntax of it.

switch (variable or an integer expression)


{
case constant:
//C Statements
;
case constant:
//C Statements
;
default:
//C Statements
;
}
Flow Chart of Switch Case

#include <stdio.h>
int main()
{
int num=2;
switch(num+2)
{
case 1:
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 is executed.

Before we discuss more about break statement, guess the output of this C
program.

#include <stdio.h>
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;
}
Output:

Case2 Case3 Case4 Default


I passed a variable to switch, the value of the variable is 2 so the control jumped
to the case 2, However there are no such statements in the above program
which could break the flow after the execution of case 2. That’s the reason after
case 2, all the subsequent cases and default statements got executed.

How to avoid this situation?


We can use break statement to break the flow of control after every case block.

Break statement in Switch Case


Break statements are useful when you want your program-flow to come out of
the switch body. Whenever a break statement is encountered in the switch body,
the control comes out of the switch case statement.
Example of Switch Case with break
I’m taking the same above that we have seen above but this time we are using
break.

#include <stdio.h>
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 ");
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 want to use the break after default then you can use it, there is no
harm in doing that.

Few Important points regarding Switch Case


1) Case doesn’t always need to have order 1, 2, 3 and so on. They can have any
integer value after case keyword. Also, case doesn’t need to be in an ascending
order always, you can specify them in any order as per the need of the program.

2) You can also use characters in switch case. for example –

#include <stdio.h>
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 ");
}
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)
4) Nesting of switch statements are allowed, which means you can have switch
statements inside another switch. However nested switch statements should be
avoided as it makes program more complex and less readable.
5) Duplicate case values are not allowed. For example, the following program is
incorrect:
This program is wrong because we have two case ‘A’ here which is wrong as we
cannot have duplicate case values.

#include <stdio.h>
int main()
{
char ch='B';
switch (ch)
{
case 'A':
printf("CaseA");
break;
case 'A':
printf("CaseA");
break;
case 'B':
printf("CaseB");
break;
case 'C':
printf("CaseC ");
break;
default:
printf("Default ");
}
return 0;
}
6) The default statement is optional, if you don’t have a default in the program, it
would run just fine without any issues. However it is a good practice to have a
default statement so that the default executes if no case is matched. This is
especially useful when we are taking input from user for the case choices, since
user can sometime enter wrong value, we can remind the user with a proper
error message that we can set in the default statement.

Loops in C

C – for loop in C programming with example


A loop is used for executing a block of statements repeatedly until a given
condition returns false.

C For loop
This is one of the most frequently used loop in C programming.
Syntax of for loop:

for (initialization; condition test; increment or decrement)


{
//Statements to be executed repeatedly
}

Flow Chart of For loop


Step 1: First initialization happens and the counter variable gets initialized.
Step 2: In the second step the condition is checked, where the counter variable
is tested for the given condition, if the condition returns true then the C
statements inside the body of for loop gets executed, if the condition returns false
then the for loop gets terminated and the control comes out of the loop.
Step 3: After successful execution of statements inside the body of loop, the
counter variable is incremented or decremented, depending on the operation (++
or –).

Example of For loop


#include <stdio.h>
int main()
{
int i;
for (i=1; i<=3; i++)
{
printf("%d\n", i);
}
return 0;
}

1
2
3
Various forms of for loop in C
I am using variable num as the counter in all the following examples –
1) Here instead of num++, I’m using num=num+1 which is same as num++.

for (num=10; num<20; num=num+1)


2) Initialization part can be skipped from loop as shown below, the counter
variable is declared before the loop.

int num=10;
for (;num<20;num++)
Note: Even though we can skip initialization part but semicolon (;) before
condition is must, without which you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this
case semicolon (;) is must after condition logic. In this case the increment or
decrement part is done inside the loop.

for (num=10; num<20; )


{
//Statements
num++;
}
4) This is also possible. The counter variable is initialized before the loop and
incremented inside the loop.

int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) As mentioned above, the counter variable can be decremented as well. In the
below example the variable gets decremented each time the loop runs until the
condition num>10 returns false.

for(num=20; num>10; num--)


Nested For Loop in C
Nesting of loop is also possible. Lets take an example to understand this:

#include <stdio.h>
int main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %d\n",i ,j);
}
}
return 0;
}
Output:

0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
In the above example we have a for loop inside another for loop, this is called
nesting of loops. One of the example where we use nested for loop is Two
dimensional array.

Multiple initialization inside for Loop in C


We can have multiple initialization in the for loop as shown below.

for (i=1,j=1;i<10 && j<10; i++, j++)


What’s the difference between above for loop and a simple for loop?
1. It is initializing two variables. Note: both are separated by comma (,).
2. It has two test conditions joined together using AND (&&) logical operator.
Note: You cannot use multiple test conditions separated by comma, you must
use logical operator such as && or || to join conditions.
3. It has two variables in increment part. Note: Should be separated by comma.

Example of for loop with multiple test conditions


#include <stdio.h>
int main()
{
int i,j;
for (i=1,j=1 ; i<3 || j<5; i++,j++)
{
printf("%d, %d\n",i ,j);
}
return 0;
}
C – while loop in C programming with
example
A loop is used for executing a block of statements repeatedly until a given
condition returns false. In the previous tutorial we learned for loop. In this guide
we will learn while loop in C.

C – while loop
Syntax of while loop:

while (condition test)


{
//Statements to be executed repeatedly
// Increment (++) or Decrement (--) Operation
}
Flow Chart of while loop

Example of while loop


#include <stdio.h>
int main()
{
int count=1;
while (count <= 4)
{
printf("%d ", count);
count++;
}
return 0;
}

1 2 3 4
step1: The variable count is initialized with value 1 and then it has been tested
for the condition.
step2: If the condition returns true then the statements inside the body of while
loop are executed else control comes out of the loop.
step3: The value of count is incremented using ++ operator then it has been
tested again for the loop condition.

Guess the output of this while loop

#include <stdio.h>
int main()
{
int var=1;
while (var <=2)
{
printf("%d ", var);
}
}
The program is an example

Use of Logical operators in while loop


Just like relational operators (<, >, >=, <=, ! =, ==), we can also use logical
operators in while loop. The following scenarios are valid :

while(num1<=10 && num2<=10)


-using AND(&&) operator, which means both the conditions should be true.

while(num1<=10||num2<=10)
– OR(||) operator, this loop will run until both conditions return false.

while(num1!=num2 &&num1 <=num2)


– Here we are using two logical operators NOT (!) and AND(&&).

while(num1!=10 ||num2>=num1)
Example of while loop using logical operator
In this example we are testing multiple conditions using logical operator inside
while loop.

#include <stdio.h>
int main()
{
int i=1, j=1;
while (i <= 4 || j <= 3)
{
printf("%d %d\n",i, j);
i++;
j++;
}
return 0;
}
Output:

1 1
2 2
3 3
4 4

C – do while loop in C programming with


example
In the previous tutorial we learned while loop in C. A do while loop is similar to
while loop with one exception that it executes the statements inside the body of
do-while before checking the condition. On the other hand in the while loop, first
the condition is checked and then the statements in while loop are executed. So
you can say that if a condition is false at the first place then the do while would
run once, however the while loop would not run at all.
C – do..while loop
Syntax of do-while loop

do
{
//Statements

}while(condition test);
Flow Chart of do while loop

Example of do while loop


#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=3);
return 0;
}

Value of variable j is: 0


Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3
While vs do..while loop in C
Using while loop:

#include <stdio.h>
int main()
{
int i=0;
while(i==1)
{
printf("while vs do-while");
}
printf("Out of loop");
}
Output:

Out of loop
Same example using do-while loop

#include <stdio.h>
int main()
{
int i=0;
do
{
printf("while vs do-while\n");
}while(i==1);
printf("Out of loop");
}
Output:

while vs do-while
Out of loop
Explanation: As I mentioned in the beginning of this guide that do-while runs at
least once even if the condition is false because the condition is evaluated, after
the execution of the body of loop.
C – Loop control statements

C – break statement in C programming


The break statement is used inside loops and switch case.

C – break statement
1. It is used to come out of the loop instantly. When a break statement is
encountered inside a loop, the control directly comes out of loop and the loop
gets terminated. It is used with if statement, whenever used inside loop.
2. This can also be used in switch case control structure. Whenever it is
encountered in switch-case block, the control comes out of the switch-case(see
the example below).

Flow Chart of break statement


Syntax:

break;
Example – Use of break in a while loop
#include <stdio.h>
int main()
{
int num =0;
while(num<=100)
{
printf("value of variable num is: %d\n", num);
if (num==2)
{
break;
}
num++;
}
printf("Out of while-loop");
return 0;
}
Output:

value of variable num is: 0


value of variable num is: 1
value of variable num is: 2
Out of while-loop
Example – Use of break in a for loop
#include <stdio.h>
int main()
{
int var;
for (var =100; var>=10; var --)
{
printf("var: %d\n", var);
if (var==99)
{
break;
}
}
printf("Out of for-loop");
return 0;
}
Output:

var: 100
var: 99
Out of for-loop
Example – Use of break statement in switch-case
#include <stdio.h>
int main()
{
int num;
printf("Enter value of num:");
scanf("%d",&num);
switch (num)
{
case 1:
printf("You have entered value 1\n");
break;
case 2:
printf("You have entered value 2\n");
break;
case 3:
printf("You have entered value 3\n");
break;
default:
printf("Input value is other than 1,2 & 3 ");
}
return 0;
}
Output:

Enter value of num:2


You have entered value 2
You would always want to use break statement in a switch case block, otherwise
once a case block is executed, the rest of the subsequent case blocks will
execute. For example, if we don’t use the break statement after every case block
then the output of this program would be:

Enter value of num:2


You have entered value 2
You have entered value 3
Input value is other than 1,2 & 3

C – continue statement with example


The continue statement is used inside loops. When a continue statement is
encountered inside a loop, control jumps to the beginning of the loop for next
iteration, skipping the execution of statements inside the body of loop for the
current iteration.

C – Continue statement
Syntax:

continue;
Flow diagram of continue statement

Example: continue statement inside for loop


#include <stdio.h>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==4)
{
/* The continue statement is encountered when
* the value of j is equal to 4.
*/
continue;
}

/* This print statement would not execute for the


* loop iteration where j ==4 because in that case
* this statement would be skipped.
*/
printf("%d ", j);
}
return 0;
}

0 1 2 3 5 6 7 8
Value 4 is missing in the output, why? When the value of variable j is 4, the
program encountered a continue statement, which makes the control to jump at
the beginning of the for loop for next iteration, skipping the statements for current
iteration (that’s the reason printf didn’t execute when j is equal to 4).

Example: Use of continue in While loop


In this example we are using continue inside while loop. When using while or do-
while loop you need to place an increment or decrement statement just above
the continue so that the counter value is changed for the next iteration. For
example, if we do not place counter– statement in the body of “if” then the value
of counter would remain 7 indefinitely.

#include <stdio.h>
int main()
{
int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
printf("%d ", counter);
counter--;
}
return 0;
}
Output:

10 9 8 6 5 4 3 2 1 0
The print statement is skipped when counter value was 7.
Another Example of continue in do-While loop
#include <stdio.h>
int main()
{
int j=0;
do
{
if (j==7)
{
j++;
continue;
}
printf("%d ", j);
j++;
}while(j<10);
return 0;
}
Output:

0 1 2 3 4 5 6 8 9

C – goto statement with example


The goto statement is rarely used because it makes program confusing, less
readable and complex. Also, when this is used, the control of the program won’t
be easy to trace, hence it makes testing and debugging difficult.

C – goto statement
When a goto statement is encountered in a C program, the control jumps directly
to the label mentioned in the goto stateemnt
Syntax of goto statement in C

goto label_name;
..
..
label_name: C-statements

Flow Chart of goto


Example of goto statement
#include <stdio.h>
int main()
{
int sum=0;
for(int i = 0; i<=10; i++){
sum = sum+i;
if(i==5){
goto addition;
}
}

addition:
printf("%d", sum);

return 0;
}
Output:

Explanation: In this example, we have a label addition and when the value of i
(inside loop) is equal to 5 then we are jumping to this label using goto. This is
reason the sum is displaying the sum of numbers till 5 even though the loop is
set to run from 0 to 10.

Array Tutorials in C

Arrays in C programming with examples


An array is a group (or collection) of same data types. For example an int array
holds the elements of int types while a float array holds the elements of float
types.

Why we need Array in C Programming?


Consider a scenario where you need to find out the average of 100 integer
numbers entered by user. In C, you have two ways to do this: 1) Define 100
variables with int data type and then perform 100 scanf() operations to store the
entered values in the variables and then at last calculate the average of them. 2)
Have a single integer array to store all the values, loop the array to store all the
entered values in array and later calculate the average.
Which solution is better according to you? Obviously the second solution, it is
convenient to store same data types in one single variable and later access them
using array index (we will discuss that later in this tutorial).

How to declare Array in C


int num[35]; /* An integer array of 35 elements */
char ch[10]; /* An array of characters for 10 elements */
Similarly an array can be of any data type such as double, float, short etc.

How to access element of an array in C


You can use array subscript (or index) to access any element stored in array.
Subscript starts with 0, which means arr[0] represents the first element in the array
arr.

In general arr[n-1] can be used to access nth element of an array. where n is any
integer number.

For example:

int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
Example of Array In C programming to find out the average
of 4 integers
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output:

Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
Lets discuss the important parts of the above program:

Input data into the array


Here we are iterating the array from 0 to 3 because the size of the array is 4.
Inside the loop we are displaying a message to the user to enter the values. All
the input values are stored in the corresponding array elements using scanf
function.

for (x=0; x<4;x++)


{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
Reading out data from an array
Suppose, if we want to display the elements of the array then we can use the for
loop in C like this.

for (x=0; x<4;x++)


{
printf("num[%d]\n", num[x]);
}
Various ways to initialize an array
In the above example, we have just declared the array and later we initialized it
with the values input by user. However you can also initialize the array during
declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};


OR (both are same)

int arr[] = {1, 2, 3, 4, 5};


Un-initialized array always contain garbage values.

C Array – Memory representation


Val[0] val[1] val[2] val[3] val[4] val[5] val[6]

11 22 34 44 55 66 79

89922 89924 89929 89934 89939 89944 89983

All the array elements occupy contigious space in memory.there is a difference of


9 among the addresses of subsequent things,this is because this array is of
integer types and an n integer holds 9 bytes of memory

More Topics on Arrays in C:


2D array – We can have multidimensional arrays in C like 2D and 3D array.
However the most popular and frequently used array is 2D – two dimensional
array. In this post you will learn how to declare, read and write data in 2D array
along with various other features of it.

Passing an array to a function– Generally we pass values and variables while


calling a function, likewise we can also pass arrays to a function. You can pass
array’s element as well as whole array (by just specifying the array name, which
works as a pointer) to a function.

Pointer to array – Array elements can be accessed and manipulated


using pointers in C. Using pointers you can easily handle array. You can have
access of all the elements of an array just by assigning the array’s base address
to pointer variable.

Two dimensional (2D) arrays in C


programming with example

An array of arrays is known as 2D array. The two dimensional (2D) array in C


programming is also known as matrix. A matrix can be represented as a table of
rows and columns. Before we discuss more about two Dimensional array lets
have a look at the following C program.
Two dimensional(2D) Array Example
For now don’t worry how to initialize a two dimensional array, we will discuss that
part later. This program demonstrates how to store the elements entered by user
in a 2d array and how to display the elements of a two dimensional array.

#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
Output:

Enter value for disp[0][0]:1


Enter value for disp[0][1]:2
Enter value for disp[0][2]:3
Enter value for disp[1][0]:4
Enter value for disp[1][1]:5
Enter value for disp[1][2]:6
Two Dimensional array elements:
1 2 3
4 5 6
Initialization of 2D Array
There are two ways to initialize a two Dimensional arrays during declaration.
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR

int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Although both the above declarations are valid, I recommend you to use the first
method as it is more readable, because you can visualize the rows and columns
of 2d array in this method.

Things that you must consider while initializing a 2D array


We already know, when we initialize a normal array (or you can say one
dimensional array) during declaration, we need not to specify the size of it.
However that’s not the case with 2D array, you must always specify the second
dimension even if you are specifying elements 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 }
How to store user input data into 2D array
We can calculate how many elements a two dimensional array can have by using
this formula:
The array arr[n1][n2] can have n1*n2 elements. The array that we have in the
example below is having the dimensions 5 and 4. These dimensions are known
as subscripts. So this array has first subscript value as 5 and second
subscript value as 4.
So the array abc[5][4] can have 5*4 = 20 elements.

To store the elements entered by user we are using two for loops, one of them is
a nested loop. The outer loop runs from 0 to the (first subscript -1) and the inner
for loops runs from 0 to the (second subscript -1). This way the the order in which
user enters the elements would be abc[0][0], abc[0][1], abc[0][2]…so on.

#include<stdio.h>
int main(){
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++) {
for(j=0;j<4;j++) {
printf("Enter value for abc[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
return 0;
}
In above example, I have a 2D array abc of integer type. Conceptually you can
visualize the above array like this:
However the actual representation of this array in memory would be something
like this:

Pointers & 2D array


As we know that the one dimensional array name works as a pointer to the base
element (first element) of the array. However in the case 2D arrays the logic is
slightly different. You can consider a 2D array as collection of several one
dimensional arrays.

So abc[0] would have the address of first element of the first row (if we consider
the above diagram number 1).
similarly abc[1] would have the address of the first element of the second row. To
understand it better, lets write a C 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<=4; i++)
{
/* The correct way of displaying an address would be
* printf("%p ",abc[i]); but for the demonstration
* purpose I am displaying the address in int so that
* you can relate the output with the diagram above that
* shows how many bytes an int element uses and how they
* are stored in contiguous memory locations.
*
*/
printf("%d ",abc[i]);
}
return 0;
}
Output:

1600101376 1600101392 1600101408 1600101424 1600101440


The actual address representation should be in hex for which we use %p instead
of %d, as mentioned in the comments. This is just to show that the elements are
stored in contiguous memory locations. You can relate the output with the
diagram above to see that the difference between these addresses is actually
number of bytes consumed by the elements of that row.

The addresses shown in the output belongs to the first element of each
row abc[0][0], abc[1][0], abc[2][0], abc[3][0] and abc[4][0].
Pointer and Array in C programming with
example
In this guide, we will learn how to work with Pointers and arrays in a C program. I
recommend you to refer Array and Pointer tutorials before going though this
guide so that it would be easy for you to understand the concept explained here.

example to print the address of array elements


#include <stdio.h>
int main( )
{
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
/* for loop to print value and address of each element of array*/
for ( int i = 0 ; i < 7 ; i++ )
{
/* The correct way of displaying the address would be using %p format
* specifier like this:
* printf("val[%d]: value is %d and address is %p\n", i, val[i], &val[i]);
* Just to demonstrate that the array elements are stored in contiguous
* locations, I m displaying the addresses in integer
*/
printf("val[%d]: value is %d and address is %d\n", i, val[i], &val[i]);
}
return 0;
}
Output:

val[0]: value is 11 and address is 1423453232


val[1]: value is 22 and address is 1423453236
val[2]: value is 33 and address is 1423453240
val[3]: value is 44 and address is 1423453244
val[4]: value is 55 and address is 1423453248
val[5]: value is 66 and address is 1423453348

C Array – Memory representation


Val[0] val[1] val[2] val[3] val[4] val[5] val[6]

11 22 34 44 55 66 79

89922 89924 89929 89934 89939 89944 89983

All the array elements occupy contigious space in memory.there is a difference of


9 among the addresses of subsequent things,this is because this array is of
integer types and an n integer holds 9 bytes of memory

In the above example I have used &val[i] to get the address of ith element of the
array. We can also use a pointer variable instead of using the ampersand (&) to
get the address.

Example – Array and Pointer Example in C


#include <stdio.h>
int main( )
{
/*Pointer variable*/
int *p;

/*Array declaration*/
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;

/* Assigning the address of val[0] the pointer


* You can also write like this:
* p = var;
* because array name represents the address of the first element
*/
p = &val[0];

for ( int i = 0 ; i<7 ; i++ )


{
printf("val[%d]: value is %d and address is %p\n", i, *p, p);
/* Incrementing the pointer so that it points to next element
* on every increment.
*/
p++;
}
return 0;
}
Output:

val[0]: value is 11 and address is 0x7fff51472c30


val[1]: value is 22 and address is 0x7fff51472c34
val[2]: value is 33 and address is 0x7fff51472c38
val[3]: value is 44 and address is 0x7fff51472c3c
val[4]: value is 55 and address is 0x7fff51472c40
val[5]: value is 66 and address is 0x7fff51472c44
val[6]: value is 77 and address is 0x7fff51472c48
Points to Note:
1) While using pointers with array, the data type of the pointer must match with
the data type of the array.
2) You can also use array name to initialize the pointer like this:

p = var;
because the array name alone is equivalent to the base address of the array.

val==&val[0];
3) In the loop the increment operation(p++) is performed on the pointer variable
to get the next location (next element’s location), this arithmetic is same for all
types of arrays (for all data types double, char, int etc.) even though the bytes
consumed by each data type is different.

Pointer logic
You must have understood the logic in above code so now its time to play with
few pointer arithmetic and expressions.

if p = &val[0] which means


*p ==val[0]
(p+1) == &val[2] & *(p+1) == val[2]
(p+2) == &val[3] & *(p+2) == val[3]
(p+n) == &val[n+1) & *(p+n) == val[n+1]
Using this logic we can rewrite our code in a better way like this:

#include <stdio.h>
int main( )
{
int *p;
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
p = val;
for ( int i = 0 ; i<7 ; i++ )
{
printf("val[%d]: value is %d and address is %p\n", i, *(p+i), (p+i));
}
return 0;
}
We don’t need the p++ statement in this program.
Passing array to function in C programming
with example
Just like variables, array can also be passed to a function as an argument . In
this guide, we will learn how to pass the array to a function using call by value
and call by reference methods.

To understand this guide, you should have the knowledge of following C


Programming topics:

1. C – Array
2. Function call by value in C
3. Function call by reference in C

Passing array to function using call by value


method
As we already know in this type of function call, the actual parameter is copied to
the formal parameters.

#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}

return 0;
}

a b c d e f g h i j
Passing array to function using call by reference
When we pass the address of an array while calling a function then this is called
function call by reference. When we pass an address as an argument, the
function declaration should have a pointer as a parameter to receive the passed
address.

#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}

int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}

return 0;
}
Output:

1 2 3 4 5 6 7 8 9 0
How to pass an entire array to a function as an argument?
In the above example, we have passed the address of each array element one
by one using a for loop in C. However you can also pass an entire array to a
function like this:

Note: The array name itself is the address of first element of that array. For
example if array name is arr then you can say that arr is equivalent to
the &arr[0].

#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}

int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output:

Value of var_arr[0] is: 11


Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 79

C – Strings

C – Strings and String functions with


examples
String is an array of characters. In this guide, we learn how to declare strings,
how to work with strings in C programming and how to use the pre-defined string
handling functions.

We will see how to compare two strings, concatenate strings, copy one string to
another & perform various string manipulation operations. We can perform such
operations using the pre-defined functions of “string.h” header file. In order to use
these string functions you must include string.h file in your C program.

String Declaration
Method 1:

char address[]={'T', 'E', 'X', 'A', 'S', '\0'};


char address[]="TEXAS";
In the above declaration NULL character (\0) will automatically be inserted at the
end of the string.

What is NULL Char “\0”?


'\0' represents the end of the string. It is also referred as String terminator & Null
Character.

String I/O in C programming

Read & write Strings in C using Printf() and Scanf() functions


#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");

/* I am reading the input string and storing it in nickname


* Array name alone works as a base address of array so
* we can use nickname instead of &nickname here
*/
scanf("%s", nickname);

/*Displaying String*/
printf("%s",nickname);

return 0;
}
Output:
Enter your Nick name:Negan
Negan
Note: %s format specifier is used for strings input/output

Read & Write Strings in C using gets() and puts() functions


#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

/* Console display using puts */


puts("Enter your Nick name:");

/*Input using gets*/


gets(nickname);

puts(nickname);

return 0;
}
C – String functions
C String function – strlen
Syntax:

size_t strlen(const char *str)


size_t represents unsigned short
It returns the length of the string without including end character (terminating
char ‘\0’).

Example of strlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:

Length of string str1: 13


strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns
the total allocated size assigned to the array. So if I consider the above example
again then the following statements would return the below values.

strlen(str1) returned value 13.


sizeof(str1) would return value 20 as the array size is 20 (see the first statement in
main function).

C String function – strnlen


Syntax:

size_t strnlen(const char *str, size_t maxlen)


size_t represents unsigned short
It returns length of the string if it is less than the value specified for maxlen
(maximum length) otherwise it returns maxlen value.

Example of strnlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the string
length was 13 it returned only 10 because the maxlen was 10.
C String function – strcmp
int strcmp(const char *str1, const char *str2)
It compares the two strings and returns an integer value. If both the strings are
same (equal) then this function would return 0 otherwise it may return a negative
or positive value based on the comparison.

If string1 < string2 OR string1 is a substring of string2 then it would result in


a negative value. If string1 > string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for
compare strings.

Example of strcmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string 1 and 2 are different


C String function – strncmp
int strncmp(const char *str1, const char *str2, size_t n)
size_t is for unassigned short
It compares both the string till n characters or in other words it compares first n
characters of both the strings.

Example of strncmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string1 and string 2 are equal


C String function – strcat
char *strcat(char *str1, char *str2)
It concatenates two strings and returns the concatenated string.

Example of strcat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:

Output string after concatenation: HelloWorld


C String function – strncat
char *strncat(char *str1, char *str2, int n)
It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will
always be appended at the end of the concatenated string.

Example of strncat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:

Concatenation using strncat: HelloWor


C String function – strcpy
char *strcpy( char *str1, char *str2)
It copies the string str2 into string str1, including the end character (terminator
char ‘\0’).

Example of strcpy:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m gonna copied into s1


C String function – strncpy
char *strncpy( char *str1, char *str2, size_t n)
size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1 and
appends several terminator chars(‘\0’) to accumulate the length of str1 to make it
n.

Example of strncpy:

#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m


C String function – strchr
char *strchr(char *str, int ch)
It searches string str for character ch (you may be wondering that in above
definition I have given data type of ch as int, don’t worry I didn’t make any
mistake it should be int only. The thing is when we give any character while using
strchr then it internally gets converted into integer for better searching.

Example of strchr:

#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:

f function strchr
C String function – Strrchr
char *strrchr(char *str, int ch)
It is similar to the function strchr, the only difference is that it searches the string
in reverse order, now you would have understood why we have extra r in strrchr,
yes you guessed it correct, it is for reverse only.

Now let’s take the same above example:

#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:

function strchr
Why output is different than strchr? It is because it started searching from the
end of the string and found the first ‘f’ in function instead of ‘of’.

C String function – strstr


char *strstr(char *str, char *srch_term)
It is similar to strchr, except that it searches for string srch_term instead of a
single char.

Example of strstr:

#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return 0;
}
Output:

Output string is: BeginnersBook.COM


You can also use this function in place of strchr as you are allowed to

give

single char also in place of search_term string.

Note that there is a difference of 4 bytes between each element because that’s
the size of an integer. Which means all the elements are stored in consecutive
contiguous memory locations in the memory.(See the diagram below)
Functions in C

Functions in C Programming with examples


A function is a block of statements that performs a specific task. Suppose you
are building an application in C language and in one of your program, you need
to perform a same task more than once. In such case you have two options –

a) Use the same set of statements every time you want to perform the task
b) Create a function to perform that task, and just call it every time you need to
perform that task.

Using option (b) is a good practice and a good programmer always uses
functions while writing codes in C.

Types of functions
1) Predefined standard library functions – such as puts(), gets(), printf(), scanf() etc
– These are the functions which already have a definition in header files (.h files
like stdio.h), so we just call them whenever there is a need to use them.

User Defined functions – The functions that we create in a program are known as
user defined functions.

In this guide, we will learn how to create user defined functions and how to use
them in C Programming

Why we need functions in C


Functions are used because of following reasons –
a) To improve the readability of code.
b) Improves the reusability of the code, same function can be used in any
program rather than writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy
to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by
function calls.
Syntax of a function
return_type function_name (argument list)
{
Set of statements – Block of code
}
return_type: Return type can be of any data type such as int, double, char, void,
short etc. Don’t worry you will understand these terms better once you go
through the examples below.

function_name: It can be anything, however it is advised to have a meaningful


name for the functions so that it would be easy to understand the purpose of
function just by seeing it’s name.

argument list: Argument list contains variables names along with their data
types. These arguments are kind of inputs for the function. For example – A
function which is used to add two integer variables, will be having two integer
argument.

Block of code: Set of C statements, which will be executed whenever a call will
be made to the function.

Do you find above terms confusing? – Do not worry I’m not gonna end this
guide until you learn all of them :)
Lets take an example – Suppose you want to create a function to add two integer
variables.

Let’s split the problem so that it would be easy to understand –


Function will add the two numbers so it should have some meaningful name like
sum, addition, etc. For example lets take the name addition for this function.

return_type addition(argument list)


This function addition adds two integer variables, which means I need two integer
variable as input, lets provide two integer parameters in the function signature.
The function signature would be –

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 would be integer –

int addition(int num1, int num2);


So you got your function prototype or signature. Now you can implement the
logic in C program like this:

How to call a function in C?


Consider the following C program

Example1: Creating a user defined function addition()


#include <stdio.h>
int addition(int num1, int num2)
{
int sum;
/* Arguments are used here*/
sum = num1+num2;

/* Function return type is integer so we are returning


* an integer value, the sum of the passed numbers.
*/
return sum;
}

int main()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);

/* Calling the function here, the function return type


* is integer so we need an integer variable to hold the
* returned value of this function.
*/
int res = addition(var1, var2);
printf ("Output: %d", res);

return 0;
}
Output:

Enter number 1: 100


Enter number 2: 120
Output: 220
Example2: Creating a void user defined function that doesn’t
return anything
#include <stdio.h>
/* function return type is void and it doesn't have parameters*/
void introduction()
{
printf("Hi\n");
printf("My name is Chaitanya\n");
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 regarding functions in C:
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.
4) A function can call itself and it is known as “Recursion“. I have written a
separate guide for it.

C Functions Terminologies that you must remember


return type: Data type of returned value. It can be void also, in such case
function doesn’t return any value.

Note: for example, if function 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 –

char abc(char ch1, char ch2)


{
char ch3;


return ch3;
}

int main()
{

char c1 = abc('a', 'x');

}

Function call by value in C programming


Function call by value is the default way of calling a function in C programming.
Before we discuss function call by value, lets understand the terminologies that
we will use while explaining this:

Actual parameters: The parameters that appear in function calls.


Formal parameters: The parameters that appear in function declarations.

For example:

#include <stdio.h>
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;
}
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). The actual parameters can also be the values. Like sum(13, 22),
here 13 and 22 are actual parameters.

In this guide, we will discuss function call by value. If you want to read call by
reference method then refer this guide: function call by reference.

Lets get back to the point.


What is Function Call By value?
When we pass the actual parameters while calling a function then this is known
as function call by value. In this case the values of actual parameters are copied
to the formal parameters. Thus operations performed on the formal parameters
don’t reflect in the actual parameters.

Example of Function call by Value


As mentioned above, in the call by value the actual arguments are copied to the
formal arguments, hence any operation performed by function on arguments
doesn’t affect actual parameters. Lets take an example to understand this:

#include <stdio.h>
int increment(int var)
{
var = var+1;
return var;
}

int main()
{
int num1=20;
int num2 = increment(num1);
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d", num2);

return 0;
}

Output:

Num 1 value is 22

Num 2 value is 27

Explanation
We passed the variable num1 while calling the method, but since we are calling
the function using call by value method, only the value of num1 is copied to the
formal parameter var. Thus change made to the var doesn’t reflect in the num1.

Example 2: Swapping numbers using Function Call


by Value
#include <stdio.h>
void swapnum( int var1, int var2 )
{
int tempnum ;
/*Copying var1 value into temporary variable */
tempnum = var1 ;

/* Copying var2 value into var1*/


var1 = var2 ;

/*Copying temporary variable value into var2 */


var2 = tempnum ;

}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: %d, %d", num1, num2);

/*calling swap function*/


swapnum(num1, num2);
printf("\nAfter swapping: %d, %d", num1, num2);
}
Output:

Before swapping: 35, 45


After swapping: 35, 45
Why variables 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.

Function call by reference in C


Programming
Before we discuss function call by reference, lets understand the terminologies
that we will use while explaining this:
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function declarations.
For example: We have a function declaration like this:

int sum(int a, int b);


The a and b parameters are formal parameters.

We are calling the function like this:

int s = sum(13, 22); //Here 10 and 20 are actual parameters


or
int s = sum(n1, n2); //Here n1 and n2 are actual parameters
In this guide, we will discuss function call by reference method. If you want to
read call by value method then refer this guide: function call by value.

Lets get back to the point.

What is Function Call By Reference?


When we call a function by passing the addresses of actual parameters then this
way of calling the function is known as call by reference. In call by reference, the
operation performed on formal parameters, affects the value of actual
parameters because all the operations performed on the value stored in the
address of actual parameters. It may sound confusing first but the following
example would clear your doubts.

Example of Function call by Reference


Lets take a simple example. Read the comments in the following program.

#include <stdio.h>
void increment(int *var)
{
/* Although we are performing the increment on variable
* var, however the var is a pointer that holds the address
* of variable num, which means the increment is actually done
* on the address where value of num is stored.
*/
*var = *var+1;
}
int main()
{
int num=20;
/* This way of calling the function is known as call by
* reference. Instead of passing the variable num, we are
* passing the address of variable num
*/
increment(&num);
printf("Value of num is: %d", num);
return 0;

output:

the value of num is :27


Function Call by Reference – Swapping numbers
Here we are swapping the numbers using call by reference. As you can see the
values of the variables have been changed after calling the swapnum() function
because the swap happened on the addresses of the variables num1 and num2.

#include
void swapnum ( int *var1, int *var2 )
{
int tempnum ;
tempnum = *var1 ;
*var1 = *var2 ;
*var2 = tempnum ;
}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);

/*calling swap function*/


swapnum( &num1, &num2 );

printf("\nAfter swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
}
Output:

Before swapping:
num1 value is 39
num2 value is 47
After swapping:
num1 value is 47
num2 value is 39

Structure

Structure in C programming with examples


Structure is a group of variables of different data types represented by a single
name. Lets take an example to understand the need of a structure in C
programming.

Lets say we need to store the data of students like student name, age, address,
id etc. One way of doing this would be creating a different variable for each
attribute, however when you need to store the data of multiple students then in
that case, you would need to create these several variables again for each
student. This is such a big headache to store data in this way.

We can solve this problem easily by using structure. We can create a structure
that has members for name, id, address and age and then we can create the
variables of this structure for each student. This may sound confusing, do not
worry we will understand this with the help of example.

How to create a structure in C Programming


We use struct keyword to create a structure in C. The struct keyword is a short
form of structured data type.

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

};
Here struct_name can be anything of your choice. Members data type can be
same or different. Once we have declared the structure we can use the struct
name as a data type like int, float etc.

First we will see the syntax of creating struct variable, accessing struct members
etc and then we will see a complete example.

How to declare variable of a structure?


struct struct_name var_name;
or

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

} var_name;
How to access data members of a structure using a struct
variable?
var_name.member1_name;
var_name.member2_name;

How to assign values to structure members?
There are three ways to do this.
1) Using Dot(.) operator

var_name.memeber_name = value;
2) All members assigned in one statement

struct struct_name var_name =


{value for memeber1, value for memeber2 …so on for all the members}
3) Designated initializers – We will discuss this later at the end of this post.

Example of Structure in C
#include <stdio.h>
/* Created a structure here. The name of the structure is
* StudentData.
*/
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
/* student is the variable of structure StudentData*/
struct StudentData student;

/*Assigning the values of each struct member here*/


student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;

/* Displaying the values of struct members */


printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}
Output:
Student Name is: Steve
Student Id is: 1234
Student Age is: 30
Nested Structure in C: Struct inside another struct
You can use a structure inside another structure, which is fairly possible. As I
explained above that once you declared a structure, the struct
struct_name acts as a new data type so you can include it in another struct just
like the data type of other data members. Sounds confusing? Don’t worry. The
following example will clear your doubt.

Example of Nested Structure in C Programming


Lets say we have two structure like this:
Structure 1: stu_address

struct stu_address
{
int street;
char *state;
char *city;
char *country;
}
Structure 2: stu_data

struct stu_data
{
int stu_id;
int stu_age;
char *stu_name;
struct stu_address stuAddress;
}
As you can see here that I have nested a structure inside another structure.

Assignment for struct inside struct (Nested struct)


Lets take the example of the two structure that we seen above to understand the
logic

struct stu_data mydata;


mydata.stu_id = 1001;
mydata.stu_age = 30;
mydata.stuAddress.state = "UP"; //Nested struct assignment
..
How to access nested structure members?
Using chain of “.” operator.
Suppose you want to display the city alone from nested struct –

printf("%s", mydata.stuAddress.city);
Use of typedef in Structure
typedef makes the code short and improves readability. In the above discussion
we have seen that while using structs every time we have to use the lengthy
syntax, which makes the code confusing, lengthy, complex and less readable.
The simple solution to this issue is use of typedef. It is like an alias of struct.

Code without typedef

struct home_address {
int local_street;
char *town;
char *my_city;
char *my_country;
};
...
struct home_address var;
var.town = "Agra";
Code using tyepdef

typedef struct home_address{


int local_street;
char *town;
char *my_city;
char *my_country;
}addr;
..
..
addr var1;
var.town = "Agra";
Instead of using the struct home_address every time you need to declare struct
variable, you can simply use addr, the typedef that we have defined.

Designated initializers to set values of Structure


members
We have already learned two ways to set the values of a struct member, there is
another way to do the same using designated initializers. This is useful when we
are doing assignment of only few members of the structure. In the following
example the structure variable s2 has only one member assignment.
#include <stdio.h>
struct numbers
{
int num1, num2;
};
int main()
{
// Assignment using using designated initialization
struct numbers s1 = {.num2 = 22, .num1 = 11};
struct numbers s2 = {.num2 = 30};

printf ("num1: %d, num2: %d\n", s1.num1, s1.num2);


printf ("num1: %d", s2.num2);
return 0;
}
Output:

num1: 11, num2: 22


num1: 30

Pointer in C Programming

Pointers in C Programming with examples


A pointer is a variable that stores the address of another variable. Unlike other
variables that hold values of a certain type, pointer holds the address of a
variable. For example, an integer variable holds (or you can say stores) an
integer value, however an integer pointer holds the address of a integer variable.
In this guide, we will discuss pointers in C programming with the help of
examples.

Before we discuss about pointers in C, lets take a simple example to


understand what do we mean by the address of a variable.

A simple example to understand how to access the address of a


variable without pointers?
In this program, we have a variable num of int type. The value of num is 10 and
this value must be stored somewhere in the memory, right? A memory space is
allocated for each variable that holds the value of that variable, this memory
space has an address. For example we live in a house and our house has an
address, which helps other people to find our house. The same way the value of
the variable is stored in a memory address, which helps the C program to find
that value when it is needed.

So let’s say the address assigned to variable num is 0x7fff5694dc58, which means
whatever value we would be assigning to num should be stored at the
location: 0x7fff5694dc58. See the diagram below.

#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p
* format specifier and ampersand (&) sign just
* before the variable name like &num.
*/
printf("\nAddress of variable num is: %p", &num);
return 0;
}
Output:

Value of variable num is: 10


Address of variable num is: 0x7fff5694dc58

Parameter name-num
Value of num-13
Address of num-0*7fff5794dt57

Example of Pointers in C
This program shows how a pointer is declared and used. There are several other
things that we can do with pointers, we have discussed them later in this guide.
For now, we just need to know how to link a pointer to the address of a variable.

Important point to note is: The data type of pointer and the variable must
match, an int pointer can hold the address of int variable, similarly a pointer
declared with float data type can hold the address of a float variable. In the
example below, the pointer and the variable both are of int type.

#include <stdio.h>
int main()
{
//Variable declaration
int num = 10;
//Pointer declaration
int *p;

//Assigning address of num to the pointer p


p = #

printf("Address of variable num is: %p", p);


return 0;
}
Output:

Address of variable num is: 0x7fff5694dc58


C Pointers – Operators that are used with Pointers
Lets discuss the operators & and * that are used with Pointers in C.

“Address of”(&) Operator


We have already seen in the first example that we can display the address of a
variable using ampersand sign. I have used &num to access the address of
variable num. The & operator is also known as “Address of” Operator.

printf("Address of var is: %p", &num);


Point to note: %p is a format specifier which is used for displaying the address
in hex format.
Now that you know how to get the address of a variable but how to store that
address in some other variable? That’s where pointers comes into picture. As
mentioned in the beginning of this guide, pointers in C programming are used for
holding the address of another variables.

Pointer is just like another variable, the main difference is that it stores
address of another variable rather than a value.

“Value at Address”(*) Operator


The * Operator is also known as Value at address operator.

How to declare a pointer?

int *p1 /*Pointer to an integer variable*/


double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
float *p4 /*pointer to a float variable*/
The above are the few examples of pointer declarations. If you need a pointer
to store the address of integer variable then the data type of the pointer
should be int. Same case is with the other data types.

By using * operator we can access the value of a variable through a pointer.


For example:

double a = 10;
double *p;
p = &a;
*p would give us the value of the variable a. The following statement would
display 10 as output.

printf("%d", *p);
Similarly if we assign a value to *pointer like this:

*p = 200;
It would change the value of variable a. The statement above will change the
value of a from 10 to 200.

Example of Pointer demonstrating the use of & and *


#include <stdio.h>
int main()
{
/* Pointer of integer type, this can hold the
* address of a integer type variable.
*/
int *p;

int var = 10;

/* Assigning the address of variable var to the pointer


* p. The p can hold the address of var because var is
* an integer type variable.
*/
p= &var;

printf("Value of variable var is: %d", var);


printf("\nValue of variable var is: %d", *p);
printf("\nAddress of variable var is: %p", &var);
printf("\nAddress of variable var is: %p", p);
printf("\nAddress of pointer p is: %p", &p);
return 0;
}
Output:
Value of variable var is: 10
Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50

C-pointers

Int var=13;

Int*p;

P=&var;

0*8fff5ed98c9c  Val 13
0*8fff5ed98c9c

0*8fff5ed98c83

Lets take few more examples to understand it better –


Lets say we have a char variable ch and a pointer ptr that holds the address of
ch.

char ch='a';
char *ptr;
Read the value of ch

printf("Value of ch: %c", ch);


or
printf("Value of ch: %c", *ptr);
Change the value of ch

ch = 'b';
or
*ptr = 'b';
The above code would replace the value ‘a’ with ‘b’.

Can you guess the output of following C program?

#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;

printf ( "Address of var is: %p", &var);


printf ( "\nAddress of var is: %p", p);

printf ( "\nValue of var is: %d", var);


printf ( "\nValue of var is: %d", *p);
printf ( "\nValue of var is: %d", *( &var));

/* Note I have used %p for p's value as it represents an address*/


printf( "\nValue of pointer p is: %p", p);
printf ( "\nAddress of pointer p is: %p", &p);

return 0;
}
Output:

Address of var is: 0x7fff5d027c58


Address of var is: 0x7fff5d027c58
Value of var is: 10
Value of var is: 10
Value of var is: 10
Value of pointer p is: 0x7fff5d027c58
Address of pointer p is: 0x7fff5d027c50
More Topics on Pointers
1) Pointer to Pointer – A pointer can point to another pointer (which means it
can store the address of another pointer), such pointers are known as double
pointer OR pointer to pointer.
2) Passing pointers to function – Pointers can also be passed as an argument
to a function, using this feature a function can be called by reference as well as
an array can be passed to a function while calling.

3) Function pointers – A function pointer is just like another pointer, it is used


for storing the address of a function. Function pointer can also be used for calling
a function in C program.

java

You might also like