C
C
1. Basic of C Language
• Keywords
• Interpreter vs Compiler
• Operator
• Writing C code
• ASCII Code Example
• Control Statement
• if-statement
• loop-statement
• Pattern Loop Questions
• switch-statement
• break and continue
• Format Specifiers
2. Function in C
• Types of functions
• Function Features
• Writing Function Code
• Recursion
• Recursion Example
• Call by value and reference
• Scope
3. Arrays in C
• Implementing arrays
• Passing array to functions
• Writing Array code
• 2D
• Assigning Values to a 2D Array
• Writing 2D array code
4. Structure in C
• Declaration of Structure Variable
• Arrays of structure
• Passing structure to functions
• Nested structure
• Writing Structure Code
5. Strings
• Passing Strings to Functions
• Predefined string functions
• Writing string functions
6. File Handling
• Why do we need file handling?
• Types of files
• File Handling Functions
• Opening Modes
• Writing Code
1
7. Questions
Basic Of C Language
• C is a general-purpose programming language created by Dennis Ritchie
at the Bell Laboratories in the early 1970s.
• C is a structured programming language.
• Identifiers: Names that we define to refer to something, and it’s user-
defined.
• Keywords: Name that are defined by the programming language, cre-
ator.
• Tokens: Smallest unit of a programming language.
• It only has 32 keywords.
int main()
{
char *name = "something";
return 0;
}
main, name they are identifiers. return, int, char they are key-
words, 0, "something" they are litrals, integer and string.
Keywords
interpreter vs compiler
Interpreter Compiler
Translates program one statement at Scans the entire program and
a time. translates it as a whole into machine
code.
Interpreters usually take less amount Compilers usually take a large amount
of time to analyze the source code. of time to analyze the source code.
However, the overall execution time is However, the overall execution time is
comparatively slower than compilers. comparatively faster than interpreters.
Operators
2
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator. B%A=0
Writing C Code
variable declration (one way)
#include <stdio.h>
int main()
{
int number1;
int number2;
int number3;
}
variable declration (another way)
#include <stdio.h>
int main()
{
int number1, number2, number3;
}
operator use-case
#include <stdio.h>
int main(void)
{
int a = 10;
// add
a += 10; a = a + 10;
// sub
a -= 10; a = a - 10;
// mul
a *= 10; a = a * 10;
3
a /= 10; a = a / 10;
int main()
{
int a;
scanf("%d", &a);
printf("%d\n", a);
}
int main()
{
char a = 'A';
char b = 'a';
return 0;
}
Control Statement
• Types Of Statements:
– Expression Statements: it is combination of variables, Constants,
operators, Function Calls and followed by a semicolon.
– Compound Statements: Compound statement is combination of
several expression statements. Compound Statement is Enclosed
within the Braces { }.
4
– Selection Statements: Selection Statements are used in decisions
making situation
– Iterative Statements: These are also Called as Loops. If we want
to Execute a part of program many times we will use loops.
– Jump Statements: These are Unconditional statements Jump
statements are useful for Transfer the Control one part of program
to other part of Program there are few Jump Statements in C goto
Code to explain if, while, do-while, ‘for’, nested-if, switch.
if
#include <stdio.h>
int main()
{
int a = 10, b = 20, c = 30;
if ( a > b )
{
if ( a > c ) printf("a is the largest.");
else printf("c is the largest.");
}
else
{
if ( b > c ) printf("b is the largest.");
else printf("c is the largest.");
}
}
loop
#include <stdio.h>
int main()
{
int i = 0;
do {
printf("%d\n", i);
5
i--;
} while (i > 0);
}
int main()
{
int rows = 5;
int main()
{
int rows = 5;
6
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 2 * (rows - i) - 1; j++) {
printf(" ");
}
for (int k = 0; k <= i; k++) {
printf("* ");
}
printf("\n");
}
return 0;
}
int main()
{
int rows = 5;
7
#include <stdio.h>
int main()
{
int rows = 5;
switch
#include <stdio.h>
int main()
{
char a = 'r';
switch (a)
{
case 'a': printf("no the case"); break;
case 'b': printf("no the case"); break;
case 'r': printf("it is the case"); break;
defualt: printf("shit.");
}
}
Format Specifiers
8
Format Specifiers Type of Output
%e A floating-point number
%s A string or sequence of character
%lf double
%Lf Long double
%o Octal integer
%u Short unsigned integer
%ld Long decimal integer
%x Hexadecimal integer
%p Print memory address in the hex.
Function in C
• A function is a group of statements that together perform a specific task.
• Every C program has at least one function, which is main().
• A function declaration tells the compiler about a function’s name, return
type, and parameters.
• A function definition provides the actual body of the function.
• A function can also be referred as a method or a sub-routine or a procedure,
etc
Types of function
• Standard library functions
• User-defined function
User-defined functions
• You can also create functions as per your need.
• Such functions created by the user are known as user-defined functions.
Features of function
• Function declaration: A function must be declared globally in a c pro-
gram to tell the compiler about the function name, function parameters,
and return type.
• Function call: Function can be called from anywhere in the program.
The parameter list must not differ in function calling and function decla-
ration. We must pass the same number of functions as it is declared in
the function declaration.
9
• Function definition: It contains the actual statements which are to be
executed. It is the most important aspect to which the control comes
when the function is called. Here, we must notice that only one value can
be returned from the function.
Function declaration, with and without parameters.
int add();
int add(int, int);
int add(int a, int b);
Function call, with and without parameters.
add();
add(10, 20);
Function definition, with and without parameters.
int add(int a, int b)
{
return a+b;
}
Function basic
#include <stdio.h>
int main()
{
int result = add(10, 20); // function call
printf("%d\n", result);
return 0;
}
10
Armstrong number
#include <stdio.h>
#include <math.h>
int armstrong(int n)
{
int length = 0, lc = n;
while (lc != 0)
{
length++;
lc /= 10;
}
int res = 0, nc = n;
while (nc != 0)
{
int rem = nc % 10;
res = res + ((int)pow((double)rem, (double)length));
nc /= 10;
}
int main()
{
int n;
printf("Number: ");
scanf("%d", &n);
int res = armstrong(n);
if (res) printf("%d is armstrong.\n", n);
else printf("%d is not armstrong.\n", n);
}
11
total_mins = convert_time_in_mins(hrs, minutes);
printf("Total minutes = %d\n", total_mins);
return 0;
}
Recursion
• Recursion is the technique of making a function call itself.
• It also allocates memory via calling itself, into the stack.
Recursion Example
• Factorial
• Fibonacci
• Sum
Factorial
#include <stdio.h>
int fact(int n)
{
if (n <= 1) return 1;
return n * fact(n - 1);
}
int main(void)
{
int n;
printf("%d\n", fact(n));
return 0;
}
12
Fibonacci
#include <stdio.h>
int fib(int n)
{
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
int main(void)
{
int a = 6;
printf("%d\n", fib(a));
return 0;
}
Sum
#include <stdio.h>
int sum(int n)
{
if (n == 0) return 0;
return n + sum(n - 1);
}
int main()
{
int n;
printf("%d\n", sum(n));
return 0;
}
13
Call by Value
• In this parameter passing method, values of actual parameters are copied
to function’s formal parameters.
• Any changes made inside functions are not reflected in actual parameters
of the caller.
#include <stdio.h>
void increment_val(int n)
{
n++;
printf("increment_val(): %d\n", n);
}
int main()
{
int n = 10;
Call by reference
• Both the actual and formal parameters refer to the same locations
• Any changes made inside the function are actually reflected in actual pa-
rameters of the caller.
• * to initiate pointer, & to get address.
int a = 10;
int *ptr = &a;
a = 20; // a = 20
*a = 10; // err: cannot derefrence, because `a` is a variable not a pointer.
ptr = 233; // it'll change the address that ptr was locating to.
*ptr = 30; // a = 30;
#include <stdio.h>
int main()
14
{
int n = 10;
Scope
• A scope in any programming is a region of the program where a defined
variable can have its existence and beyond that variable it cannot be ac-
cessed.
• Local Variables:
• Variables that are declared inside a function or block are called local vari-
ables.
• They can be used only by statements that are inside that function or block
of code.
• Local variables are not known to functions outside their own.
• Global Variables:
• Global variables are defined outside a function, usually on top of the pro-
gram.
• Global variables hold their values throughout the lifetime of your program
and they can be accessed inside any of the functions defined for the pro-
gram.
int a = 10; // global
int main()
{
int b = a; // local
}
Arrays
• It is a collection of similar type of data which can be either of int, float,
double, char (String), etc.
• All the data types must be same.
• For example, we can’t have an array in which some of the data are integer
and some are float.
15
Implementing Arrays
• How to declare an array?
• Index of an array
• Printing element of an array
Index of an array
int array[5] = { 10, 20, 30, 40, 50 };
ELEMENTS 10 20 30 40 50
INDEX 0 1 2 3 4
int main()
{
int array[5] = { 10, 20, 30, 40, 50 };
for (int i = 0; i < 5; i++) printf("%d ", array[i]);
printf("\n");
}
void print(int size, int array[size]); // size is defined with the array.
void print(int array[]); // size is not defined, either it should be global o
16
void print(int *array, int size); // pointered array, same as string.
int main()
{
int array[] = { 10, 20, 30, 40, 50 };
print(5, array);
print(array);
print(array, 5);
}
Linear Search
#include <stdio.h>
int main()
{
int array[] = { 10, 20, 30, 40, 50 };
int target = 30;
return 0;
}
Bubble Sorting
#include <stdio.h>
int main()
{
int array[5] = { 4, 1, 3, 5, 2 };
17
for (int i = 0; i < 5; i++) printf("%d ", array[i]);
Reverse
#include <stdio.h>
int main()
{
int array[] = { 10, 20, 30, 40, 50 };
return 0;
}
int main()
{
int a[10];
18
printf("Enter 10 values: ");
for (int i = 0; i < 10; i++) scanf("%d", &a[i]);
return 0;
}
2-D
• 2D array are generally known as, Matrix.
-- --
| 10 20 30 |
| 40 50 60 |
| 43 23 54 |
-- --
int array[3][3] = {
{ 10, 20, 30 },
{ 40, 50, 60 },
{ 43, 23, 54 }
};
19
int array[3][3] = { 0 };
array[0][2] = 10;
array[2][1] = 20;
-- --
| 0 0 10 |
| 0 0 0 |
| 0 20 0 |
-- --
Array 2D Code
• 2D array implementation
• 2D array addition
• 2D array multiplication
2D array implementation
#include <stdio.h>
int main()
{
int m, n;
printf("M x N: ");
scanf("%d%d", &m, &n);
int array[m][n];
2D array addition
#include <stdio.h>
int main()
{
20
int m, n;
printf("M x N: ");
scanf("%d%d", &m, &n);
int mat1[m][n];
int mat2[m][n];
int mat3[m][n];
21
}
2D array multiplication
#include <stdio.h>
int main()
{
int m, n, p, q;
22
return 0;
}
Structure in c
• We use structures to store data of different types. For example, you are a
student.
• Your name is a string and your phone number and roll_no are integers.
• So, here name, address and phone number are those different types of
data.
struct structure_name
{
char *name;
int roll_no;
long int phone_no;
};
main()
{
struct student p1, p2, p3; // define variable
}
23
Arrays of structure
struct student
{
char name[30];
int phone_number;
};
main()
{
struct student variable[4]; // 4, structure.
struct student one = variable[0]; // we can access them as usual array elements.
}
Nested structure
struct students
{
struct names {
char *a;
char *b;
} name;
int roll_no;
};
struct info
{
char name[128];
int maths;
int physics;
int cs;
};
int main()
24
{
int n = 50;
struct info v[n];
Strings
• Strings in C language are an array of characters ended with null characters
('\0').
• The null character at the end of a string indicates its end and the strings
are always enclosed by double quotes.
• In C language characters are enclosed by single quotes.
char string[6] = { 'r','a','h','u','l','\0' };
char string[6] = "rahul";
char string[] = "rahul";
char *string = "rahul";
• There is a minor difference between the declarations of the strings in both
of the above statements.
• Like when we declare char as string[10], 10 bytes of memory space gets al-
located to hold the 10 values of string, while when we declare it like string[]
then memory gets allocated at the time of execution of the program.
25
Predefined string functions
• We can perform different kinds of string functions like joining of 2 strings,
comparing one string with another or finding the length of the string.
Function Use
strlen calculates the length of string
strcat Appends one string at the end of another
strcpy Copies a string into another
strcmp Compares two strings
int main()
{
char *a = "Hello, ";
char *b = "World!";
26
int b_size = strlen(b);
return 0;
}
int main()
{
char *string = "Hello, World... testing 1... 2... 3...";
printf("\n");
}
return 0;
}
27
File Handling
File handling refers to the method of storing data in the C program in the
form of an output or input that might have been generated while running a C
program in a data file, i.e., a binary file or a text file for future analysis and
reference in that very program.
Types of Files in a C
• Text file
• Binary file
Text file
• The text files are the most basic/simplest types of files that a user can
create in a C program.
• We create the text files using an extension .txt with the help of a simple
text editor.
• In general, we can use notepads for the creation of .txt files.
• These files store info internally in ASCII character format, but when we
open these files, the content/text opens in a human-readable form.
28
Text binary
• The binary files store info and data in the binary format of 0’s and 1’s
(the binary number system).
• Thus, the files occupy comparatively lesser space in the storage.
• In simpler words, the binary files store data and info the same way a
computer holds the info in its memory.
• Thus, it can be accessed very easily as compared to a text file.
Opening Modes
Mode
in
Pro-
gram Meaning of Mode When the file doesn’t exist
r Open a file for reading the In case the file doesn’t exist in the
content. location, then fopen() will return
NULL
rb Open a file for reading the content In case the file doesn’t exist in the
in binary mode. location, then fopen() will return
NULL.
w Open a file for writing the content. In case the file exists, its contents
are overwritten. In case the file
doesn’t exist in the location, then
it will create a new file.
wb Open a file for writing the content In case the file exists, then its
in binary mode. contents will get overwritten. In
case the file doesn’t exist in the
location, then it will create a new
file.
29
Mode
in
Pro-
gram Meaning of Mode When the file doesn’t exist
a Open a file for appending the In case the file doesn’t exist in the
content. Meaning, the data of the location, then it will create a new
program is added to the file’s end file.
in a program.
ab Open a file for appending the In case the file doesn’t exist in the
content in binary mode. Meaning, location, then it will create a new
the data of the program is added file.
to the file’s end in a program in a
binary mode.
r+ Open a file for both writing and In case the file doesn’t exist in the
reading the content. location, then fopen() will return
NULL.
rb+ Open a file for both writing and In case the file doesn’t exist in the
reading the content in binary location, then fopen() will return
mode. NULL.
w+ Open a file for both writing and In case the file exists, its contents
reading. are overwritten. In case the file
doesn’t exist in the location, then
it will create a new file
wb+ Open a file for both writing and In case the file exists, its contents
reading the content in binary are overwritten. In case the file
mode. doesn’t exist in the location, then
it will create a new file.
a+ Open a file for both appending In case the file doesn’t exist in the
and reading the content. location, then it will create a new
file.
ab+ Open a file for both appending In case the file doesn’t exist in the
and reading the content in binary location, then it will create a new
mode. file.
Writing Code
• Reading information from a text file
• Writing data to the text file in a program
Reading File
#include <stdio.h>
#include <stdlib.h>
int main()
30
{
FILE *file = fopen("a.txt", "r"); // read file, with `r` mode.
return 0;
}
Writing File
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *file = fopen("a.txt", "w"); // read file, with `r` mode.
return 0;
}
31
Questions
• What is the difference between Control Statement and Selection State-
ment?
• How to skip an iteration?
• Define break and continue with example?
• List out format specifier with definition.
• Types of functions, explain in breif with example.
• Write a program for armstrong number.
• What is Recursion, difference between Recursion and Loop?
• Write a program for Fibonacci.
• What is call by reference? and how it’s different from call by value?
• Define scope with example?
• Output of the code.
int num[] = { 5, 3, 4, 2 };
int a = num[4];
printf("%d\n", a);
• What is 2D array, write code for 2D array.
• What is structure in C, define nested structure.
• Write code for passing array to the function.
• List out string functions, with example.
• What does strcmp do?
• What is file handling?
• Why do we need file handling?
• Types of files?
• List out modes in file handling in C.
• Difference between fprintf() and printf().
• Write code to read file.
• Write code to write file.
• Functions in file handling.
32