You are on page 1of 155

C language Tutorial by Apna College

These are the chapters included in this video.

After installing the Code editor which is VScode, we should


download MinGW, which is the compiler for running C
Language in VSCode.

C:\MinGW\bin, search for mingw in the search bar and


copy this path. After that we’d go to control panel, the go
to system (see later part of video from 8:00)
To run C in VSCode, you need to install this extension:

To run a C code, you need to go in the terminal

After you open a new terminal, you need to type the


following command:
The line we’ve written above has compiled the code, after
this, we will run the file by the following command:

This is the code we’ve written to print hello world as a text


in our terminal:

Chapter 1: Variables, Data Types, Inputs/outputs


1. Variables:

Here, we have created some variables of different types:

There are some rules to write variables in C language:

First rule means that you have a


variable ‘a’ and another variable ‘A’.
Both will be considered different
because of case sensitivity.

Second rule states that the first


character of a variable name should
either be an alphabet or
underscore.

This is an example of writing variable names with


underscore:
Some incorrect variable names maybe -age or 1age.

Likewise, you cannot use a comma or even a space in a


variable name.

Moreover, you cannot use any other special


character in variable names except underscore.

Following are the variable data types in c:

A character data type occupies 1 byte of data. An


integer data type occupies 2 bytes of data while a float
occupies 4 bytes of data.

Also, you may notice that variable data types like boolean
or string do not exist in C language.
Here, we have used 3 data types:

They are int, float and char. Int is used to store whole
numbers. Floats are used to store decimals. Char is used
to store special characters.

After variables, there are 2. constants. The value of


constants does not change.

Caution: when you are defining character constants, you


need to use single quotation marks for defining their
value.
3. Keywords:

Keywords are special


characters that we use
while writing programs in
C. They are what makes
the C language functional.

These are the 32 keywords


that are used in C
Language.

4. Program Structure:

In the first line we write #include


<stdio.h>. This is called
preproccessor directive. You need
to write this line in your code,
otherwise your code won’t run.
Next, in the program structure is the main() function,
inside the main function we write what we want to execute
and in the end we write return 0. This tells that the code
runs smoothly and has zero errors.

There are three things that you would write all the
same in all programs and that is:
● #include<stdio.h>
● int main(){
● return 0

Between int main (){ and return 0 you would write your
code, and after each line you should put a semicolon. This
is considered as a full-stop in C-Language and it
terminates the statement. Also, you could’ve written
printf(“Hello World!”); and return 0; command in
same line followed by a semicolon at the end of each
statement.
5. Comments:

This is a single line comment, which means that you can


only write it in a single line. If you want to take your
comment to two or more than two lines then you might
want to use /* */. Here is an example of a multiline
comment:
Output:

To get output of some kind on the terminal we will use the


printf command:

This is how you get a single output:

But, if you want to print the same text let’s say 5 times
and each time you want it on a new line, you would use
the \n within your text like this:

#include <stdio.h>

int main() {

printf("Hello jee \n");


printf("Hello jee \n");
printf("Hello jee \n");
printf("Hello jee \n");
printf("Hello jee \n");
return 0;
}

There are some output cases that you need to take


care of when you are writing code

These are called


format specifiers

#include <stdio.h>

int main() {

int age = 21;


printf("Your age is: %d", age);

return 0;
}

By above code, you’ve specified the format of the variable


age you created, for specifying the format we have used
%d.

Similarly, for printing a float variable, you can do this:


Similarly, for printing a character:

6. Input:

The & operator stores the value of age to some


specific address.
See this program where we take input from user and
store it in some variable and then print it:

#include <stdio.h>

void main(){
int age;
printf("Enter your age and we will print it on the
screen: ");
scanf("%d" , &age);
printf("age is: %d ", age);
return 0;
}

The output of this code would be:


Notice the printf command in line 4. Right
below it, we will put the scanf command to
take the input

Now, after this we will take two numbers as input


and then we will print their sum:(When
reviewing this code, make sure to copy it
and paste it to a compiler or code editor
before you start reading it)

#include <stdio.h>

void main(){
int num1, num2;

printf("Enter first number: ");


scanf("%d", &num1);

printf("Enter second number: ");


scanf("%d", &num2);

printf("The sum of the two numbers you entered are: %d", num1 +
num2);
return 0;
}

The output of this code would be:


This is the process when the code runs, when we
run our C language file, the compiler checks that
file for any syntax errors and then it runs that file
as an exe(executable) for windows or as a
.out(output) file in mac or linux.

Practice Question 01: Printing the area of


square by taking the length of a side as
input.

#include <stdio.h>

void main(){
int side;
printf("Enter the length of a single side of
square to find its area: ");
scanf("%d", &side);

printf("The area of the square is: %d",


side*side);

return 0;
}

The output of the code will be:

Practice Question#02: Print the area of


circle by taking radius as input:

#include <stdio.h>

// Finding area of Square //

void main(){
float radius;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
printf("The area of the circle is: %f",
3.14*radius*radius);
return 0;
}
The output of the code above is:

Homework set for first chapter:

Part(a) code:

#include <stdio.h>

// Finding perimeter of rectangle //


void main(){

int sideA, sideB;


printf("To calculate the perimeter of recatangle, give lentgh of first
side: ");
scanf("%d", &sideA);

printf("To calculate the perimeter of recatangle, give lentgh of


second side : ");
scanf("%d", &sideB);

printf("The perimeter of rectange is: %d", sideA + sideB);

return 0;

Output:

Part B:

#include <stdio.h>

// Finding cube of a number //

void main(){
int number;
printf("Enter a number and gets its cube printed on screen: ");
scanf("%d", &number);

printf("The cube of the number you entered is: %d",


number*number*number);

Output of this code:

Chapter 2: Instructions and Operators


In this line:

We have assigned a value to variable d, and then


we declared another variable with that which is
e.

Also, make sure that you declare the variable


first and then use it!

Here, there is an error as we have used the years


variable before declaring it!
Similarly, we can first declare a number of
variables in a same line and then store their
value as 1. But if we try to store the value
without declaring the variable we would get
errors:

Note that there will only be a single variable on


left hand side:

Consider this line of code:


Here, the value of a*b is stored in y but not in
‘x’. X is only declared as a variable.

Important Note:

When printing a variable, make sure you


specify it’s format(i.e %d for integers, %f for
floating numbers, %c for characters).
Here, before printing a, we have specified
its format first with %d

Arithmetic instructions:

For power we need to use a function pow()


Also, we need to include a header file which is
#include <math.h>.

Now, we will print a number raised to a


power:

#include <stdio.h>
#include <math.h>

int main() {

int a,b;
a = b = 2;
int power = pow(a,b);
printf("%d", power);
return 0;
}

Output of this code will be:

Now, the next operator we will look at is the


modular operator:
The modular operator
returns the remainder of
the division.
#include <stdio.h>
#include <math.h>

//Using the modular Operator//


int main() {

int a;

a = 3%2;

printf("%d", a );
}

Above code will print 1, as the remainder of


division of 3 and 2 is 1.

!Note: Modular operator doesn’t work on


float entries.

The code wont run as the operands or


numbers we are performing the operation on is
invalid.

Also, if numerator is negative, then the


modulus is negative as well.
Next up, we have Artihmetic instructions
If we perform a mathematical function
between an integer and a float, the output
of this operation will be a float value.

Now, take this example if we are dividing 3 by


2 or 3/2.

The output of this code will be 1.

But, if one of the numbers here is float value.


We will get the answer in float value:
See this example, if we assign the above value to
an integer and print it:

We will get this error:


Now, note that there are two type of type
conversions in C language, one is implicit
conversion and other is explicit conversion.
Impicit conversion happens by itself, you do
not need to write any code for that, but for
explicit conversion, we need to write code by
ourselves. We get the implicit conversion error
here because an integer occupies the space of 2
bits, but a float occupies the space of 4 bits,
which is why a float can’t be converted to an
integer.
Now, if we want to convert 1.999999 to an
integer and remove it’s decimal. We will write the
following code:

Assignment Operators
The multiplicative, division and modular
operators are preferred first and then the
addition and subtraction operator.

If for example, you can get two operators of


same precedence, then you need to apply the
associativity rule
The associativity rule states that you need to go
from left to right.

After operators, you have instructions,


As we know that the C language code gets
executed from top to bottom, but there are
instructions that are called control instructions
that can control the flow of the program. For
example, it can execute a line that is below a
certain line before the line that is above it.

In decision control, we’ll study if-else, in loop


control, we’ll study for loop.

After this, we will study the operators


Firstly, with the relational operators:

Now, checking our first relational operator that is


==
Here, we wrote this in our printf statement, the
output will be 1

1 here signifies true, since 4 is indeed equal to


4.

Therefore, if we write it like this:

Since the above statement is false, therefore the


output we’d get will be 0

All other integers except zero are true and


zero is false
The above statement would return true, simply
because four is greater than three

If you write this in your code:

You will get false, as three is never greater than


three
Lastly, we have this relational operator that is
called Not equal to

By above code, we understand that since the


statement that four is not equal to four is
false, it will return zero(since 4 is equal to 4,
duh!!!)
Next up, we have logical operators

First of our logical operator is &&, in this case,


we check different statement thru this operator
and if both statements are true, then in the
output, you’d get true(1), but if only a single
statement is false, then output would be show
false(0) as well.
Let’s have a look at this example:

Since, one of the statements above is


false(4!=4 is false), we know that the output
shown will be false as well

Another example:
In logical OR, if any one statement is true, then
the output will be true as well!

The output of the above statement will be true

Third logical operator is Logical Not operator

It will inverse whatever the output will be:

The above statement is false, but if use Not


operator before it then it would return true in the
ouput, here is an example of this in the code:
Similarly, it can also inverse a true statement:

Here is the operator precedence which tells which


operator is preferred. NOT operator is
preferred first.
Here are the assignment operators.

If you want to write a = a + b code, you can


use a shorthand technique and instead use
something like a+=b.
See, third question. If we change the
statement a bit like this:
Here, we’re getting an error because we have
used the variable in the same line we have
declared that variable

That means that part(c) is not valid.

For part(d), it would give us a warning as


there are multiple characters used in the
char keyword.

It gives us this warning because it simply doesn’t


have enough space to hold the two characters
alltogether. Following is the homework set
for Chapter 2:
Chapter 3: Conditional Statments

The syntax of if-else statement will be:


The stuff that comes inside the curly braces in C
language is called a block, inside this ‘block’,
there are multiple statements.

Now, let’s say that if you have to check two


conditions at a time, for that we would use an
else if block:
Also, if you are checking multiple conditions at a
time, then the flow of the code would look like:

You would check all conditions with if and then


else if, and then at the end you can use an else
which would run when all the conditions are
falsified. If any condition inside an else-if
block gets true than the compiler would jump
out of the code and other conditions wont run.

But, if we want to check multiple conditions and


we want a certain number of conditions to be
checked for being true of false, then we would
use multiples if in our code like this:
The next ternary operator we are going to study
is ternary operator which can be used as an
alternative for an if-else. Following is the syntax
to use:
The number will be taken by the user, whichever
number will be inputed by the user will take the
switch to that specific case.

For example if user inputs 2, it will display


tuesday.

,
#include <stdio.h>

int main(){
int day;
printf("Enter a day(1-7): ");

scanf("%d", &day);

switch(day){
case 1: printf("The day is monday\n");
break;
case 2: printf("The day is tuesday\n");
break;
case 3: printf("The day is wednesday\n");
break;
case 4: printf("The day is thursday\n");
break;
case 5: printf("The day is friday\n");
break;
case 6: printf("The day is saturday\n");
break;
case 7: printf("The day is sunday\n");
break;
default: printf("There are 7 days in a week, enter a
valid day\n");
break;
}
We can also write the same switch-case program
by taking input a character from the user
Chapter 4: Loop Control instructions

In for loop, we have 3 steps, first is initialization, then


we have a specific condition by using an iterator on
which the loop will work on and then we update that
iterator(either increase it or decrease it).

After that it will implement whatever is inside the for


loop.

!note: Once the variable initialization is done, it


doesn’t reinitialize the variable.
We can use the for loop to perform repetitive task like
printing hello world 5 times:

Similarly, if we want to print numbers from 1-100, we


can perform the task like this:
We use post increment and pre- increment plus post
decrement and pre decrement operators in C langauge

Post increment and decrement look like this: i++ and


i–-

Pre increment and pre decrement will look like: ++i


and --i

Here, weve set the value of the counter used in for loop
as a floating value.The output will similarly be printed
in floating form:

We can also use the counter as a character, we can


print alphabets from capital A or small a to capital Z or
small Z, these alphabets have ASCII values
themselves:
The program to print characters from capital A to small
z will be:
We can also create an infinite loop in C language by
not giving the stopping condition in the for loop like
this:

This loop will run until it drains all the PC’s memory.

Next up, we are going at while loops

Also, we have to declare the counter outside the while


loop, then start the while loop for a specific condition
which does something very specific then we’ll add the
increment statement.
An example in code will look like:
The same code can be written in for loop:

After this, we’ll look at do while loop:

In do while loop, the function is performed first


and then condition is checked.
Now, if we want to write a code for printing numbers
from 1 to 5 using do while loop:

Things to note here:


- We need to initialize variables outside
do-while.
- We will increment it in the do block.
- We will use the condition in while block
int main() {

int n;
printf("Enter A number: "); // if you enter 3,
you will get 1 + 2 + 3 and vice v.
scanf("%d", &n);
int sum;

for(int i = 1; i<=n; i++){

sum = sum + i;

}
printf("The sum is %d", sum );

!)Special Case:

When printing an integer or any other specific


variable, if you put %d before the printed
statement you’ll get an output that wont make
sense, see this for example:
Therefore, putting %d before means that you’re
actually putting the variable there!

==================================

Now, we’ll try to print the numbers in reverse:


int main() {

int n;
printf("Enter A number: "); // if you enter 3, you will get 1
+ 2 + 3 and vice v.
scanf("%d", &n);
int sum;

for(int i = 1; i<=n; i++){

sum = sum + i;

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

printf("The numbers printed in reverse are:\n");

for(int i=n; i>=1; i--){


printf("%d \n", i);
}
return 0;

A user can say that an error might occur when we are


redeclaring and re-initializing i variable in the two
for loops, but the i variable is only limited to that for
loop block. After the for loop block gets executed, the
compiler forgets about the i variable.
Even If you’d use it outside the loop(without
declaring it), you would get the error that i is not
declared(because i was never declared outside the for
loop), here is an example of that error:

Here, the printf outside the for loop block will throw
you an error, as the variable i was only used inside the
for loop and after that loop block gets executed, the
compiler forgets about the i variable.

Here is the error statement:


We can do this task inside a single for loop, here’s how:

int main() {

int n;
printf("Enter A number: "); // if you enter 3, you will get 1
+ 2 + 3 and vice v.
scanf("%d", &n);
int sum;

for(int i=1, j=n; i<=n && j>=1; i++,j--){

sum = sum + i;
printf("%d\n", j);

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

An alternative code without using the i variable will be:


int main() {

int n;
printf("enter a number: ");
scanf("%d", &n);
int multiple;
for(int i = 1; i<=10; i++ ){
multiple = i*n;
printf("%d\n", multiple);
}

return 0;
}

Example output:(for Table)


Break Statment

The break statement always breaks the loop, and


the statement below the break statement(if inside the
loop) doesn’t gets implemented.

Output:
// Online C compiler to run C program online
#include <stdio.h>

int main() {
int n;
do{
printf("Enter an even number, if you enter an odd number,
loop will end: ");
scanf("%d", &n);
printf("%d\n", n);

if(n%2!=0){
break;
}

} while(1);
printf("The Loop has ended");

This do-while loop is an infinite loop as we have not


defined an ending point for it, in the while block, we
have stated (1), 1 means true, which means that the
condition will remain true and loop will never
break(loop breaks when condition becomes false).
Therefore, we add the break statement with the if
condition
int main() {
int n;
do{
printf("Enter a number ");
scanf("%d", &n);
printf("%d\n", n);

if(n%7==0) {
break;
}

} while(1);
printf("The Loop has ended");

One important thing to note here is that break


statement also enables you to break out of the
nested loop.

If for instance, you


have two for loops and then you write a break
statement, then it will break out of both the for loops.
Continue Statement

Continue statement is used when we need to skip some


lines of code and move to the next iteration, it is
mostly used in loops. Here is an example of continue
statement in code:

int main() {
for(int i=1; i<=5; i++){
if(i ==3){
continue;
}

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

Output:
Here in this code, we have skipped 3 in the loop
and have printed numbers from 1 to 5
int main() {
for(int i=1; i<=10; i++){
if(i ==6){
continue;
}

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

}
int main() {
for(int i=5; i<=50; i++){
if(i%2 == 0){
continue;
}

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

}
int main() {

int n;
printf("Enter a number: ");
scanf("%d", &n);

int fact = 1;

for(int i=1; i<=n; i++){


fact = fact*i;

}
printf("%d\n", fact);

Note: While using this program, you cannot input big


numbers to calculate factorial of, because the end
result simply would be huge and the data type int
wont be able to store that value in itself.
int main() {

int n;
printf("enter a number: ");
scanf("%d", &n);
int multiple;
for(int i = 10; i>=1; i-- ){
multiple = i*n;
printf("%d\n", multiple);
}

return 0;
}
int main() {

int sum;

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


sum = sum + i;

}
printf("%d\n", sum);
}
Question a code:

#include <stdio.h>

int main() {
int rows = 4; // You can adjust the number of rows as needed

// Outer loop for rows


for (int i = 0; i < rows; i++) {
// Inner loop for columns
for (int j = 0; j < 5; j++) {
printf("*");
}
// Move to the next line after printing a row
printf("\n");
}

return 0;
}

Question b code

// Online C compiler to run C program online


#include <stdio.h>

int main() {
int n, count;

printf("Enter a number to check it's prime or not: ");


scanf("%d", &n);

for(int i=1;i<=n;i++){
if(n%i==0){
count++;
}

}
if(count ==2)
printf("Number you entered is a prime number!");

else
printf("Number you entered is not a prime number");

return 0;
}
Misc Topic: How to write if-statment with bool:

// Online C compiler to run C program online


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

bool tempIsCold;

int temp;

printf("Is the temperature cold today? Enter 0 if it is not!: ");


scanf("%d", &temp);
tempIsCold = temp;

if(tempIsCold){
printf("woof it's cold");

else{
printf("It's not cold!");
}
}

Before using the bool variable, make sure that you


have added the #include <stdbool.h> header file.

Here, after we’ve created the boolean variable with


name tempIsCold, we then take an integer input from
the user and then we run an if statement on the basis
of the input entered by the user. If the user enters
0(which is considered as a falsy value in C
language), the compiler will treat it as false, and thus
it will run the else block, if the user enters 1 or any
other value other than 0(values except 0 are
considered true in C language), then it will run the if
block. Now notice the syntax if(tempIsCold). The
tempIsCold variable is added as an input into the if
block, if that value of tempIsCold returns true, it will
run(Code Blocks run on true value of variables).
Any other values will be false, so it will run the else
block in this case.

==================================

Chapter 5: Functions and recursions

In the first step, we declare the function.

To declare the function we write void thisFunction();


Now, we know that this function exists.
Here, we have now written printf(“hello”);
This function now prints “hello” whenever it is called.

After this we can call the function in our code like this:

printHello(); is a function that was called in this code.


We declare the function above int main().

Then we call the function inside int main().

And then we define that function’s task below int


main().

We can call the function multiple times and it will


perform the same task all over again.
#include <stdio.h>

void printHello();
void printGoodBye();

int main() {

printHello();
printGoodBye();

void printHello(){
printf("Hello!\n");
}

void printGoodBye(){
printf("Good Bye!\n");
}

You can obviously write the function task above int


main() like this:
#include <stdio.h>

void printHello(){
printf("Hello!\n");
}

void printGoodBye();

int main() {

printHello();
}
But the conventional way is to write the way we wrote
above.

==================================

#include <stdio.h>

void printNamaste(){
printf("Namaste!\n");
}

void printbonjour(){
printf("Bonjour!\n");

int main() {

char ch;
printf("Press F if you are French, Press I if you are an indian: ");
scanf("%c", &ch);

if(ch == 'F' || ch == 'f'){


printbonjour();
}
else if(ch == 'I' || ch == 'i'){
printNamaste();
}

else{
printf("invalid input! Enter a valid character.");
}
}
First point: It doesn’t matter what function you declare
first above or below main, the compiler goes
straight to the main function to declare all
functions.

Second point: A function can be called indirectly if you


call that function inside another function and this
function gets called in the code, take this example:

Here, the function


bonjour(); was
defined in the
namaste() function,
when we call
namaste(),
bonjour() gets called
as well.
Printf() and scanf() are library defined functions and
they use a preproccesor directive which is #include
<stdio.h>, if we wont use this then our code will not
run.
The first function takes
no parameter and also
return nothing(because
it has void in its start)

The second function


takes an integer n as a
parameter but returns
nothing as a value.
The third function takes
two values as parameter
and returns an integer
value(has int in its
start)

Now, we will make a function that will take two values


and it will return us the sum of those two values.

#include <stdio.h>

int sum(int a, int b){


return(a+b);
}

int main() {
int a,b;
printf("Enter First Number: ");
scanf("%d", &a);

printf("Enter second Number: ");


scanf("%d", &b);

int s = sum(a,b);
printf("sum is %d", s);

}
We can name the variable n differently even in both
functions, but when we name a certain variable inside a
function, the scope of that variable is confined to that
function itself and not outside of it. If you’ve named a
variable n inside main() function, you cannot use it
outside that function directly!
To print a Table of a number thru a function, we will
take the input from the user:

#include <stdio.h>

void printTable(int n);

int main() {

int n;
printf("Enter a number: ");
scanf("%d", &n);

printTable(n);
}

void printTable(int n){


for(int i =1; i<=10; i++){
printf("%d\n", i*n);
}
}

In this code, when we call the


function inside the main
function, we only write our n
variable, this is called the
argument. And the int n we
have written below main() is
the parameter
Here, the code of line that is
marked with red represent a
function call. Here, we write
our argument
First, we need to include our library in the top of the
program:
The pow function was
explained above.

If you use %d an int values, you would get an


error that the argument takes ‘double’. In this
case, you would enter float values because %f can also
be used for double.

#include <stdio.h>
#include <math.h>

int main() {
float n;

printf("Enter a number: ");


scanf("%f", &n);

printf("%f", pow(n,2));
}
// Online C compiler to run C program online
#include <stdio.h>
#include <math.h>

int circleArea(int radius); //Defining function


int squareArea(int sqLength); //Defining function

int main() {

int radius;
printf("Enter the radius of circle to calculate its area: ");
scanf("%d", &radius);

int sqLength;
printf("Enter the length of square to calculate its area: ");
scanf("%d", &sqLength);

int c = circleArea(radius); //Storing value in a var to print later


int sq = squareArea(sqLength);

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

return 0;
}

int circleArea(int radius){

radius = radius * radius * 3.142; // Area Of circle

int squareArea(int sqLength){

sqLength = sqLength * sqLength; // Area of Square

}
An alternative code can be:

Here, we have used


the return keyword to
return the values and
then we used printf to
print the values for
the function.
Complete Code:
// Online C compiler to run C program online
#include <stdio.h>
#include <math.h>

int circleArea(int radius); //Defining function


int squareArea(int sqLength); //Defining function
int rectArea(int a, int b);

int main() {

int radius;
printf("Enter the radius of circle to calculate its area: ");
scanf("%d", &radius);

int sqLength;
printf("Enter the length of square to calculate its area: ");
scanf("%d", &sqLength);

int c = circleArea(radius); //Storing value in a var to print later


int sq = squareArea(sqLength);

int a;
printf("Enter length of first side of rectangle: ");
scanf("%d", &a);

int b;
printf("Enter length of second side of rectangle: ");
scanf("%d", &b);

printf("The area of circle is: %d\n", c);


printf("The area of square is: %d\n", sq);
printf("The area of rectangle is: %d", rectArea(a,b));

return 0;
}

int circleArea(int radius){

radius = radius * radius * 3.142; // Area Of circle

int squareArea(int sqLength){

sqLength = sqLength * sqLength; // Area of Square

}
int rectArea(int a, int b){
return a*b; // Here we have done the task differently.
}

================================

Recursion

Note here that this task can also be done thru


loops but we’ll use recursion here. Also note that
there are tasks in programming that can be done by
both recursion and loops, therefore we might need to
consider which one we will use to perform the task!
#include <stdio.h>

void printHW(int count);

int main() {

printHW(5); // This would print hello world 5 times

return 0;
}

void printHW(int count){

if (count ==0){ /*When count = 0, the function would return to main code */
return;
}
printf("Hello World!\n");
printHW(count-1); //Since its already printed once, we add count - 1 here.

Now, visualise why count -1


was used. Now, when count =
5 was called in the main
function, the function kept
printing hello world and took
the value of count from the
main function and kept
subtracting 1 from it and kept
printing hello world.
Now, there are 2 types of calls:

1 is the main
function call:

In this type of
call, some
function calls
another function
and that function calls another function for example
and returns some value to the second function, the
second function then returns the value to the main
function. This is how normal functions work.

Second type of
call is a
recursive
function call, in
this case, a single
functions calls itself and finally returns a value to the
main function as we saw above. This whole process is
called recursion.
Here, what we can do
is first find some till
(n-1) numbers, then
later we can add n to
it. Let’s say if n = 3,
we’ll first find sum for
numbers that go till
n-1, in this case n - 1 or 3-1 = 2, that means sum till 2
numbers before 3, we’ll add that first and then add that
part to 3.

Here, 1 is the
base value in
which we will return some specific value given by us, in
this case that value will be 1 as sum of 1 is 1 ofc
Code:

#include <stdio.h>

int sum(int n);

int main() {

int n;
printf("Enter a number you want sum till: ");
scanf("%d", &n);

printf("The sum is %d", sum(n)); // Takes argument for the function from user

return 0;
}

int sum(int n){

if(n ==1){ //This is the base value


return 1;
}

int sumNm1 = sum(n-1); //Gets the sum till n-1 and stores in sumNm1
int sumN = sumNm1 + n;
return sumN;
}

Output:
sum(1) is called the base Case, where the whole
work is done, here n = 1, it then returns the value to n
=2 or sum(2).
Code:

#include <stdio.h>

int factorial(int n);

int main() {

int n;
printf("Enter a number: ");
scanf("%d", &n);

printf("The Factorial is %d", factorial(n)); //Passes the argument thru user

int factorial(int n){

if(n ==0){
return 1;
}

int FactNm1 = factorial(n-1); //Factorial till (n-1)


int Fact = FactNm1 * n; // Factorial till (n-1) multiplied to n.
}

Base case is very important is


recursion because it stops recursion
at a certain point
Let’s take an example of what will happen if we
remove base case from our program.

Here, the line of


case which
contained the
base case was
removed which
was became the
reason thru
which this
program ran
infinite times
until a
segmentation
fault appeared
in the program.
#include <stdio.h>

int TempConv(int temp);

int main() {

int temp;
printf("Enter Temperature in Celsius: ");
scanf("%d", &temp);

printf("The temperature is Fahrenheit is %d", TempConv(temp));

int TempConv(int temp){


temp = (temp * 9/5) + 32;
return(temp);
}
Above highlighted is our formula for recursion.
Code:
// Online C compiler to run C program online
#include <stdio.h>

int fib(int n);

int main() {
// Write C code here
int n;
printf("Enter a fibonucci term to print fibonacci value for that term number: ");

scanf("%d", &n);

printf("%d", fib(n)); /* returns the sum of all values till n, if you enter 7, it
will give the sum till 7 terms */
}

int fib(int n){

if(n == 0 || n ==1 ){
if(n==0){
return 0;
}
if(n==1){
return 1;
}
}

int fibNm1 = fib(n-1); // fibonacci till n-1


int fibNm2 = fib(n-2); // fibonacci till n-2

int fibN = fibNm1 + fibNm2;

return fibN;

}
Addtional problem: Write a code to print fibonacci
sequence thru for loops:

#include <stdio.h>

int main() {
int n, first = 0, second = 1, next;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

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


if (i <= 1) {
next = i;
} else {
next = first + second; // first(0) + second(1) = next(1)
first = second; // first(1)
second = next; // second(1), then 1 + 1 = 2(next) and so on...
}

printf("%d ", next);


}

return 0;
}
Additional Problem: Print these sequences below:

Seq1 code: (Almost same logic used as in fibonacci)


#include <stdio.h>

int main() {
int n, first = 0, second = 3, next;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Series:\n ");

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

next = first + second; // first(0) + second(3) = next(3)


first = next; //first(3)
//first(3) + second(3) = next(6)
//first(6) and so on...

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


}

return 0;
}
Seq2 code:
#include <stdio.h>

int main() {
int n, first = 7, second = 5, next;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Series:\n ");

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

next = first + second; // first(7) + second(5) = next(12)


first = next; //first(12)
//first(12) + second(5) = next(17)
//first(17) and so on...

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


}

return 0;
}
Seq3 Code:
#include <stdio.h>

int main() {
int n, first = 70, second = 5, next;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Series:\n ");

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

next = first - second; // first(70) - second(5) = next(65)


first = next; //first(65)
//first(65) - second(5) = next(60)
//first(60) and so on...
if(next ==0){
printf("The series has ended!");
break;
}

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


}

return 0;
}
Question(a) Code:(sum of digits)
#include <stdio.h>

int sumOfDigits(int number) {


int sum = 0;

// Take the absolute value to handle negative numbers


if (number < 0) {
number = -number;
}

while (number > 0) {


// Add the last digit to the sum
sum = sum + (number % 10); //example: 123 % 10 = 3 and then add 3 to sum

// Remove the last digit from the number


number = number/ 10; // 123 /10 = 12

return sum;
}

int main() {
int num;

// Input a number from the user


printf("Enter a number: ");
scanf("%d", &num);

// Call the function to find the sum of digits


int result = sumOfDigits(num);

// Display the result


printf("Sum of digits: %d\n", result);

return 0;
}
Question(b) Code:(square root):

#include <stdio.h>
#include <math.h>

int main() {
double number;

// Input a number from the user


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

// Check if the entered number is non-negative


if (number < 0) {
printf("Cannot calculate the square root of a negative number.\n");
} else {
// Calculate and print the square root
double squareRoot = sqrt(number);
printf("Square root of %.2lf is %.2lf\n", number, squareRoot);
}

return 0;
}
Question(c) (Temperature Question)

// Online C compiler to run C program online


#include <stdio.h>

int temp(int inp);

int main() {

int inp;

temp(inp);

int temp(int inp){

printf("Enter temperature: ");


scanf("%d", &inp);

if (inp >= 25){


printf("temperature is hot!");
} else if(inp< 25 ) {
printf("Its Cold Outside!");
}

}
Question(d) (Power of a number)
// Online C compiler to run C program online
#include <stdio.h>

int power(int n);

int main() {

int n;
printf("Enter a number: ");
scanf("%d", &n);

printf("%d", power(n));

int power(int n){


int result = n*n;
return result;
}
Chapter 6: Pointers

Here the ptr variable is a pointer which holds the


memory address of age. A pointer variable consists
of an asterisk(*).

According to this syntax, in the


second line we have stored the
address of age into the pointer
ptr. Therefore, the address of age
which is 2010 has been stored in
ptr.

(*) is called value


at address, this
enables to get the
value of the
variable while &
gets the address of
that.
At the end, we have stored the
value of that pointer in _age. This
will print(if we print it) the original
value(22) since it contained the *(asterisk) or the
value at address operator.

Let’s try this in code and see what output we get:

Notice that _age had the value of the pointer(_age =


*ptr), therefore, we got 22 at the output.

Trying something different here, if we print pointer


ptr.

Notice that the


output is a random hexadecimal number and the
format specifier used is %p, which we normally use
for pointers.

We can also use %u which represent unsigned int, so


that we get a relatively simpler value at output when
we print the pointer

Notice now that we have a simpler value.

==================================

We can declare
pointers as
integers, floats and
characters. It
depends on what
type of address
you have stored in
that specific
variable. If you
have used an
integer let’s say int age(like we used above), you
need to create an int pointer.

!Look at the third line,


here we have printed the
address of the pointer

You may notice that the output for:


printf("%p\n", &age);
printf("%p\n", ptr);

Are the same, and that is because they are the same
thing, &age and ptr are same, but if you add &ptr, it
would mean that you are trying to call the address of
that specific pointer, in that case you will have a
different output.
Since we have used the *ptr operator, the value of x
which is essentially *ptr has been
declared to zero

This has also been verified thru


code.
Now to verify the rest of the code. When we write
*ptr + =5. We have added 5 to the value of x, and
then (*ptr)++ we have added 1 to *ptr which in itself
was the original value of x, so when we’ll print x in the
end. We’ll have x = 6.

Note one thing that *ptr contains


For solving this we just need to use
the value at address operator twice.

This is how it can be done in code:

This is the timeline.


Here is an example of
calling function by value.

We can also call function by reference:

We will use *n
to write the
integer. And
then when
passing the
argument we
can use &n.
Here, int* as
parameter
means that we
need to pass a pointer argument.

For doing this we can use


another variable and empty the value of b in that
variable and then empty value of a in b, and then a will
get empty, then we’ll put the value of the new variable
in a and we’ll be able to swap the values right away.

We can perform this thru


functions and then call the function by value and then
by reference.
Code:(call by value)

!note: Since we have only changed a and b in the


function definition, the value of x and y will not change
but the values of a and b will change.

This means that the values were not


swapped, so we will use the call by reference function
and we will use pointers to actually change the values.

Here, the values have been swapped as we used


pointers.
!note: we use call by reference when we need
‘more than one values’ from the function, then
we use pointers.
Since it’s a call
by value function, this function would make a copy of
another variable n which will have a different
address. When we’ll print, the output of addresses
wont match simply because there were two variables
that were created and both will have different
addresses.
Running this in code:

// Online C compiler to run C program online


#include <stdio.h>

void printAddress(int n);

int main() {
int n =4;
printf("The address in the main function is: %u", &n);
printf("\n");
printAddress(n);

return 0;
}

void printAddress(int n){


printf("The address of n in call by value function is %u", &n);
}
Now, if we form a call by reference function and use
pointers.

// Online C compiler to run C program online


#include <stdio.h>

void printAddress(int *n);

int main() {
int n =4;
printf("The address in the main function is: %u", &n);
printf("\n");
printAddress(&n);

return 0;
}

void printAddress(int *n){


printf("The address of n in call by value function is %u", n);
}
~note: Here we need to return more than one
values(we need to return three values), therefore
we’ll make use of pointers.
Reference video:
Call By Value & Call By Reference in C

When we created the variables x and y inside the


function and changed their values, it won’t reflect on
the x and y we created in the main function and
that is because the variables created in the function are
local to that function and they will get destroyed
once you come out of that function, therefore the
values of variables we get at the output are the ones
we created in the main function.

We
can directly use pointers so that we can access the
value of the variables that are present.
Explanation of this concept:

When we use the call


by value, we send
copies of variables
to the function, when
we use call by
reference, we give
the addresses of
variables and then we
can manipulate those
variables through
pointers.
Chapter 7: Arrays

This is how you create an array

When we write int marks[3], there are three memory


locations created, each one is recognized as an int and
it holds 4 bytes

First block is 0, the second is 1 and so on!


To input an array, we first take the data we need to put
in the zeroth index, then the first index and so on.

Let’s suppose we have an array which contains 3


elements, in code it will show up like:

Now, we have created a 3-element array, now, we need


to take input for each element.
// Online C compiler to run C program online
#include <stdio.h>

int main() {
int marks[03];

printf("Enter Physics Marks: ");


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

printf("Enter chemistry Marks: ");


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

printf("Enter math Marks: ");


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

printf("Physics marks are %d, Chemistry Marks are %d, Math marks are %d", marks[0],
marks[1], marks[2]);

return 0;
}
Notice if you try to take inputs for extra elements(i.e
elements more than the array length), you will get
errors:

Program will abort, this is a runtime error, compiler


won't be able to tell u this error, but the program will
tell u this in runtime(when you run your code)
// Online C compiler to run C program online
#include <stdio.h>

int main() {
float equipPrice[3] = { 9.25, 6.25 , 7.50};

float gst = 2.40;

float finalPriceBat = equipPrice[0] + gst;


float finalPriceglove = equipPrice[1] + gst;
float finalPricepad = equipPrice[2] + gst;

printf("The price of bat with added GST is %f\n", finalPriceBat );


printf("The price of gloves with added GST is %f\n", finalPriceglove );
printf("The price of pads with added GST is %f\n", finalPricepad );

return 0;
}
Pointer arithmetic

Here, if we increase the value of pointer, it will increase


the data type, for example if the pointer is of type int,
it will then change to float/double if we increment
it.
The pointer will now hold a different sort of address.

Similarly, decrementing it will bring it to it’s older


address
Now here an array named arr is actually a pointer, and
it points to array’s 0th index.
This is how we can travel thru an array, this ptr pointer
will point to the zeroth index of the array, and then we
can increment that pointer, so that we can move thru
the index of the array and access the values on that
indexes.
This is how we can move thru an array, store their
values and also manipulate them if we like.

We can also perform this task with the help of pointers.


Here, n represents the size of the array, there are two
ways you can code the argument line. One is by writing
array with the square brackets, and then defining it’s
size thru n

And other is to use pointers. You can then call the


function by giving the relevant arguments.
\t is used to give a tab space.
This is how the above array
can be accessed.
Note: the array size of each array will remain the
same.

Mini Project: Storing marks of 2 students of 3


subjects:

This is how we can make a 2D array and then input


values on all indexes.
This is the code without using a function.
In the second part we’ll get an error:
We can perform array reversal by exchanging values,
like exchanging the 1st value with the last, 2nd with
the 2nd last and vice versa – this is a classical method
of rearranging the array.

Firstly, we can perform this the lengthy way like this by


swapping algorithm we used before (see page#127)
Logic for building a program:

7:04:25

You might also like