C Programming Basics Notes For Beginners
C Programming Basics Notes For Beginners
C Programming Basics
What is C Language ?
C is a general purpose programming language and it was developed
by Dennis Ritchie in 1972. These Programs are simply set of
instructions given by a programmer to the computer in high level
language. The program execution process consists of two steps ,
first it uses a compiler to translate/convert the high level program
into machine code then execute the instruction set.
Write Features of C?
C has wide features −
Easy to learn its fundamental concepts and as a beginner level entity
in programming.
It follows structured programming approach scheme.
It produces efficient programs that accomplish a given task.
It can handle low-level activities.
It can be compiled on a variety of computer platforms.
Write Overview/History of C?
C was invented to write an operating system called UNIX.
C is a successor of interpreted B language which was introduced
around the early 1972, in At&T Bell Laboratories which was then
standardized by the American National Standards Institute.
The UNIX OS was totally written in C.
Today C is the most widely used and popular System Programming
Language.
What is Algorithm?
As in all programming or real world entity to express with we need a
algorithm which means a series of simple written English statements,
i.e steps to move forward for task. for example a screenshot of it.
What is Flowchart? Explain flowchart and its various components?
A flowchart is a formalized graphic representation that represents
an algorithm, workflow or process, showing the steps as boxes of
various kinds, and their order by connecting them with arrows. This
diagrammatic representation shows a solution model to a given
problem.
What is Variable?
A variable is nothing but a name given to a storage area that our
programs can manipulate. Each variable in C has a specific type,
which determines the size and layout of the variable’s memory; the
range of values that can be stored within that memory; and the set
of operations that can be applied to the variable.
Rules for naming a variable!
The name of a variable can be composed of letters, digits, and the
underscore character.
It must start with either a letter or an underscore.
It should not start with special character or a digit.
C language is case-sensitive.
What is Datatype ? Types of datatype?
Data types in c refer to an extensive system used for declaring
variables or functions of different types. The type of a variable
determines how much space it occupies in storage and how the bit
pattern stored is interpreted.
The types in C can be classified as follows −
Type Description
1 if statement
An if statement consists of a boolean expression followed by
one or more statements.
if…else statement
An if statement can be followed by an optional else
statement, which executes when the Boolean expression is
2 false.
nested if statements
You can use one if or else if statement inside
3 another if or else ifstatement(s).
switch statement
A switch statement allows a variable to be tested for equality
4 against a list of values.
What is Loop?
A loop statement allows us to execute a statement or group of
statements multiple times. Given below is the general form of a loop
statement in most of the programming languages –
C programming language provides the following types of loops to
handle looping requirements.
1 while loop
Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing the
loop body.
for loop
Executes a sequence of statements multiple times and
2 abbreviates the code that manages the loop variable.
do…while loop
It is more like a while statement, except that it tests the
3 condition at the end of the loop body.
nested loops
You can use one or more loops inside any other while, for, or
4 do..while loop.
break statement
Terminates the loop or switch statement and transfers
execution to the statement immediately following the loop or
1 switch.
2 continue statement
Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
goto statement
3 Transfers control to the labeled statement.
What is an Array?
An array is a collection of similar data items, i.e all of the same
datatype, accessed using a common name. A one-
dimensional array is like a list; A two dimensional array is like a table
would be considered as row and columns.
Syntax:
One-dimensional array is declared as follows:
type array-name[size] = { list of values };
example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int arr[]={2,3,4}; //Compile time array initialization
for(i=0 ; i<3 ; i++)
{
printf(“%dt”,arr[i]);
}
getch();
}
Output :2 3 4
Two-dimensional array is declared as follows,
type array-name[row-size][column-size]
Example : int a[3][4];
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[3][4];
int i,j,k;
printf(“Enter array element”);
for(i=0;i<3;i++)
{
for(j=0; j < 4; j++)
{
scanf(“%d”,&arr[i][j]);
}
}
for(i=0; i < 3; i++)
{
for(j=0; j < 4; j++)
{
printf(“%d”,arr[i][j]);
}}
getch();
}
What is Structures?
Structure is a user-defined data type in C which allows you to use
dissimilar datatypes such as combination of (int,float,char) to store a
particular type of record or segment. Structure helps to construct a
complex datatype.
The only difference is that array is used to store collection of similar
datatypes while structure can store collection of any
type(dissimilar) of data.
struct keyword is used to define a structure. struct define a new data
type which is a collection of different type of data.
Syntax :
struct structure_name
{
//Statements
};
Example of Structure
struct TextBook
{
char names[15];
int price;
int pages;
};
1) Declaring Structure variables separately
struct Student
{
char[20] name;
int age;
int seatno;
};
struct Student St1 , St2; //declaring variables of Student
2) Declaring Structure Variables with Structure definition
struct Student
{
char[20] name;
int age;
int seatno;
} St1, St2;
Accessing Structure Members
Structure members can be accessed and assign the values in number
of ways. In order to assign a value to a structure member, the
member name must be linked with the structure variable
using dot[.]operator also called period or member
access operator.
struct TextBook
{
char names[15];
int price;
int pages;
} b1 , b2 ;
b1.price=200; //b1 is variable of TextBook type and price is
member of TextBook
Program :
#include<stdio.h>
#include<conio.h>
struct employer
{
char ename[10];
int revenue;
};
struct employer emp[5];
int i,j;
void inquire()
{
for(i=0;i<3;i++)
{
printf(“nEnter %d employer recordn”,i+1);
printf(“nEmployer namet”);
scanf(“%s”,emp[i].ename);
printf(“nEnter employer revenuet”);
scanf(“%d”,&emp[i].revenue);
}
printf(“nDisplaying Employer recordn”);
for(i=0;i<3;i++)
{
printf(“nEmployer name is %s”,emp[i].ename);
printf(“nRevenue is %d”,emp[i].revenue);
}}
void main()
{
clrscr();
inquire();
getch();
}
Nested Structures
Nesting of structures, are also implemented in C language.
Example :
struct student
{
char[30] name;
int age;
struct address
{
char[50] area;
char[50] city;
int pincode;
};
};
What does static variable mean ?
Static variable is accessible in C, throughout the life time of the
program. At the time of the program execution, static variables
allocations takes place first. In a scenario where one variable is to be
used by all the functions (which is accessed by main () function), then
the variable need to be declared as static in a C program.
What is the difference between calloc() and malloc() ?
A block of memory may be allocated using the function
malloc malloc(). The malloc function reserves a block of memory of
specified size and returns a pointer of type void(). This means we can
assign the base address of the block to any type of pointer
Syntax – P = (cast type*)malloc(byte size);
Calloc() is also a memory allocation function which is generally used
to allocate memory for array and structure. malloc() is used to
allocate a single block of storage space, calloc() allocates multiple
blocks of storage, each of same size and initializes them with zero.
Syntax – P = (cast type*)calloc(n,array size)
What is Call by Value?
The call by value method of passing arguments to a function copies
the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the
function have no effect on the argument.
By default, C programming uses call by value to pass arguments. In
general, it means the code within a function cannot alter the
arguments used to call the function. Consider the
function swap() definition as follows.
/* function definition to swap the values */
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
What is Call by reference?
The call by reference method of passing arguments to a function
copies the address of an argument into the formal parameter. Inside
the function, the address is used to access the actual argument used
in the call. It means the changes made to the parameter affect the
passed argument.
To pass a value by reference, argument pointers are passed to the
functions just like any other value. So accordingly you need to
declare the function parameters as pointer types as in the following
function swap(), which exchanges the values of the two integer
variables pointed to, by their arguments.
/* function definition to swap the values */
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
What are Pointers?
A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location. Like any variable or
constant, you must declare a pointer before using it to store any
variable address. The general form of a pointer variable declaration
is
type *var-name;
Steps how to use Pointers
(a) We define a pointer variable,
(b) assign the address of a variable to a pointer and
(c) finally access the value at the address available in the pointer
variable. This is done by using unary operator * that returns the
value of the variable located at the address specified by its operand.
What is Recursion?
Recursion is the process of repeating items in a self-similar way. In
programming languages, if a program allows you to call a function
inside the same function, then it is called a recursive call of the
function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to
call itself.
Recursive functions are very useful to solve many mathematical
problems, such as calculating the factorial of a number, generating
Fibonacci series, etc.
Example for recursion
#include <stdio.h>
int factorial(unsigned int i)
{
if(i <= 1)
{ return 1;
}
return i * factorial(i – 1);
}
int main() {
int i = 15;
printf(“Factorial of %d is %dn”, i, factorial(i));
return 0;}
Explain class/datatype String ? Explain its String Handling
Functions?
Strings are actually one-dimensional array of characters terminated
by a nullcharacter ”. Thus a null-terminated string contains the
characters that comprise the string followed by a null.
strcpy(s1, s2);
1 Copies string s2 into string s1.
strcat(s1, s2);
2 Concatenates string s2 onto the end of string s1.
strlen(s1);
3 Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater
4 than 0 if s1>s2.
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string
5 s1.
strstr(s1, s2);
6 Returns a pointer to the first occurrence of string s2 in string s1
Example
#include <stdio.h>
#include <string.h>
int main () {
char str1[12] = “Hello”;
char str2[12] = “World”;
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf(“strcpy( str3, str1) : %sn”, str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf(“strcat( str1, str2): %sn”, str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf(“strlen(str1) : %dn”, len );
return 0;
}
Explain Storage class?
A storage class defines the scope (visibility) and life-time of variables
and/or functions within a C Program. They precede the type that
they modify. We have four different storage classes in a C program –
auto
static
extern
auto Storage Class
The auto storage class is the default storage class for all local
variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage
class. ‘auto’ can only be used within functions, i.e., local variables.
static Storage Class
The static storage class instructs the compiler to keep a local variable
in existence during the life-time of the program instead of creating
and destroying it each time it comes into and goes out of scope.
Therefore, making local variables static allows them to maintain their
values between function calls.
In C programming, when static is used on a class data member, it
causes only one copy of that member to be shared by all the objects
of its class.
extern Storage Class
The extern storage class is used to give a reference of a global
variable that is visible to ALL the program files. When you use
‘extern’, the variable cannot be initialized however, it points the
variable name at a storage location that has been previously defined.
The extern modifier is most commonly used when there are two or
more files sharing the same global variables or functions
Explain Operators? And its Types?
An operator is a symbol that tells the compiler to perform specific
mathematical or logical functions. C language is rich in built-in
operators and provides the following types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Miscellaneous Operators
Arithmetic Operators
The following table shows all the arithmetic operators
supported by the C language. Assume variable A holds
10 and variable B holds 20 then
Operator Description Example
A+B=
+ Adds two operands. 30
A*B=
* Multiplies both operands. 200
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit
operation. The truth tables for &, |, and ^ is as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
(~A ) = -61,
Binary Ones Complement i.e,. 1100
Operator is unary and 0011 in 2’s
has the effect of ‘flipping’ complement
~ bits. form.
Assignment Operators
C=A+
B will
assign
the
Simple assignment operator. value of
Assigns values from right side A + B to
= operands to left side operand C
Misc Operators ↦ sizeof & ternary
Besides the operators discussed above, there are a few
other important operators including sizeof and ?
: supported by the C Language.
sizeof(a),
where a is
integer, will
sizeof() Returns the size of a variable. return 4.
&a; returns
& Returns the address of a variable. the actual
address of
the variable.
If Condition is
true ? then
value X :
otherwise
?: Conditional Expression. value Y
Explain Functions?
A function is a group of statements that together
perform a task. Every C program has at least one
function, which is main(), and all the most trivial
programs can define additional functions.
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.
Defining a Function
The general form of a function definition in C
programming language is as follows −
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of
a function header and a function body. Here are all the
parts of a function −
• Return Type − A function may return a value.
The return_type is the data type of the value the
function returns. Some functions perform the desired
operations without returning a value. In this case, the
return_type is the keyword void.
• Function Name − This is the actual name of the
function. The function name and the parameter list
together constitute the function signature.
• Parameters − A parameter is like a placeholder.
When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter
or argument. The parameter list refers to the type, order,
and number of the parameters of a function.
Parameters are optional; that is, a function may contain
no parameters.
• Function Body − The function body contains a
collection of statements that define what the function
does.
Example
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Explain Function Arguments?
If a function is to use arguments, it must declare
variables that accept the values of the arguments.
These variables are called the formal parameters of the
function.
Formal parameters behave like other local variables
inside the function and are created upon entry into the
function and destroyed upon exit.
While calling a function, there are two ways in which
arguments can be passed to a function −
S.N. Call Type & Description
Call by value
This method copies the actual value of an
argument into the formal parameter of the
function. In this case, changes made to the
parameter inside the function have no effect on
1 the argument.
Call by reference
This method copies the address of an argument
into the formal parameter. Inside the function, the
address is used to access the actual argument
used in the call. This means that changes made
2 to the parameter affect the argument.