C Rkhussain Sir
C Rkhussain Sir
1 . C Introduction
2.C Fundamentals
3. C Flow Control
4. C Functions
5. C Programming Arrays
6. C Programming Pointers
7. C Programming Strings
9. C Programming Files
C Introduction
o Getting Started with C
o C Comments
C Fundamentals
C Flow Control
o C if...else Statement
o C for Loop
o C while and do...while Loop
o C break and continue
o C switch Statement
o C goto Statement
C Functions
o C Functions
o C User-defined functions
o Types of User-defined Functions in C Programming
o C Recursion
o C Storage Class
C Programming Arrays
o C Arrays
o C Multidimensional Arrays
o Pass arrays to a function in C
C Programming Pointers
o C Pointers
o Relationship Between Arrays and Pointers
o C Pass Addresses and Pointers
o C Dynamic Memory Allocation
o C Array and Pointer Examples
C Programming Strings
o C Programming Strings
o String Manipulations In C Programming Using Library Functions
o String Examples in C Programming
o C struct
o C structs and Pointers
o C Structure and Function
o C Unions
C Programming Files
o C File Handling
o C Files Examples
C Additional Topics
You can run C on your computer using the following two methods:
Run C online
Install C on your computer
To run C code, you need to have a C compiler installed on your system. However, if
you want to start immediately, you can use our free online C compiler.
Online C Compiler
The online compiler enables you to run C code directly in your browser—no
installation required.
For those who prefer to install C on your computer, this guide will walk you through
the installation process on Windows, macOS, and Linux (Ubuntu).
Windows
Mac
Linux
1. Install VS Code
Go to the VS Code Official website and download the Windows installer. Once the
download is complete, run the installer and follow the installation process.
Click Finish to complete the installation process.
Visit the official MinGW website and download the MinGW installation manager.
C MinGW Installation
Step 3: Run the Installer
Now, go to your downloads folder and run the installer you just downloaded. You will
be prompted to this screen.
C Run MinGW Installer
Click on Continue and wait till the download is completed.
This will include the gcc-core package, which contains the GCC compiler for C.
Step 4: Add MinGW to System PATH
Go to the folder and double click on the MinGW folder and copy its location.
C:\MinGW\bin
Search environment variable on the terminal. In system properties, click on
environment variables. You will be prompted to the screen below.
Open VS Code and click on Extensions in the left side of the window.
Then, search for C/C++ by Microsoft in the Extensions and click on install.
Now, you are all set to run C code inside your VS Code.
Note: Alternatively, you can use IDEs like Code::Blocks or Visual Studio, which
come with their own C compilers.
First open VS Code, click on the File in the top menu and then select New File.
Create a New File in VS Code
Then, save this file with a .c extension by clicking on File again, then Save As, and
type your filename ending in .c. (Here, we are saving it as hello.c)
#include<stdio.h>
int main(){
printf("Hello World");
return 0;
Run Code
Then click on the run button on the top right side of your screen.
C Run Program
Instead of the run button as in Windows and macOS, you should follow the following
steps to run your C program on Linux.
After compiling successfully, you'll see a new file named hello (or hello.exe on
Windows) in the same directory.
./hello
Now that you have set everything up to run C programs on your computer, you'll be
learning how the basic program works in C in the next tutorial.
In the previous tutorial you learned how to install C on your computer. Now, let's write
a simple C program.
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
Run Code
Output
Hello, World!
Note: A Hello, World! program includes the basic syntax of a programming language
and helps beginners understand the structure before getting started. That's why it is
a common practice to introduce a new language using a Hello, World! program.
It's okay if you don’t understand how the program works right now. We will learn
about it in upcoming tutorials. For now, just write the exact program and run it.
Working of C Program
Congratulations on writing your first C program.Now, let's see how the program
works.
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
Run Code
printf("Hello, World!");
Here, printf statement prints the text Hello, World! to the screen.
Remember these important things about printf:
Everything you want to print should be kept inside parentheses ().
Not following the above rules will result in errors and your code will not run
successfully.
As we have seen from the last example, a C program requires a lot of lines even for
a simple program.
For now, just remember that every C program we will write will follow this structure:
#include <stdio.h>
int main() {
// your code
return 0;
Day3
C Comments
In the previous tutorial you learned to write your first C program. Now, let's learn
about C comments.
Tip: We are introducing comments early in this tutorial series because, from now on,
we will be using them to explain our code.
Comments are hints that we add to our code, making it easier to understand.
For example,
#include <stdio.h>
int main() {
return 0;
Run Code
Output
Hello World
Single-line Comments in C
In C, a single line comment starts with // symbol. It starts and ends in the same line.
For example,
#include <stdio.h>
int main() {
return 0;
Run Code
Output
Age: 25
We can also use the single line comment along with the code.
Here, code before // are executed and code after // are ignored by the compiler.
Multi-line Comments in C
#include <stdio.h>
int main() {
return 0;
Run Code
Output
Age: 25
In this type of comment, the C compiler ignores everything from /* to */.
Note: Remember the keyboard shortcut to use comments:
Multi line comment: ctrl + shift + / (windows) and cmd + shift + / (mac)
While debugging there might be situations where we don't want some part of the
code. For example,
In the program below, suppose we don't need data related to height. So, instead of
removing the code related to height, we can simply convert them into comments.
#include <stdio.h>
int main() {
}
Run Code
Here, the code throws an error because we have not defined a product variable.
For example,
#include <stdio.h>
int main() {
return 0;
Run Code
Here, we have resolved the error by commenting out the code related to the product.
If we need to calculate the product in the near future, we can uncomment it.
Day4
In the previous tutorial you learnt about C comments. Now, let's learn about
variables, constants and literals in C.
Variables
To indicate the storage area, each variable should be given a unique name
(identifier). Variable names are just the symbolic representation of a memory
location. For example:
int age = 25;
Here, age is a variable of int type and we have assigned an integer value 25 to it.
char ch = 'a';
// some code
ch = 'l';
Visit this page to learn more about different types of data a variable can store.
Constants
If you want to define a variable whose value cannot be changed, you can use
the const keyword. This will create a constant. For example,
const double PI = 3.14;
PI = 2.9; //Error
You can also define a constant using the #define preprocessor directive. We will
learn about it in C Macros tutorial.
Literals
Literals are data used for representing fixed values. They can be used directly in the
code. For example: 1, 2.5, 'c' etc.
Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these
terms.
1. Integers
For example:
2. Floating-point Literals
-2.0
0.0000234
-0.22E-5
Note: E-5 = 10-5
3. Characters
4. String Literals
5. Escape Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
For example: \n is used for a newline. The backslash \ causes escape from the
normal way the characters are handled by the compiler.
Day5
C Data Types
In C programming, data types are declarations for variables. This determines the
type and size of data associated with variables. For example,
int myVar;
Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.
Basic types
Here's a table containing commonly used types in C programming for quick access.
char 1 %c
float 4 %f
double 8 %lf
signed char 1 %c
unsigned char 1 %c
Integers are whole numbers that can have both zero, positive and negative values
but no decimal values. For example, 0, -5, 10
We can use int for declaring an integer variable.
int id;
The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -
2147483648 to 2147483647.
double price;
The size of float (single precision float data type) is 4 bytes. And the size
of double (double precision float data type) is 8 bytes.
char
Keyword char is used for declaring character type variables. For example,
char test = 'h';
void
void is an incomplete type. It means "nothing" or "no type". You can think of void
as absent.
For example, if a function is not returning anything, its return type should be void.
Note that, you cannot create variables of void type.
If you need to use a large number, you can use a type specifier long. Here's how:
long a;
long long b;
long double c;
Here variables a and b can store integer values. And, c can store a floating-point
number.
If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can
use short.
short d;
You can always check the size of a variable using the sizeof() operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;
return 0;
Run Code
For example,
// valid codes
Here, the variables x and num can hold only zero and positive values because we
have used the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1,
whereas variable x can hold values from 0 to 232-1.
Data types that are derived from fundamental data types are derived types. For
example: arrays, pointers, function types, structures, etc.
bool type
Enumerated type
Complex types
Day 6
C Output
In C programming, printf() is one of the main output function. The function sends
formatted output to the screen. For example,
Example 1: C Output
#include <stdio.h>
int main()
printf("C Programming");
return 0;
Run Code
Output
C Programming
How does this program work?
All valid C programs must contain the main() function. The code execution
begins from the start of the main() function.
The printf() is a library function to send formatted output to the screen. The
function prints the string inside quotations.
To use printf() in our program, we need to include stdio.h header file using
the #include <stdio.h> statement.
The return 0; statement inside the main() function is the "Exit status" of the
program. It's optional.
#include <stdio.h>
int main()
{
int testInteger = 5;
return 0;
Run Code
Output
Number = 5
We use %d format specifier to print int types. Here, the %d inside the quotations will
be replaced by the value of testInteger.
#include <stdio.h>
int main()
return 0;
Run Code
Output
number1 = 13.500000
number2 = 12.400000
To print float, we use %f format specifier. Similarly, we use %lf to print double values.
int main()
return 0;
Run Code
Output
character = a
C Input
In C programming, scanf() is one of the commonly used function to take input from
the user. The scanf() function reads formatted input from the standard input such as
keyboards.
#include <stdio.h>
int main()
int testInteger;
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Run Code
Output
Enter an integer: 4
Number = 4
Here, we have used %d format specifier inside the scanf() function to take int input
from the user. When the user enters an integer, it is stored in the testInteger variable.
Notice, that we have used &testInteger inside scanf(). It is because &testInteger gets
the address of testInteger, and the value entered by the user is stored in that
address.
#include <stdio.h>
int main()
float num1;
double num2;
scanf("%f", &num1);
scanf("%lf", &num2);
return 0;
}
Run Code
Output
num1 = 12.523000
num2 = 10.200000
We use %f and %lf format specifier for float and double respectively.
#include <stdio.h>
int main()
char chr;
return 0;
Run Code
Output
Enter a character: g
You entered g
When a character is entered by the user in the above program, the character itself is
not stored. Instead, an integer value (ASCII value) is stored.
And when we display that value using %c text format, the entered character is
displayed. If we use %d to display the character, it's ASCII value is printed.
#include <stdio.h>
int main()
char chr;
return 0;
Run Code
Output
Enter a character: g
You entered g.
Here's how you can take multiple inputs from the user and display them.
#include <stdio.h>
int main()
int a;
float b;
return 0;
}
Run Code
Output
3.4
%d for int
%f for float
%c for char
Here's a list of commonly used C data types and their format specifiers.
int %d
char %c
float %f
double %lf
unsigned int %u
signed char %c
unsigned char %c
Day7
C Programming Operators
C Arithmetic Operators
* multiplication
/ division
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
return 0;
}
Run Code
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
It is because both the variables a and b are integers. Hence, the output is also an
integer. The compiler neglects the term after the decimal point and shows
answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a=9 is divided by b=4, the
remainder is 1. The % operator can only be used with integers.
a/b = 2.5
a/d = 2.5
c/b = 2.5
c/d = 2
#include <stdio.h>
int main()
return 0;
Run Code
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also be
used as postfixes like a++ and a--. Visit this page to learn more about how increment
and decrement operators work when used as postfix.
C Assignment Operators
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
#include <stdio.h>
int main()
int a = 5, c;
c = a; // c is 5
c += a; // c is 10
c -= a; // c is 5
c *= a; // c is 25
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
return 0;
Run Code
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
C Relational Operators
A relational operator checks the relationship between two operands. If the relation is
true, it returns 1; if the relation is false, it returns value 0.
== Equal to 5 == 3 is evaluated to 0
#include <stdio.h>
int main()
int a = 5, b = 5, c = 10;
return 0;
}
Run Code
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
C Logical Operators
Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c=
||
operand is true (d>5)) equals to 1.
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
Run Code
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Explanation of logical operator program
C Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof is a unary operator that returns the size of data (constants, variables,
array, structure, etc).
Example 6: sizeof Operator
#include <stdio.h>
int main()
int a;
float b;
double c;
char d;
return 0;
Run Code
Output
Other operators such as ternary operator ?:, reference operator &, dereference
operator * and member selection operator -> will be discussed in later tutorials.
Before we wrap up, let’s put your knowledge of C Programming Operators to the
test! Can you solve the following challenge?
Challenge:
Write a function to find the smallest of two numbers.
Check Code
Day 8
C if...else Statement
C if Statement
if (test expression)
{
// code
}
How if statement works?
The if statement evaluates the test expression inside the parenthesis ().
If the test expression is evaluated to true, statements inside the body of if are
executed.
If the test expression is evaluated to false, statements inside the body of if are
not executed.
Working
of if Statement
To learn more about when test expression is evaluated to true (non-zero value) and
false (0), check relational and logical operators.
Example 1: if statement
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if (number < 0) {
return 0;
Run Code
Output 1
Enter an integer: -2
You entered -2.
When the user enters -2, the test expression number<0 is evaluated to true.
Hence, You entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
When the user enters 5, the test expression number<0 is evaluated to false and the
statement inside the body of if is not executed
C if...else Statement
if (test expression) {
else {
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if (number%2 == 0) {
}
else {
printf("%d is an odd integer.",number);
return 0;
Run Code
Output
Enter an integer: 7
7 is an odd integer.
When the user enters 7, the test expression number%2==0 is evaluated to false.
Hence, the statement inside the body of else is executed.
C if...else Ladder
The if...else statement executes two different codes depending upon whether the
test expression is true or false. Sometimes, a choice has to be made from more than
2 possibilities.
The if...else ladder allows you to check between multiple test expressions and
execute different statements.
if (test expression1) {
// statement(s)
// statement(s)
// statement(s)
}
.
.
else {
// statement(s)
#include <stdio.h>
int main() {
if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
else {
}
return 0;
Run Code
Output
23
Result: 12 < 23
Nested if...else
This program given below relates two integers using either <, > and = similar to
the if...else ladder's example. However, we will use a nested if...else statement to
solve this problem.
#include <stdio.h>
int main() {
printf("Result: %d = %d",number1,number2);
else {
}
}
else {
return 0;
Run Code
If the body of an if...else statement has only one statement, you do not need to use
brackets {}.
if (a > b) {
printf("Hello");
printf("Hi");
is equivalent to
if (a > b)
printf("Hello");
printf("Hi");
Before we wrap up, let’s put your knowledge of C if else to the test! Can you solve
the following challenge?
Challenge:
Write a function to determine if a student has passed or failed based on their score.
A student passes if their score is 50 or above.
Day 9
C for Loop
In programming, a loop is used to repeat a block of code until the specified condition
is met.
1. for loop
2. while loop
3. do...while loop
We will learn about for loop in this tutorial. In the next tutorial, we will learn
about while and do...while loop.
for Loop
{
// statements inside the body of loop
#include <stdio.h>
int main() {
int i;
return 0;
Run Code
Output
1 2 3 4 5 6 7 8 9 10
1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body
of for loop is executed. This will print the 1 (value of i) on the screen.
3. The update statement ++i is executed. Now, the value of i will be 2. Again, the
test expression is evaluated to true, and the body of for loop is executed. This
will print 2 (value of i) on the screen.
4. Again, the update statement ++i is executed and the test expression i < 11 is
evaluated. This process goes on until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for loop terminates.
#include <stdio.h>
int main()
scanf("%d", &num);
sum += count;
return 0;
}
Run Code
Output
Sum = 55
The value entered by the user is stored in the variable num. Suppose, the user
entered 10.
The count is initialized to 1 and the test expression is evaluated. Since the test
expression count<=num (1 less than or equal to 10) is true, the body of for loop is
executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2. Again, the
test expression is evaluated. Since 2 is also less than 10, the test expression is
evaluated to true and the body of the for loop is executed. Now, sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false), and the loop
terminates.
We will learn about while loop and do...while loop in the next tutorial.
Before we wrap up, let’s put your knowledge of C for Loop to the test! Can you solve
the following challenge?
Challenge:
Write a function to calculate the factorial of a number.
Day10
In programming, loops are used to repeat a block of code until a specified condition
is met.
1. for loop
2. while loop
3. do...while loop
In the previous tutorial, we learned about for loop. In this tutorial, we will learn
about while and do..while loop.
while loop
while (testExpression) {
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
return 0;
Run Code
Output
1
2
3. This process goes on until i becomes 6. Then, the test expression i <= 5 will
be false and the loop terminates.
do...while loop
The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed at least once. Only then, the test expression is
evaluated.
do {
}
while (testExpression);
How do...while loop works?
The body of do...while loop is executed once. Only then, the testExpression is
evaluated.
If testExpression is true, the body of the loop is executed
again and testExpression is evaluated once more.
This process goes on until testExpression becomes false.
#include <stdio.h>
int main() {
do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
Run Code
Output
Enter a number: 0
Sum = 4.70
Here, we have used a do...while loop to prompt the user to enter a number. The loop
works as long as the input number is not 0.
The do...while loop executes at least once i.e. the first iteration runs without checking
the condition. The condition is checked only after the first iteration has been
executed.
do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
while(number != 0.0);
So, if the first input is a non-zero number, that number is added to the sum variable
and the loop continues to the next iteration. This process is repeated until the user
enters 0.
But if the first input is 0, there will be no second iteration of the loop
and sum becomes 0.0.
Before we wrap up, let’s put your knowledge of C while and do...while Loop to the
test! Can you solve the following challenge?
Challenge:
Day 11
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
The break statement is almost always used with if...else statement inside the loop.
#include <stdio.h>
int main() {
int i;
scanf("%lf", &number);
return 0;
Run Code
Output
Enter n4: -3
Sum = 10.30
In C, break is also used with the switch statement. This will be discussed in the next
tutorial.
C continue
The continue statement skips the current iteration of the loop and continues with the
next iteration. Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.
// If the user enters a negative number, it's not added to the result
#include <stdio.h>
int main() {
int i;
scanf("%lf", &number);
continue;
}
sum += number; // sum = sum + number;
return 0;
}
Run Code
Output
Enter n10: 12
Sum = 59.70
In this program, when the user enters a positive number, the sum is calculated
using sum += number; statement.
When the user enters a negative number, the continue statement is executed and it
skips the negative number from the calculation.
o
Before we wrap up, let’s put your knowledge of C break and continue to the test! Can
you solve the following challenge?
Challenge:
Write a function to check if a given number is prime or not.
A prime number is a natural number that has exactly two distinct positive
divisors: 1 and itself.
For example, 7 is a prime number because it has only two distinct positive
divisors: 1 and 7.
Return 1 if num is prime, otherwise return 0.
Day12
C switch Statement
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of
the switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
case constant1:
// statements
break;
case constant2:
// statements
break;
.
default:
// default statements
}
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.
If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to constant2,
statements after case constant2: are executed until break is encountered.
If we do not use the break statement, all statements after the matching label
are also executed.
#include <stdio.h>
int main() {
char operation;
double n1, n2;
scanf("%c", &operation);
switch(operation)
{
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
default:
Run Code
Output
12.4
32.5 - 12.4 = 20.1
The - operator entered by the user is stored in the operation variable. And, two
operands 32.5 and 12.4 are stored in variables n1 and n2 respectively.
Day13
C goto Statement
The goto statement allows us to transfer control of the program to the specified label.
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the goto statement is encountered, the control of the
program jumps to label: and starts executing the code.
// If the user enters a negative number, the sum and average are displayed.
#include <stdio.h>
int main() {
int i;
scanf("%lf", &number);
}
sum += number;
jump:
return 0;
Run Code
Output
1. Enter a number: 3
Sum = 16.60
Average = 5.53
The use of goto statement may lead to code that is buggy and hard to follow. For
example,
one:
test += i;
goto two;
}
two:
if (test > 5) {
goto three;
... .. ...
Also, the goto statement allows you to do bad stuff such as jump out of the scope.
That being said, goto can be useful sometimes. For example: to break from nested
loops.
If you think the use of goto statement simplifies your program, you can use it. That
being said, goto is rarely useful and you can create any C program without
using goto altogether.
Here's a quote from Bjarne Stroustrup, creator of C++, "The fact that 'goto' can do
anything is exactly why we don't use it."
Day 14
C Functions
Suppose, you need to create a program to create a circle and color it. You can create
two functions to solve this problem:
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Types of function
User-defined functions
The sqrt() function calculates the square root of a number. The function is
defined in the math.h header file.
Visit standard library functions in C programming to learn more.
User-defined function
You can also create functions as per your need. Such functions created by the user
are known as user-defined functions.
How user-defined function works?
#include <stdio.h>
void functionName()
... .. ...
... .. ...
int main()
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
void functionName()
And, the compiler starts executing the codes inside functionName().
The control of the program jumps back to the main() function once code inside the
function definition is executed.
Working of C Function
3. A large program can be divided into smaller modules. Hence, a large project
can be divided among many programmers.
Day 15
C User-defined functions
Suppose, you need to create a circle and color it depending upon the radius and
color. You can create two functions to solve this problem:
createCircle() function
color() function
Here is an example to add two integers. To perform this task, we have created an
user-defined addNumbers().
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
int n1,n2,sum;
scanf("%d %d",&n1,&n2);
printf("sum = %d",sum);
return 0;
int result;
result = a+b;
Function prototype
A function prototype gives information to the compiler that the function may later be
used in the program.
Syntax of function prototype
In the above example, int addNumbers(int a, int b); is the function prototype which
provides the following information to the compiler:
1. name of the function is addNumbers()
The function prototype is not needed if the user-defined function is defined before
the main() function.
Calling a function
Function definition
Function definition contains the block of code to perform a specific task. In our
example, adding two numbers and returning it.
When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a function.
In programming, argument refers to the variable passed to the function. In the above
example, two variables n1 and n2 are passed during the function call.
The parameters a and b accepts the passed arguments in the function definition.
These arguments are called formal parameters of the function.
Passing Argument to Function
The type of arguments passed to a function and the formal parameters must match,
otherwise, the compiler will throw an error.
Return Statement
The return statement terminates the execution of a function and returns a value to
the calling function. The program control is transferred to the calling function after the
return statement.
In the above example, the value of the result variable is returned to the main
function. The sum variable in the main() function is assigned this value.
Return Statement of Function
Syntax of return statement
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in the
function prototype and function definition must match.
Visit this page to learn more on passing arguments and returning value from a
function.
Day 16
These 4 programs below check whether the integer entered by the user is a prime
number or not.
The output of all these programs below is the same, and we have created a user-
defined function in each example. However, the approach we have taken in each
example is different.
#include <stdio.h>
void checkPrimeNumber();
int main() {
return 0;
void checkPrimeNumber() {
int n, i, flag = 0;
scanf("%d",&n);
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
flag = 1;
if(n%i == 0) {
flag = 1;
break;
}
if (flag == 1)
else
Run Code
The checkPrimeNumber() function takes input from the user, checks whether it is a
prime number or not, and displays it on the screen.
The return type of the function is void. Hence, no value is returned from the function.
#include <stdio.h>
int getInteger();
int main() {
int n, i, flag = 0;
// no argument is passed
n = getInteger();
if (n == 0 || n == 1)
flag = 1;
if(n%i == 0){
flag = 1;
break;
if (flag == 1)
else
return 0;
int getInteger() {
int n;
Run Code
Here, the getInteger() function takes input from the user and returns it. The code to
check whether a number is prime or not is inside the main() function.
#include <stdio.h>
int main() {
int n;
scanf("%d",&n);
checkPrimeAndDisplay(n);
return 0;
int i, flag = 0;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
flag = 1;
if(n%i == 0){
flag = 1;
break;
}
if(flag == 1)
else
Run Code
#include <stdio.h>
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
flag = checkPrimeNumber(n);
if(flag == 1)
printf("%d is not a prime number",n);
else
return 0;
int checkPrimeNumber(int n) {
if (n == 0 || n == 1)
return 1;
int i;
if(n%i == 0)
return 1;
}
return 0;
Run Code
Well, it depends on the problem you are trying to solve. In this case, passing an
argument and returning a value from the function (example 4) is better.
Day 17
C Recursion
A physical world example would be to place two parallel mirrors facing each other.
Any object in between them would be reflected recursively.
In C, we know that a function can call other functions. It is even possible for the
function to call itself. These types of construct are termed as recursive functions.
How recursion works?
void recurse()
... .. ...
recurse();
... .. ...
int main()
... .. ...
recurse();
... .. ...
Working of
Recursion
The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if...else statement (or similar approach) can be used
where one branch makes the recursive call, and other doesn't.
#include <stdio.h>
int main() {
scanf("%d", &number);
result = sum(number);
return 0;
int sum(int n) {
if (n != 0)
return n + sum(n-1);
else
return n;
}
Output
When n is equal to 0, the if condition fails and the else part is executed returning the
sum of integers ultimately to the main() function.
Sum of Natural Numbers
Before we wrap up, let’s put your knowledge of C Recursion to the test! Can you
solve the following challenge?
Challenge:
Day 19
C Storage Class
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope,
visibility and lifetime of a variable.
1. automatic
2. external
3. static
4. register
Local Variable
The variables declared inside a block are automatic or local variables. The local
variables exist only inside the block in which it is declared.
int main(void) {
printf("C programming");
printf("%d", i);
return 0;
Run Code
When you run the above program, you will get an error undeclared identifier i. It's
because i is declared inside the for loop block. Outside of the block, it's undeclared.
int main() {
void func() {
}
In the above example, n1 is local to main() and n2 is local to func().
This means you cannot access the n1 variable inside func() as it only exists
inside main(). Similarly, you cannot access the n2 variable inside main() as it only
exists inside func().
Global Variable
Variables that are declared outside of all functions are known as external or global
variables. They are accessible from any function inside the program.
#include <stdio.h>
void display();
int main()
++n;
display();
return 0;
void display()
{
++n;
Run Code
Output
n=7
Suppose, a global variable is declared in file1. If you try to use that variable in a
different file file2, the compiler will complain. To solve this problem, keyword extern is
used in file2 to indicate that the external variable is declared in another file.
Register Variable
The register keyword is used to declare register variables. Register variables were
supposed to be faster than local variables.
However, modern compilers are very good at code optimization, and there is a rare
chance that using register variables will make your program faster.
Unless you are working on embedded systems where you know how to optimize
code for the given application, there is no use of register variables.
Static Variable
static int i;
The value of a static variable persists until the end of the program.
#include <stdio.h>
void display();
int main()
display();
display();
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}
Run Code
Output
6 11
During the first function call, the value of c is initialized to 1. Its value is increased by
5. Now, the value of c is 6, which is printed on the screen.
During the second function call, c is not initialized to 1 again. It's because c is a static
variable. The value c is increased by 5. Now, its value will be 11, which is printed on
the screen.
Day 20
C Arrays
Arrays in C
An array is a variable that can store multiple values. For example, if you want to
store 100 integers, you can create an array for it.
int data[100];
dataType arrayName[arraySize];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it
can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed once it is
declared.
Suppose you declared an array mark as above. The first element is mark[0], the
second element is mark[1] and so on.
Declare an Array
Few keynotes:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first
element.
If the size of an array is n, to access the last element, the n-1 index is used. In
this example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the address of
the mark[1] will be 2124d. Similarly, the address of mark[2] will be 2128d and
so on.
This is because the size of a float is 4 bytes.
Here, we haven't specified the size. However, the compiler knows its size is 5 as we
are initializing it with 5 elements.
Initialize an Array
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
mark[2] = -1;
mark[4] = 0;
Here's how you can take input from the user and store it in an array element.
scanf("%d", &mark[2]);
scanf("%d", &mark[i-1]);
Here's how you can print an individual element of an array.
// print the first element
printf("%d", mark[0]);
printf("%d", mark[2]);
printf("%d", mark[i-1]);
// Program to take 5 values from the user and store them in an array
#include <stdio.h>
int main() {
int values[5];
scanf("%d", &values[i]);
}
return 0;
Run Code
Output
Enter 5 integers: 1
-3
34
Displaying integers: 1
-3
34
Here, we have used a for loop to take five inputs and store them in an array. Then,
these elements are printed using another for loop.
#include <stdio.h>
int main() {
double average;
printf("Enter number of elements: ");
scanf("%d", &n);
scanf("%d", &marks[i]);
return 0;
Run Code
Output
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39.60
Here, we have computed the average of n numbers entered by the user.
Access elements out of its bound!
int testArray[10];
Now let's say if you try to access testArray[12]. The element is not available. This
may cause unexpected output (undefined behavior). Sometimes, you might get an
error, and some other times your program may run correctly.
Hence, you should never access elements of an array outside of its bound.
Multidimensional arrays
In this tutorial, you learned about arrays. These arrays are called one-dimensional
arrays.
In the next tutorial, you will learn about multidimensional arrays (array of an array).
Before we wrap up, let’s put your knowledge of C Arrays to the test! Can you solve
the following challenge?
Challenge:
The function takes an array of integer array and an integer array_size, which
is the length of the array.
Return the sum of the first and last elements of the array.
For example, if array = [10, 20, 30, 40, 50] and array_size = 5, the expected
output is 60.
1
Day 21
C Multidimensional Arrays
In C programming, you can create an array of arrays. These arrays are known as
multidimensional arrays. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can
think the array as a table with 3 rows and each row has 4 columns.
float y[2][4][3];
Here, the array y can hold 24 elements.
Initialization of a 2d array
Initialization of a 3d array
int test[2][3][4] = {
#include <stdio.h>
int main()
{
int temperature[CITY][WEEK];
scanf("%d", &temperature[i][j]);
}
}
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
return 0;
Run Code
Output
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26
#include <stdio.h>
int main()
{
scanf("%f", &a[i][j]);
scanf("%f", &b[i][j]);
{
printf("%.1f\t", result[i][j]);
if (j == 1)
printf("\n");
return 0;
Run Code
Output
Enter a11: 2;
Enter a22: 2;
Enter b12: 0;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
#include <stdio.h>
int main()
{
int test[2][3][2];
{
for (int k = 0; k < 2; ++k)
scanf("%d", &test[i][j][k]);
printf("\nDisplaying values:\n");
}
return 0;
Run Code
Output
Enter 12 values:
3
4
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
Day 22
In C programming, you can pass an entire array to functions. Before we learn that,
let's see how you can pass individual elements of an array to functions.
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
int main() {
display(ageArray[1], ageArray[2]);
return 0;
}
Run Code
Output
Here, we have passed array parameters to the display() function in the same way we
pass variables to a function.
display(ageArray[1], ageArray[2]);
We can see this in the function definition, where the function parameters are
individual variables:
// code
}
#include <stdio.h>
float calculateSum(float num[]);
int main() {
result = calculateSum(num);
}
float calculateSum(float num[]) {
sum += num[i];
return sum;
}
Run Code
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an
argument.
result = calculateSum(num);
... ..
}
This informs the compiler that you are passing a one-dimensional array to the
function.
To pass multidimensional arrays to a function, only the name of the array is passed
to the function (similar to one-dimensional arrays).
Example 3: Pass two-dimensional arrays
#include <stdio.h>
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
scanf("%d", &num[i][j]);
displayNumbers(num);
return 0;
printf("Displaying:\n");
printf("%d\n", num[i][j]);
Run Code
Output
Enter 4 numbers:
4
5
Displaying:
Notice the parameter int num[2][2] in the function prototype and function definition:
// function prototype
For example,
void displayNumbers(int num[][2]) {
// code