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
Char
Typically a single octet(one byte). This is an integer type.
Int
The most natural size of integer for the machine.
Float
A single-precision floating point value.
Double
A double-precision floating point value.
Void
Represents the absence of type.
What is token in C? Types of Tokens?
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. C statement consists of five tokens –
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.
Comments
Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below −
/* my first program in C */
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language
Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names.
Auto
Else
long
Break
Enum
void
Case
extern
return
Char
Float
short
Switch
For
signed
Continue
Goto
sizeof

Difference between while and do-while loop? Explain?

1.    In While loop the condition is tested first and then the statements are executed if the condition turns out to be true. whereas, In do-while the statements are executed firstly i.e first time and then the conditions are tested, if the condition turns out to be true then the statements are executed again.
2.    A do-while is used for a block of code that must be executed at least once i.e, do-while loop runs at least once even though the condition given is false whereas, while loop do not run in case the condition given is false.
3.    In a while loop the condition is first tested and if it returns true then it goes in the loop
In a do-while loop the condition is tested at the last.
4.    While loop is entry control loop, where as do-while is exit control loop.
6.    Syntax: while loop  :
while (condition)
{
Statements;
}
7.    Syntax: do while loop  :
Do
{
Statements;
}while(condition);
Explain Decision Making ?
Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Types of Decision Making Statements
C programming language provides the following types of decision making statements.
S.N.
Statement & Description
1
if statement
An if statement consists of a boolean expression followed by one or more statements.
2
if…else statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
3
nested if statements
You can use one if or else if statement inside another if or else ifstatement(s).
4
switch statement
A switch statement allows a variable to be tested for equality against a list of values.
5
nested switch statements
You can use one switch statement inside another switchstatement(s).
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.
S.N.
Loop Type & Description
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.
2
for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
3
do…while loop
It is more like a while statement, except that it tests the condition at the end of the loop body.
4
nested loops
You can use one or more loops inside any other while, for, or do..while loop.
Explain Loop Control Statements?
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
S.N.
Control Statement & Description
1
break statement
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
2
continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
3
goto statement
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.
1
strcpy(s1, s2);
Copies string s2 into string s1.
2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3
strlen(s1);
Returns the length of string s1.
4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6
strstr(s1, s2);
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
+
Adds two operands.
A + B = 30
−
Subtracts second operand from the first.
A − B = -10
*
Multiplies both operands.
A * B = 200
/
Divides numerator by de-numerator.
B / A = 2
%
Modulus Operator and remainder of after an integer division.
B % A = 0
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable B holds 20 then
Operator
Description
Example
==
Checks if the values of two operands are equal or not. If yes, then the condition becomes true.
(A == B) is not true.
!=
Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true.
(A <= B) is true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then −
Operator
Description
Example
&&
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
(A && B) is false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.
!(A && B) is true.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −
p
q
p & q
p | q
p ^ q
0
0
0
0
0
0
1
0
1
1
1
1
1
1
0
1
0
0
1
1
Operator
Description
Example
&
Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) = 12, i.e., 0000 1100
|
Binary OR Operator copies a bit if it exists in either operand.
(A | B) = 61, i.e., 0011 1101
^
Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) = 49, i.e., 0011 0001
~
Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.
(~A ) = -61, i.e,. 1100 0011 in 2’s complement form.
<<
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
A << 2 = 240 i.e., 1111 0000
>>
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
A >> 2 = 15 i.e., 0000 1111
Assignment Operators
The following table lists the assignment operators supported by the C language
Operator
Description
Example
=
Simple assignment operator. Assigns values from right side operands to left side operand
C = A + B will assign the value of A + B to 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.
Operator
Description
Example
sizeof()
Returns the size of a variable.
sizeof(a), where a is integer, will return 4.
&
Returns the address of a variable.
&a; returns the actual address of the variable.
*
Pointer to a variable.
*a;
? :
Conditional Expression.
If Condition is true ? then value X : otherwise 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
1
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 the argument.
2
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 to the parameter affect the argument.

6 thoughts on “C Programming Basics Notes for Beginners”

  1. Pingback: Important programming languages for computer science student

  2. Pingback: which book should i refer for fybsc computer science

  3. Pingback: Basic C language programs for beginners for an interview with answers

  4. Pingback: PHP basics for beginners | Techniyojan

Leave a Comment

Your email address will not be published. Required fields are marked *