0% found this document useful (0 votes)
23 views114 pages

C Rkhussain Sir

Uploaded by

abdulhussain0886
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views114 pages

C Rkhussain Sir

Uploaded by

abdulhussain0886
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

RK HUSSAIN 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

 8. C Structure and Union

 9. C Programming Files

 10. C Additional Topics

 C Introduction
o Getting Started with C

o Your First C Program

o C Comments

 C Fundamentals

o C Variables, Constants and Literals


o C Data Types
o C Input Output (I/O)
o C Programming Operators

 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

 C Structure and Union

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

o C Keywords and Identifiers


o C Precedence And Associativity Of Operators
o C Bitwise Operators
o C Preprocessor and Macros
o C Standard Library Functions
o C enums

Getting Started with C

C is a powerful general-purpose programming language known for its efficiency and


flexibility.

You can run C on your computer using the following two methods:

 Run C online
 Install C on your computer

In this tutorial, you will learn both methods.


Run C Online

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.

Install C on Your Computer

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

To install a C programming environment on Windows, you'll need two main


components:
 VS Code: A text editor to write your code,

 MinGW: A compiler that turns your C code into an executable program.

Follow the steps below to install C on Windows:

1. Install VS Code

2. Download MinGW Compiler

3. Run the installer

4. Add MinGW to System PATH

5. Install C/C++ Extension in VS Code

Here's a detailed explanation of each of the steps.


Step 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.

Step 2: Download MinGW Compiler

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.

Include gcc-core package

During installation, you will be prompted to select the components to install.


Mark mingw32-base for installation, click on installation and apply changes.

C GCC-Core Package Installation

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.

C Setting Environment Variables


Then, find the Path variable in the System variables section and click on Edit.
Click New and add the path to the bin directory within your MinGW installation (i.e.
C:\MinGW\bin)
FInally, close all the dialogues with the Ok button.
Step 5: Install C/C++ Extension in VS Code

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.

Installing C Extension in Windows

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.

and this is a code block

Run Your First C Program

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)

Now, write the following code into your file:

#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

You should see Hello World printed to the command prompt.


For Linux System

Instead of the run button as in Windows and macOS, you should follow the following
steps to run your C program on Linux.

In Terminal, navigate to your file's directory, and compile with

gcc hello.c -o hello

After compiling successfully, you'll see a new file named hello (or hello.exe on
Windows) in the same directory.

Run your program using

./hello

Congratulations! You've written and executed your first C program.

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.

Your First C Program

In the previous tutorial you learned how to install C on your computer. Now, let's write
a simple C program.

The following program displays Hello, World! on the screen.

#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

Notice the following line of 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 ().

 The text to be printed is enclosed within double quotes "".

 Each printf statement ends with a semicolon ;.

Not following the above rules will result in errors and your code will not run
successfully.

Basic Structure of a C Program

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;

And, we will write out code inside curly braces {}.


Next, we will be learning about C comments.

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.

Comments are completely ignored by C compilers.

For example,

#include <stdio.h>

int main() {

// print Hello World to the screen


printf("Hello World");

return 0;

Run Code
Output

Hello World

Here, // print Hello World to the screen is a comment in C programming. The C


compiler ignores everything after the // symbol.
Note: You can ignore the programming concepts and simply focus on
the comments. We will revisit these concepts in later tutorials.

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() {

// create integer variable

int age = 25;

// print the age variable


printf("Age: %d", age);

return 0;

Run Code
Output

Age: 25

In the above example, we have used two single-line comments:


 // create integer variable

 // print the age variable

We can also use the single line comment along with the code.

int age = 25; // create integer variable

Here, code before // are executed and code after // are ignored by the compiler.

Multi-line Comments in C

In C programming, there is another type of comment that allows us to comment on


multiple lines at once, they are multi-line comments.

To write multi-line comments, we use the /*....*/ symbol. For example,


/* This program takes age input from the user

It stores it in the age variable

And, print the value using printf() */

#include <stdio.h>

int main() {

// create integer variable

int age = 25;


// print the age variable

printf("Age: %d", age);

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:

 Single Line comment: ctrl + / (windows) and cmd + / (mac)

 Multi line comment: ctrl + shift + / (windows) and cmd + shift + / (mac)

Prevent Executing Code Using Comments

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() {

int number1 = 10;

int number2 = 15;

int sum = number1 + number2;

printf("The sum is: %d\n", sum);

printf("The product is: %d\n", product);


return 0;

}
Run Code
Here, the code throws an error because we have not defined a product variable.

We can comment out the code that's causing the error.

For example,

#include <stdio.h>

int main() {

int number1 = 10;

int number2 = 15;


int sum = number1 + number2;

printf("The sum is: %d\n", sum);

// printf("The product is: %d\n", product);

return 0;

Run Code

Now, the code runs without any errors.

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.

Why use Comments?

We should use comments for the following reasons:

 Comments make our code readable for future reference.


 Comments are used for debugging purposes.

 We can use comments for code collaboration as it helps peer developers to


understand our code.
Note: Comments are not and should not be used as a substitute to explain poorly
written code. Always try to write clean, understandable code, and then use
comments as an addition.
In most cases, always use comments to explain 'why' rather than 'how' and you are
good to go.

Next, we will be learning in detail about C Variables, constants and literals.


Day4

C Variables, Constants and Literals

In the previous tutorial you learnt about C comments. Now, let's learn about
variables, constants and literals in C.
Variables

In programming, a variable is a container (storage area) to hold data.

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.

The value of a variable can be changed, hence the name variable.

char ch = 'a';

// some code

ch = 'l';

Visit this page to learn more about different types of data a variable can store.

What are the rules for naming a variable?

Can we change the data type of a variable?

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;

Notice, we have added keyword const.

Here, PI is a symbolic constant; its value cannot be changed.

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

An integer is a numeric literal(associated with numbers) without any fractional or


exponential part. There are three types of integer literals in C programming:

 decimal (base 10)


 octal (base 8)

 hexadecimal (base 16)

For example:

Decimal: 0, -9, 22 etc

Octal: 021, 077, 033 etc

Hexadecimal: 0x7f, 0x2a, 0x521 etc

In C programming, octal starts with a 0, and hexadecimal starts with a 0x.

2. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an


exponent form. For example:

-2.0
0.0000234
-0.22E-5
Note: E-5 = 10-5

3. Characters

A character literal is created by enclosing a single character inside single quotation


marks. For example: 'a', 'm', 'F', '2', '}' etc.

4. String Literals

A string literal is a sequence of characters enclosed in double-quote marks. For


example:

"good" //string constant

"" //null string constant

" " //string constant of six white space


"x" //string constant having a single character.

"Earth is round\n" //prints string with a newline

5. Escape Sequences

Sometimes, it is necessary to use characters that cannot be typed or has special


meaning in C programming. For example: newline(enter), tab, question mark etc.

In order to use these characters, escape sequences are used.

Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return
\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? 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.

Type Size (bytes) Format Specifier

int at least 2, usually 4 %d, %i

char 1 %c

float 4 %f

double 8 %lf

short int 2 usually %hd

unsigned int at least 2, usually 4 %u

long int at least 4, usually 8 %ld, %li

long long int at least 8 %lld, %lli

unsigned long int at least 4 %lu

unsigned long long int at least 8 %llu

signed char 1 %c

unsigned char 1 %c

long double at least 10, usually 12 or 16 %Lf


int

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;

Here, id is a variable of type integer.

You can declare multiple variables at once in C programming. For example,

int id, age;

The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -
2147483648 to 2147483647.

float and double

float and double are used to hold real numbers.


float salary;

double price;

In C, floating-point numbers can also be represented in exponential. For example,

float normalizationFactor = 22.442e2;

What's the difference between float and double?

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';

The size of the character variable is 1 byte.

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.

short and long

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;

printf("size of short = %d bytes\n", sizeof(a));

printf("size of long = %d bytes\n", sizeof(b));

printf("size of long long = %d bytes\n", sizeof(c));

printf("size of long double= %d bytes\n", sizeof(d));

return 0;

Run Code

signed and unsigned


In C, signed and unsigned are type modifiers. You can alter the data storage of a
data type by using them:

 signed - allows for storage of both positive and negative numbers


 unsigned - allows for storage of only positive numbers

For example,

// valid codes

unsigned int x = 35;

int y = -35; // signed int

int z = 36; // signed int

// invalid code: unsigned int cannot hold negative integers

unsigned int num = -35;

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.

Derived Data Types

Data types that are derived from fundamental data types are derived types. For
example: arrays, pointers, function types, structures, etc.

We will learn about these derived data types in later tutorials.

 bool type

 Enumerated type

 Complex types


Day 6

C Input Output (I/O)

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()

// Displays the string inside quotations

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.

Example 2: Integer Output

#include <stdio.h>
int main()
{

int testInteger = 5;

printf("Number = %d", testInteger);

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.

Example 3: float and double Output

#include <stdio.h>

int main()

float number1 = 13.5;

double number2 = 12.4;

printf("number1 = %f\n", number1);

printf("number2 = %lf", number2);

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.

Example 4: Print Characters


#include <stdio.h>

int main()

char chr = 'a';

printf("character = %c", chr);

return 0;

Run Code
Output

character = a

To print char, we use %c format specifier.

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.

Example 5: Integer Input/Output

#include <stdio.h>
int main()

int testInteger;

printf("Enter an integer: ");

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.

Example 6: Float and Double Input/Output

#include <stdio.h>

int main()

float num1;

double num2;

printf("Enter a number: ");

scanf("%f", &num1);

printf("Enter another number: ");

scanf("%lf", &num2);

printf("num1 = %f\n", num1);

printf("num2 = %lf", num2);

return 0;
}

Run Code
Output

Enter a number: 12.523

Enter another number: 10.2

num1 = 12.523000
num2 = 10.200000
We use %f and %lf format specifier for float and double respectively.

Example 7: C Character I/O

#include <stdio.h>

int main()

char chr;

printf("Enter a character: ");


scanf("%c",&chr);

printf("You entered %c.", 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.

Example 8: ASCII Value

#include <stdio.h>

int main()

char chr;

printf("Enter a character: ");


scanf("%c", &chr);

// When %c is used, a character is displayed


printf("You entered %c.\n",chr);

// When %d is used, ASCII value is displayed

printf("ASCII value is %d.", chr);

return 0;

Run Code

Output
Enter a character: g

You entered g.

ASCII value is 103.

I/O Multiple Values

Here's how you can take multiple inputs from the user and display them.

#include <stdio.h>

int main()

int a;

float b;

printf("Enter integer and then a float: ");

// Taking multiple inputs


scanf("%d%f", &a, &b);

printf("You entered %d and %f", a, b);

return 0;

}
Run Code
Output

Enter integer and then a float: -3

3.4

You entered -3 and 3.400000

Format Specifiers for I/O

As you can see from the above examples, we use

 %d for int
 %f for float

 %lf for double

 %c for char

Here's a list of commonly used C data types and their format specifiers.

Data Type Format Specifier

int %d

char %c

float %f

double %lf

short int %hd

unsigned int %u

long int %li

long long int %lli


Data Type Format Specifier

unsigned long int %lu

unsigned long long int %llu

signed char %c

unsigned char %c

long double %Lf

Day7

C Programming Operators

An operator is a symbol that operates on a value or a variable. For example: + is an


operator to perform addition.

C has a wide range of operators to perform various operations.

C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition,


subtraction, multiplication, division etc on numerical values (constants and
variables).

Operator Meaning of Operator

+ addition or unary plus


Operator Meaning of Operator

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)

Example 1: Arithmetic Operators

// Working of arithmetic operators


#include <stdio.h>
int main()

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;

printf("Remainder when a divided by b = %d \n",c);

return 0;
}
Run Code
Output

a+b = 13

a-b = 5

a*b = 36

a/b = 2

Remainder when a divided by b=1

The operators +, - and * computes addition, subtraction, and multiplication


respectively as you might have expected.

In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.

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.

Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,

// Either one of the operands is a floating-point number

a/b = 2.5
a/d = 2.5

c/b = 2.5

// Both operands are integers

c/d = 2

C Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the


value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by
1. These two operators are unary operators, meaning they only operate on a single
operand.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators

#include <stdio.h>

int main()

int a = 10, b = 100;

float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);

printf("++c = %f \n", ++c);

printf("--d = %f \n", --d);

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

An assignment operator is used for assigning a value to a variable. The most


common assignment operator is =
Operator Example Same as

= 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

Example 3: Assignment Operators

// Working of assignment operators

#include <stdio.h>

int main()

int a = 5, c;

c = a; // c is 5

printf("c = %d\n", c);

c += a; // c is 10

printf("c = %d\n", c);

c -= a; // c is 5

printf("c = %d\n", c);

c *= a; // c is 25

printf("c = %d\n", c);

c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0

printf("c = %d\n", c);

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.

Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1


Operator Meaning of Operator Example

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators

// Working of relational operators

#include <stdio.h>

int main()

int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);

printf("%d == %d is %d \n", a, c, a == c);

printf("%d > %d is %d \n", a, b, a > b);

printf("%d > %d is %d \n", a, c, a > c);

printf("%d < %d is %d \n", a, b, a < b);

printf("%d < %d is %d \n", a, c, a < c);

printf("%d != %d is %d \n", a, b, a != b);

printf("%d != %d is %d \n", a, c, a != c);

printf("%d >= %d is %d \n", a, b, a >= b);

printf("%d >= %d is %d \n", a, c, a >= c);

printf("%d <= %d is %d \n", a, b, a <= b);

printf("%d <= %d is %d \n", a, c, a <= c);

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

An expression containing logical operator returns either 0 or 1 depending upon


whether expression results true or false. Logical operators are commonly used
in decision making in C programming.

Operator Meaning Example

Logical AND. True only if all If c = 5 and d = 2 then, expression ((c=


&&
operands are true && (d>5)) equals to 0.

Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c=
||
operand is true (d>5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression !(c==5) equals


!
operand is 0 0.

Example 5: Logical Operators

// Working of logical operators

#include <stdio.h>

int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);

printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);

printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) || (c < b);

printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);

printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);

printf("!(a != b) is %d \n", result);

result = !(a == b);

printf("!(a == b) is %d \n", 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

 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c >


b) is 1 (true).

 (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).

 (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).

 (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are


0 (false).

 !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b)


is 1 (true).

 !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0


(false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction,


multiplication, division, etc are converted to bit-level which makes processing faster
and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Visit bitwise operator in C to learn more.


Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

The sizeof operator

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;

printf("Size of int=%lu bytes\n",sizeof(a));


printf("Size of float=%lu bytes\n",sizeof(b));

printf("Size of double=%lu bytes\n",sizeof(c));

printf("Size of char=%lu byte\n",sizeof(d));

return 0;

Run Code
Output

Size of int = 4 bytes

Size of float = 4 bytes


Size of double = 8 bytes
Size of char = 1 byte

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.

 Return the smallest of the two numbers a and b.


 For example, if a = 3, and b = 7, the expected output is 3.

Check Code

Day 8

C if...else Statement

C if Statement

The syntax of the if statement in C programming is:

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

// Program to display a number if it is negative

#include <stdio.h>

int main() {

int number;

printf("Enter an integer: ");

scanf("%d", &number);

// true if number is less than 0

if (number < 0) {

printf("You entered %d.\n", number);


}
printf("The if statement is easy.");

return 0;

Run Code
Output 1

Enter an integer: -2
You entered -2.

The if statement is easy.

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

The if statement is easy.

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

The if statement may have an optional else block. The syntax of


the if..else statement is:

if (test expression) {

// run code if test expression is true


}

else {

// run code if test expression is false

How if...else statement works?

If the test expression is evaluated to true,


 statements inside the body of if are executed.

 statements inside the body of else are skipped from execution.

If the test expression is evaluated to false,

 statements inside the body of else are executed

 statements inside the body of if are skipped from execution.

Working of if...else Statement

Example 2: if...else statement

// Check whether an integer is odd or even

#include <stdio.h>

int main() {

int number;

printf("Enter an integer: ");

scanf("%d", &number);

// True if the remainder is 0

if (number%2 == 0) {

printf("%d is an even integer.",number);

}
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.

Syntax of if...else Ladder

if (test expression1) {

// statement(s)

else if(test expression2) {

// statement(s)

else if (test expression3) {

// statement(s)

}
.
.

else {

// statement(s)

Example 3: C if...else Ladder

// Program to relate two integers using =, > or < symbol

#include <stdio.h>

int main() {

int number1, number2;

printf("Enter two integers: ");

scanf("%d %d", &number1, &number2);

//checks if the two integers are equal.

if(number1 == number2) {

printf("Result: %d = %d",number1,number2);

//checks if number1 is greater than number2.

else if (number1 > number2) {

printf("Result: %d > %d", number1, number2);

//checks if both test expressions are false

else {

printf("Result: %d < %d",number1, number2);

}
return 0;

Run Code
Output

Enter two integers: 12

23

Result: 12 < 23

Nested if...else

It is possible to include an if...else statement inside the body of


another if...else statement.

Example 4: 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() {

int number1, number2;

printf("Enter two integers: ");

scanf("%d %d", &number1, &number2);

if (number1 >= number2) {


if (number1 == number2) {

printf("Result: %d = %d",number1,number2);

else {

printf("Result: %d > %d", number1, number2);

}
}
else {

printf("Result: %d < %d",number1, number2);

return 0;

Run Code

If the body of an if...else statement has only one statement, you do not need to use
brackets {}.

For example, this code

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.

 Return "Pass" if the score is 50 or above and "Fail" otherwise.


 For example, with input 55, the return value should be "Pass".
1

Day 9

C for Loop

In programming, a loop is used to repeat a block of code until the specified condition
is met.

C programming has three types of loops:

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

The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)

{
// statements inside the body of loop

How for loop works?

 The initialization statement is executed only once.

 Then, the test expression is evaluated. If the test expression is evaluated to


false, the for loop is terminated.

 However, if the test expression is evaluated to true, statements inside the


body of the for loop are executed, and the update expression is updated.

 Again the test expression is evaluated.


This process goes on until the test expression is false. When the test expression is
false, the loop terminates.
To learn more about test expression (when the test expression is evaluated to true
and false), check out relational and logical operators.

for loop Flowchart

Working of for loop

Example 1: for loop

// Print numbers from 1 to 10

#include <stdio.h>

int main() {

int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", 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.

Example 2: for loop

// Program to calculate the sum of first n natural numbers

// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>

int main()

int num, count, sum = 0;

printf("Enter a positive integer: ");

scanf("%d", &num);

// for loop terminates when count exceeds num


for(count = 1; count <= num; ++count)

sum += count;

printf("Sum = %d", sum);

return 0;
}

Run Code
Output

Enter a positive integer: 10

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.

Then, the value of sum is printed on the screen.

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.

 The factorial of a non-negative integer n is the product of all positive integers


less than or equal to n.
 For example, the factorial of 3 is 3 * 2 * 1 = 6.

 Return the factorial of the input number num.

Day10

C while and do...while Loop

In programming, loops are used to repeat a block of code until a specified condition
is met.

C programming has three types of loops.

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

The syntax of the while loop is:

while (testExpression) {

// the body of the loop

How while loop works?


 The while loop evaluates the testExpression inside the parentheses ().
 If testExpression is true, statements inside the body of while loop are
executed. Then, testExpression is evaluated again.
 The process goes on until testExpression is evaluated to false.

 If testExpression is false, the loop terminates (ends).

To learn more about test expressions (when testExpression is evaluated


to true and false), check out relational and logical operators.

Flowchart of while loop

Working of while loop

Example 1: while loop

// Print numbers from 1 to 5

#include <stdio.h>

int main() {

int i = 1;

while (i <= 5) {
printf("%d\n", i);
++i;

return 0;

Run Code
Output

1
2

Here, we have initialized i to 1.


1. When i = 1, the test expression i <= 5 is true. Hence, the body of
the while loop is executed. This prints 1 on the screen and the value of i is
increased to 2.
2. Now, i = 2, the test expression i <= 5 is again true. The body of the while loop
is executed again. This prints 2 on the screen and the value of i is increased
to 3.

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.

The syntax of the do...while loop is:

do {

// the body of the loop

}
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.

 If testExpression is false, the loop ends.

Flowchart of do...while Loop

Working of do...while loop

Example 2: do...while loop

// Program to add numbers until the user enters zero

#include <stdio.h>

int main() {

double number, sum = 0;

// the body of the loop is executed at least once

do {
printf("Enter a number: ");
scanf("%lf", &number);

sum += number;

while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}

Run Code
Output

Enter a number: 1.5

Enter a number: 2.4

Enter a number: -3.4

Enter a number: 4.2

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.

Outside the loop, we print the value of sum.


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:

Write a function to count the number of digits in a given number.

 Return the number of digits in num.


 For example, if num = 12345, the expected output is 5.

Day 11

C break and continue


C break

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.

How break statement works?


Working of break in C

Example 1: break statement

// Program to calculate the sum of numbers (10 numbers max)

// If the user enters a negative number, the loop terminates

#include <stdio.h>

int main() {

int i;

double number, sum = 0.0;

for (i = 1; i <= 10; ++i) {


printf("Enter n%d: ", i);

scanf("%lf", &number);

// if the user enters a negative number, break the loop


if (number < 0.0) {
break;

sum += number; // sum = sum + number;

printf("Sum = %.2lf", sum);

return 0;

Run Code
Output

Enter n1: 2.4

Enter n2: 4.5

Enter n3: 3.4

Enter n4: -3

Sum = 10.30

This program calculates the sum of a maximum of 10 numbers. Why a maximum of


10 numbers? It's because if the user enters a negative number, the break statement
is executed. This will end the for loop, and the sum is displayed.

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.

How continue statement works?


Working of
Continue in C

Example 2: continue statement

// Program to calculate the sum of numbers (10 numbers max)

// If the user enters a negative number, it's not added to the result

#include <stdio.h>

int main() {
int i;

double number, sum = 0.0;

for (i = 1; i <= 10; ++i) {

printf("Enter a n%d: ", i);

scanf("%lf", &number);

if (number < 0.0) {

continue;
}
sum += number; // sum = sum + number;

printf("Sum = %.2lf", sum);

return 0;

}
Run Code
Output

Enter n1: 1.1

Enter n2: 2.2

Enter n3: 5.5

Enter n4: 4.4

Enter n5: -3.4

Enter n6: -45.5

Enter n7: 34.5

Enter n8: -4.2

Enter n9: -1000

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.

 For example, if num = 5, the expected output is 1.

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 there is no match, the default statements are executed.


Notes:

 If we do not use the break statement, all statements after the matching label
are also executed.

 The default clause inside the switch statement is optional.

switch Statement Flowchart


switch Statement
Flowchart

Example: Simple Calculator

// Program to create a simple calculator

#include <stdio.h>

int main() {
char operation;
double n1, n2;

printf("Enter an operator (+, -, *, /): ");

scanf("%c", &operation);

printf("Enter two operands: ");

scanf("%lf %lf",&n1, &n2);

switch(operation)
{

case '+':

printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);

break;

case '-':

printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);

break;

case '*':

printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);

break;

case '/':

printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);


break;

// operator doesn't match any case constant +, -, *, /

default:

printf("Error! operator is not correct");


}
return 0;

Run Code
Output

Enter an operator (+, -, *, /): -

Enter two operands: 32.5

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.

Since the operation is -, the control of the program jumps to

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

Finally, the break statement terminates the switch statement.

Day13

C goto Statement

The goto statement allows us to transfer control of the program to the specified label.

Syntax of goto Statement

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.

Working of goto Statement

Example: goto Statement

// Program to calculate the sum and average of positive numbers

// If the user enters a negative number, the sum and average are displayed.

#include <stdio.h>

int main() {

const int maxInput = 100;

int i;

double number, average, sum = 0.0;

for (i = 1; i <= maxInput; ++i) {

printf("%d. Enter a number: ", i);

scanf("%lf", &number);

// go to jump if the user enters a negative number

if (number < 0.0) {


goto jump;

}
sum += number;

jump:

average = sum / (i - 1);

printf("Sum = %.2f\n", sum);

printf("Average = %.2f", average);

return 0;

Run Code
Output

1. Enter a number: 3

2. Enter a number: 4.3

3. Enter a number: 9.3

4. Enter a number: -2.9

Sum = 16.60

Average = 5.53

Reasons to avoid goto

The use of goto statement may lead to code that is buggy and hard to follow. For
example,

one:

for (i = 0; i < number; ++i)

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.

Should you use goto?

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

A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can create
two functions to solve this problem:

 create a circle function

 create a color function

Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.

Types of function

There are two types of function in C programming:


 Standard library functions

 User-defined functions

Standard library functions

The standard library functions are built-in functions in C programming.

These functions are defined in header files. For example,

 The printf() is a standard library function to send formatted output to the


screen (display output on the screen). This function is defined in
the stdio.h header file.
Hence, to use the printf()function, we need to include the stdio.h header file
using #include <stdio.h>.

 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();

... .. ...

... .. ...

The execution of a C program begins from the main() function.

When the compiler encounters functionName();, control of the program jumps to

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

Note, function names are identifiers and should be unique.


This is just an overview of user-defined functions. Visit these pages to learn more on:

 User-defined Function in C programming

 Types of user-defined Functions

Advantages of user-defined function

1. The program will be easier to understand, maintain and debug.

2. Reusable codes that can be used in other programs

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

A function is a block of code that performs a specific task.


C allows you to define functions according to your need. These functions are known
as user-defined functions. For example:

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

Example: User-defined 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;

printf("Enters two numbers: ");

scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call

printf("sum = %d",sum);

return 0;

int addNumbers(int a, int b) // function definition

int result;

result = a+b;

return result; // return statement

Function prototype

A function prototype is simply the declaration of a function that specifies function's


name, parameters and return type. It doesn't contain function body.

A function prototype gives information to the compiler that the function may later be
used in the program.
Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2, ...);

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()

2. return type of the function is int

3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before
the main() function.

Calling a function

Control of the program is transferred to the user-defined function by calling it.


Syntax of function call

functionName(argument1, argument2, ...);

In the above example, the function call is made using addNumbers(n1,


n2); statement inside the main() function.

Function definition

Function definition contains the block of code to perform a specific task. In our
example, adding two numbers and returning it.

Syntax of function definition

returnType functionName(type1 argument1, type2 argument2, ...)

//body of the function

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.

Passing arguments to 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.

If n1 is of char type, a also should be of char type. If n2 is of float type,


variable b also should be of float type.

A function can also be called without passing an argument.

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

Types of User-defined Functions in C Programming

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.

Example 1: No Argument Passed and No Return Value

#include <stdio.h>

void checkPrimeNumber();

int main() {

checkPrimeNumber(); // argument is not passed

return 0;

// return type is void meaning doesn't return any value

void checkPrimeNumber() {

int n, i, flag = 0;

printf("Enter a positive integer: ");

scanf("%d",&n);
// 0 and 1 are not prime numbers

if (n == 0 || n == 1)

flag = 1;

for(i = 2; i <= n/2; ++i) {

if(n%i == 0) {

flag = 1;

break;
}

if (flag == 1)

printf("%d is not a prime number.", n);

else

printf("%d is a prime number.", n);

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 empty parentheses in checkPrimeNumber(); inside the main() function indicates


that no argument is passed to the function.

The return type of the function is void. Hence, no value is returned from the function.

Example 2: No Arguments Passed But Returns a Value

#include <stdio.h>

int getInteger();

int main() {

int n, i, flag = 0;
// no argument is passed

n = getInteger();

// 0 and 1 are not prime numbers

if (n == 0 || n == 1)

flag = 1;

for(i = 2; i <= n/2; ++i) {

if(n%i == 0){

flag = 1;

break;

if (flag == 1)

printf("%d is not a prime number.", n);

else

printf("%d is a prime number.", n);

return 0;

// returns integer entered by the user

int getInteger() {

int n;

printf("Enter a positive integer: ");


scanf("%d",&n);
return n;

Run Code

The empty parentheses in the n = getInteger(); statement indicates that no argument


is passed to the function. And, the value returned from the function is assigned to n.

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.

Example 3: Argument Passed But No Return Value

#include <stdio.h>

void checkPrimeAndDisplay(int n);

int main() {

int n;

printf("Enter a positive integer: ");

scanf("%d",&n);

// n is passed to the function

checkPrimeAndDisplay(n);

return 0;

// return type is void meaning doesn't return any value


void checkPrimeAndDisplay(int n) {

int i, flag = 0;
// 0 and 1 are not prime numbers

if (n == 0 || n == 1)

flag = 1;

for(i = 2; i <= n/2; ++i) {

if(n%i == 0){

flag = 1;

break;
}

if(flag == 1)

printf("%d is not a prime number.",n);

else

printf("%d is a prime number.", n);

Run Code

The integer value entered by the user is passed to


the checkPrimeAndDisplay() function.

Here, the checkPrimeAndDisplay() function checks whether the argument passed is


a prime number or not and displays the appropriate message.

Example 4: Argument Passed and Returns a Value

#include <stdio.h>

int checkPrimeNumber(int n);

int main() {

int n, flag;
printf("Enter a positive integer: ");

scanf("%d",&n);

// n is passed to the checkPrimeNumber() function

// the returned value is assigned to the flag variable

flag = checkPrimeNumber(n);

if(flag == 1)
printf("%d is not a prime number",n);

else

printf("%d is a prime number",n);

return 0;

// int is returned from the function

int checkPrimeNumber(int n) {

// 0 and 1 are not prime numbers

if (n == 0 || n == 1)

return 1;

int i;

for(i=2; i <= n/2; ++i) {

if(n%i == 0)

return 1;

}
return 0;

Run Code

The input from the user is passed to the checkPrimeNumber() function.

The checkPrimeNumber() function checks whether the passed argument is prime or


not.
If the passed argument is a prime number, the function returns 0. If the passed
argument is a non-prime number, the function returns 1. The return value is assigned
to the flag variable.
Depending on whether flag is 0 or 1, an appropriate message is printed from
the main() function.

Which approach is better?

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.

A function should perform a specific task. The checkPrimeNumber() function doesn't


take input from the user nor it displays the appropriate message. It only checks
whether a number is prime or not.

Day 17

C Recursion

Recursion is the process of defining something in terms of itself.

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.

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>

int sum(int n);

int main() {

int number, result;

printf("Enter a positive integer: ");

scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);

return 0;

int sum(int n) {

if (n != 0)

// sum() function calls itself

return n + sum(n-1);

else

return n;

}
Output

Enter a positive integer:3


sum = 6
Initially, the sum() is called from the main() function with number passed as an
argument.
Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is
passed to the sum() function. This process continues until n is equal to 0.

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

Advantages and Disadvantages of Recursion

Recursion makes program elegant. However, if performance is vital, use loops


instead as recursion is usually much slower.
That being said, recursion is an important concept. It is frequently used in data
structure and algorithms. For example, it is common to use recursion in problems
such as tree traversal.

Before we wrap up, let’s put your knowledge of C Recursion to the test! Can you
solve the following challenge?

Challenge:

Write a function to calculate the factorial of a number.

 The factorial of a non-negative integer n is the product of all positive integers


less than or equal to n.
 For example, the factorial of 3 is 3 * 2 * 1 = 6.

 Return the factorial of the input number num.

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.

There are 4 types of storage class:

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.

Let's take an example.


#include <stdio.h>

int main(void) {

for (int i = 0; i < 5; ++i) {

printf("C programming");

// Error: i is not declared at this point

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.

Let's take another example.

int main() {

int n1; // n1 is a local variable to main()

void func() {

int n2; // n2 is a local variable to 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.

Example 1: Global Variable

#include <stdio.h>

void display();

int n = 5; // global variable

int main()

++n;

display();

return 0;

void display()

{
++n;

printf("n = %d", 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

A static variable is declared by using the static keyword. For example;

static int i;

The value of a static variable persists until the end of the program.

Example 2: Static Variable

#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];

How to declare an array?

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.

Access Array Elements

You can access elements of an array by indices.

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.

How to initialize an array?

It is possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

You can also initialize an array like this.

int mark[] = {19, 10, 8, 17, 9};

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

Change Value of Array elements

int mark[5] = {19, 10, 8, 17, 9}

// make the value of the third element to -1

mark[2] = -1;

// make the value of the fifth element to 0

mark[4] = 0;

Input and Output Array Elements

Here's how you can take input from the user and store it in an array element.

// take input and store it in the 3rd element

scanf("%d", &mark[2]);

// take input and store it in the ith element

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]);

// print the third element

printf("%d", mark[2]);

// print the ith element\

printf("%d", mark[i-1]);

Example 1: Array Input/Output

// Program to take 5 values from the user and store them in an array

// Print the elements stored in the array

#include <stdio.h>

int main() {

int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array

for(int i = 0; i < 5; ++i) {

scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of the array


for(int i = 0; i < 5; ++i) {
printf("%d\n", 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.

Example 2: Calculate Average

// Program to find the average of n numbers using arrays

#include <stdio.h>

int main() {

int marks[10], i, n, sum = 0;

double average;
printf("Enter number of elements: ");

scanf("%d", &n);

for(i=0; i < n; ++i) {

printf("Enter number%d: ",i+1);

scanf("%d", &marks[i]);

// adding integers entered by the user to the sum variable


sum += marks[i];

// explicitly convert the sum to double

// then calculate average

average = (double) sum / n;

printf("Average = %.2lf", average);

return 0;

Run Code
Output

Enter number of elements: 5

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!

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can access the array elements from testArray[0] to testArray[9].

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:

Write a function to add the first and last elements of an array.

 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.

Two dimensional Array

Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];
Here, the array y can hold 24 elements.

Initializing a multidimensional array

Here is how you can initialize two-dimensional and three-dimensional arrays:

Initialization of a 2d array

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};


int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

Initialization of a 3d array

You can initialize a three-dimensional array in a similar way to a two-dimensional


array. Here's an example,

int test[2][3][4] = {

{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},

{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

Example 1: Two-dimensional array to store and print values

// C program to store temperature of two cities of a week and display it.

#include <stdio.h>

const int CITY = 2;

const int WEEK = 7;

int main()
{

int temperature[CITY][WEEK];

// Using nested loop to store values in a 2d array

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

for (int j = 0; j < WEEK; ++j)

printf("City %d, Day %d: ", i + 1, j + 1);

scanf("%d", &temperature[i][j]);
}
}

printf("\nDisplaying values: \n\n");

// Using nested loop to display vlues of a 2d array

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

for (int j = 0; j < WEEK; ++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

Example 2: Sum of two matrices

// C program to find the sum of two matrices of order 2*2

#include <stdio.h>

int main()
{

float a[2][2], b[2][2], result[2][2];

// Taking input using nested for loop

printf("Enter elements of 1st matrix\n");


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)

printf("Enter a%d%d: ", i + 1, j + 1);

scanf("%f", &a[i][j]);

// Taking input using nested for loop

printf("Enter elements of 2nd matrix\n");


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

for (int j = 0; j < 2; ++j)

printf("Enter b%d%d: ", i + 1, j + 1);

scanf("%f", &b[i][j]);

// adding corresponding elements of two arrays

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

for (int j = 0; j < 2; ++j)

result[i][j] = a[i][j] + b[i][j];

// Displaying the sum


printf("\nSum Of Matrix:");

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

for (int j = 0; j < 2; ++j)

{
printf("%.1f\t", result[i][j]);
if (j == 1)

printf("\n");

return 0;

Run Code
Output

Enter elements of 1st matrix

Enter a11: 2;

Enter a12: 0.5;

Enter a21: -1.1;

Enter a22: 2;

Enter elements of 2nd matrix

Enter b11: 0.2;

Enter b12: 0;

Enter b21: 0.23;

Enter b22: 23;

Sum Of Matrix:

2.2 0.5

-0.9 25.0

Example 3: Three-dimensional array

// C Program to store and print 12 values entered by the user

#include <stdio.h>

int main()
{
int test[2][3][2];

printf("Enter 12 values: \n");

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

for (int j = 0; j < 3; ++j)

{
for (int k = 0; k < 2; ++k)

scanf("%d", &test[i][j][k]);

// Printing values with the proper index.

printf("\nDisplaying values:\n");

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

for (int j = 0; j < 3; ++j)

for (int k = 0; k < 2; ++k)


{

printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);

}
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

Pass arrays to a function in C

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.

Pass Individual Array Elements

Passing array elements to a function is similar to passing variables to a function.

Example 1: Pass Individual Array Elements

#include <stdio.h>
void display(int age1, int age2) {

printf("%d\n", age1);

printf("%d\n", age2);

int main() {

int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()

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.

// pass second and third elements to display()

display(ageArray[1], ageArray[2]);

We can see this in the function definition, where the function parameters are
individual variables:

void display(int age1, int age2) {

// code
}

Example 2: Pass Arrays to Functions

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]);

int main() {

float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()

result = calculateSum(num);

printf("Result = %.2f", result);


return 0;

}
float calculateSum(float num[]) {

float sum = 0.0;

for (int i = 0; i < 6; ++i) {

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);

However, notice the use of [] in the function definition.

float calculateSum(float num[]) {

... ..
}

This informs the compiler that you are passing a one-dimensional array to the
function.

Pass Multidimensional Arrays to a 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>

void displayNumbers(int num[2][2]);

int main() {
int num[2][2];

printf("Enter 4 numbers:\n");

for (int i = 0; i < 2; ++i) {

for (int j = 0; j < 2; ++j) {

scanf("%d", &num[i][j]);

// pass multi-dimensional array to a function

displayNumbers(num);

return 0;

void displayNumbers(int num[2][2]) {

printf("Displaying:\n");

for (int i = 0; i < 2; ++i) {

for (int j = 0; j < 2; ++j) {

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

void displayNumbers(int num[2][2]);


This signifies that the function takes a two-dimensional array as an argument. We
can also pass arrays with more than 2 dimensions as a function argument.

When passing two-dimensional arrays, it is not mandatory to specify the number of


rows in the array. However, the number of columns should always be specified.

For example,
void displayNumbers(int num[][2]) {

// code

Recommended Reading: Call by Reference in C

You might also like