C Programming

Complete C language

What is Programming.....?

  • Computer programming is a medium for us to communicate with computers. Just like we use some  regional  languages to communicate with each other . same with the use of programming we deliver our instruction to the computers.

What is C....?

  • C is a programming language.

  • C is the one of the oldest and finest programming language.

  • C language Was developed by Dennis Ritchie at AT & T's bell labs, USA in 1972.

 Uses of C

  • C language is use to program wide variety of system some of the uses of  are as follows.
    • Major part of windows ,Linux and other operating system are written in C.
    • C is used to write driver programs for devices like Tablet, printers etc.
    • C language is used to program embedded systems where programs need to run faster in limited memory (Microwave, cameras etc.)

Variables

  • A variable is a container which stores a 'value' .
  • In kitchen, we have containers storing Rice, Dal, Sugar etc.
  • Variable is an Entity whose value can be change.
  • similarly variable in C store value of a Constant Example:
                                         a = 3;          // a is assigned "3"
                                         b = 4.7;      // b is assigned "4.7"
                                         c = 'A';       // c is assigned "A"

Rules for naming variable in C

  1. First character must e an alphabet or underscore(_)

  2. No comma, blank space are allowed

  3. No special Symbol other than (_) allowed.

  4. Variable names are cause sensitive

  • We must create meaningful variable names in our programs. This enhance readability of our programs.

Constant

An Entity whose value doesn't change is called as constant.

Examples : - 1, 2,3,4,A and lot more are the examples of constant. As this is defined in our definition pretty well.

  Types of constants

   Primarily, there are three types of constants:
  1. Integer Constant       šŸ‘‰  -1 , 5 ,10 ,23(It don't contain any fractional  parts )
  2. Real Constant           šŸ‘‰  -45.4, 6.7 , 7.0 (It my or may not contain fractional parts )
  3. Character constant    šŸ‘‰ 'a' , '$' , 'g' (Must be enclosed in an single inverted comma)

Keywords

these are reserved words whose meaning is already known to the compiler. There are 32 keywords available in C. The practice of making the name of variable out of these 32 reserve keywords is Prohibited. 

C Keywords | Top 24 Keywords of C with Syntax and Examples

Our First C program

link :- Click here to get the practice note .

Basic Structure of a C Program

All C programs have to follow a basic structure. A C program Starts with a main Function and executes instruction present inside it.
Each instruction is Terminated with the semicolon (;)
There are some rules which are applicable to all the c Programs :
  1. Every program's execution starts from main() Function.
  2. All the Statement are terminated with a semicolon. 
  3. Instructions are case- sensitive
  4. Instructions are executed in the same order in which they are written

Comments 

Comments are used to clarify something about the program in plain language. It is a way for us to add notes to our program. There are Two types of comments in C.
  1. Single line comments : // this is a comments
  2. Multi-line Comments : /* This is a multi line comments */
Comments in a C program are not executed and are ignored.

Compilation and Execution

Awesome Coding: Stages of compilation and execution of c program
A compiler is a computer program which converts a C program into machine language so that it can be easily understood by the computer.

A C program is written in plan text. This plain text is combination of instruction in a particular sequence. The compiler performs some basic checks and finally converts the program into an executable.

Library Functions

C language has a lot of Valuable library function which is used to carry out certain tasks. for instance printf  function is used to print values on the screen.

 printf(" This is %d", i);
  • %d for integers
  • %f for real values
  • %c for characters

link :-

Receiving input from the user

In order to take input from the user and assign it to a variable, we use scanf  function

Syntax for using scanf:

  •  scanf ("%d",&i)

& is the "address of" operator and it means that the supplied value should be copied to the address which is indicated by variable i.

Link:- 

Practice set :-

  • write a c program to calculate area of rectangle :
    • using hard codded inputs
    • Using input supplied by the user
  • calculate the area of the circle and modify the same program to calculate the volume of the cylinder gives its volume and height.

Link :- click here to get the solution of above problem.

  • Write a program to covert a celsius (centigrade degrees temperature to  Fahrenheit )

Link :- click here to get the solution of the above problem.

  • write a program to calculate simple interest for a set of values representing principal , number of years and rate of interest.

Link :- click here to get the solution of the above problem.

Instruction and operators

A c program is a set of instructions. just like a recipe Which contain instructions to prepare  a particular dish

Types of instructions

  1. Type declaration instruction
  2. Arithmetic Instruction
  3. Control instruction

Type declaration Instruction :

1.Type declaration instruction

  • int a ;
  • float b;
  • Other variations :
    • int i = 10; int j = i ; int a = 2
    • int ji = a +j -i
    • float b = a+3; float a = 1.1 => (here we got the error as we are trying to use it before defining it .)
  • int a,b,c,d;  
    • a = b = c = d = 30 ; => (The value of a,b,c&d will be 30 each )

 2. Arithmetic instructions

  • int i = (3 * 2) + 1
    • operands  can be int/float etc.
    • +,-,*,/ are arithmetic operators
  • int b = 2 , c = 3;
  • int z = b*c; (Legal)
  • int z; b*c = z;(in legal not allowed )
  • % => Modular division operator
    • Return the reminder
    • cannot be applied on the float
    • sign is same as of numerator (-5%2 = -1 )
      • 5% 2 = 1
      • -5% 2 = -1

Note : -

  1. No operator is assumed to be present
    •  int i = ab =>Invalid
    • int i = a*b =>valid 
     2. There is no operator to perform exponentiation in C
     3. To find the exponent in c we use  this function pow(4,5) we get the power of 4 in terms of 5

Type Conversion : - 

An Arithmetic operation between
  • int and int       => int
  • int and float    = > float
  • float and float => float
  • important
    • 5/2 => 2             5.0/2 = 2.5
    • 2/5 => 0             2.0/5 = 0.4

Note :-

  • int a = 3.5; In this cause 3.5(float) will be demoted to 3(int) because a is not able to store floats.
  • float a = 8 ; a will store 8.0 8=> 8.0 (promotion to the float)

Operator Precedence in C :-

 3*x - 8y is (3x)-(8y) or 3(x-8y)..?

In C language simple mathematical rules like BODMAS , No longer applies.

The answer for the above Question is provided by operator precedence & associativity.

Operator precedence :-

The following table list the Operator priority in C.

    Operators with its Precedence and Associativity - Progr@mming in C ...

Operators of higher priority are evaluated first.

Operator Associativity:-

When Operators of Equal priority are present in an in an expression, the tie is take care of by associativity . 
  • x * y / z => (x*y)/z
  • x / y * z   => (x/y)*z
  • *,/ follow left to right associativity.

Link :- Click here to get the link of above practice code.

Control Instructions:

Determines the flow of control in a program four types of control instruction in c are.
  1. Sequence control Instruction
  2. Decision Control instruction
  3. Loop control instruction
  4. Cause Control Instruction
More expanded detail of this topic is added in next chapters of this blog.

Practice set:-

  • Which of the following are invalid in C..?
    1. int a; b = a;
    2. int v = 3^3;
    3. char dt = '21 Dec 2020'
  • What data type will 3.0/8 -2 Return ....?
    • Answer :- double /float(because most of the compiler consider double to every decimal number it's consider as double until the data type are not defined )
  • Write the program to check whether a number is divisible by 97 or not .  

Link :- Click here to get the practice code of above problem.

  • Explain step by step evaluation of 3*x/y-z+k
    • Where x = 2 , y = 3 , z = 3 , k = 1

Link :- click here to get the above practice code of above problem.

  • 3.0 + 1 will be :
    • Integer
    • Floating point number šŸ‘ˆ(Answer)
    • Character

Conditional Instruction:

sometimes we want to watch comedy video on YouTube if the day is Sunday.
Sometime we order the the junk food if it is our friend birthday in the hostel.
You might want to buy the Umbrella if it's raining and you have the money.
you order the meal if your favorite dish is listed in the menu.

All these are decision Which depend on a condition being met.
In C language too, we must be able to execute instruction 0n a condition (s) being met.

Decision Making instruction in c :

  • if else Statement
  • The syntax of an if-else Statement in C look like
    • if (Condition to be checked){
    • statements -if condition is true ;
    • }
    • else {
    • statement if the condition is true ;
    • }
  • else is optional not mandatory if the condition of if is false than it run

Relational operators in C

Relation operators are used to evaluate conditions(True of false ) inside the if statement
some example of relational operator are
C Tutorial (11) : if-else & Relational operators – Anukul Verma

Note :- '=' is used for the assignment operator where '==' is used for the equality check

The condition can be any valid expression. In c a non zero value is consider as true .

Logical operators:- 

Operators and Expressions – Part VI (Logical Operator) | My ...

Usage of logical Operator :-

  • && --> AND --> is true when both the conditions are true 
    • "1" and "0" is Evaluated as false.
    • "0" and ''1" is Evaluated as false.
    • "1" and "1" is Evaluated as True
  • || --> OR --> is true when at least one of the condition is true
    • "1" and "0" is Evaluated as True.
    • "0" and ''0" is Evaluated as false.
    • "1" and "1" is Evaluated as True
  • ! --> return true if given false and false if given True.
    • ! (3==3) --> Evaluates to false
    • !(3 > 30) --> Evaluate to true. 
  • As the number of condition increases the level of indentation increases This reduces the readability logical operators to rescue in such cases

Else if Clause

Instead of using multiple if statement we can also use else if along with if thus forming an if-else-if-else ladder.
using if-else if-else reduces indents
the last else is optional also there can be any number of "if-else"

last else is executed on if all the condition is fail.

Conditional operator:

A short hand "if-else" can be written using the conditional operator or ternary operators
  • Syntax
    • condition ? expression -if-true : expression if-false

Switch cause Control Instruction

switch cause is used when we have to make a choice between number of alternatives for a guven Variable.

Syntax

   Switch (integer-expression)

   {

  case c1:

      code;

  case c2:

     code;

  case c3:

     code;


Link:- Click here to get above practice code.

The value of integer-expression  is matched against c1,c2,c3...... if it matches any of these cases, that case along with all subsequent "case" and "default" statements are executed.

Quick Quiz :-
Write a program to find grade of a student given his marks based on below:
  1. 90-100 --> A
  2. 80-70   --> B
  3. 70-80   --> C
  4. 60-70   --> D
  5. <60      --> F

Important Note :-

  1.  We can use switch- case statements even by writing cases in any order of our choice (not necessarily ascending)
  2. char values are allowed as they can be easily evaluated to an integer.
  3. A switch an occur with in another but in practice this is rarely done 

Practice set :-

  • What will be the output of this program
           int a = 10;
           if (a = 11)
              print("I am 11");
           else
             print(" I am not 11");
  •    Output :- I am 11 (because 1= is a assignment operator )
  • Write a program to find at whether a student is pass or fail; if it required total 40% and at least 33% in each subject to pass. Assume 3 subject take marks input from the user .
  • Calculate income tax paid by an employee to the government as per the slabs mentioned below
    • income slab             Tax
    • 2.5L - 50L                  5%
    • 5.0L - 10.0L               20%
    • above 10.0L              30%
  • Note :- there is no tax below 2.5l Take income amount as an input from, the user

Link :-  click here to get the solution of above practice problem.

  • Write a program to find whether a year entered is a leap year or not. take year as an input from the user .

Link:- Click here to get the solution of above practice problem.

  • write a program to determine the character entered by the user is lower cause or not.

Link :-click here to get the solution of the above problem.

  • Write a program to find greatest of 4 number entered by the user.

Loop Control Instruction :-

Why loops

Sometimes we want our programs to executed few set of instruction over and over again for ex.
printing 1 to 100 , first 100 even number etc.

Hence loops make it easy for a programmer to tell computer that a  given set of instruction must be executed repeatedly.

Types of Loops:-

Primarily, there are three types of loops in C Language :
1. While loop
2. do-while loop
3. for loop

we will look into these one to one

While loop

      while(Condition is true){
            //  Code                                              
           //   Code                                    (The block keep executing as long as the condition is true)
               }

Example:- Click here to get the example.

Note:- If the condition never become false, the while loop keeps getting executed. Such a loop is known as an infinite loop.

Quick Quiz :- Write a program to print natural number from 10 to 20 When initial loop counter i is initialized to 0. 


The loop Counter need not be int, it can be float as well.

Increment and Decrement operators.

  • i++ => i is in increment operator
  • i--  => i is decrement operator
  • +++  operator does not exist
  •  += is the compound assignment operator
  • just like -=,+= . /= & %=

do-while loop.

The Syntax of do while loop looks like this.


do {
// code;
// code;
}while (Condition);

do-while loop works very similar to while loop
While- Check the condition & then execute the code
do-While - Execute the code and than check the condition


       do-While loop = While loop which execute at least once.

Quick Quiz. :- Write a program to print first n natural numbers using do-while loop.

Input :- 4
output:- 1
              2 
              3
              4

For Loops

The Syntax of For loop look like This.

for(initialize; test ; increment or decrement)
       {
//code;
//code;
//code;
}

initialize :- Setting a loop Counter to an initial value.
Test :- Checking a condition.
Increment :- Updating the loop counter


Quick Quiz:- Write a program to print first n natural number using for loop.

Quick Quiz:- Write a program to print n natural number in reverse order.

The Break Statement in C language.

The break statement is used to exit the loop irrespective whether the condition is true or false.
Whenever "break" is encountered inside the loop the control statement is sent outside the loop.

The Continue Statement in C.

The continue statement in used to immediately move to the next iteration of the loop.
the Control is taken to the next iteration thus skipping everything below "Continue" inside the loop for that iteration.

Note:-

  1. Sometimes, the name of the variable might not indicate the Behaviour of the program.
  2. Break Statement Completely Exits the loop.
  3. Continue Statement skips the particular statements of the loop.

Practice set:-

1. Write a program to print multiplication table of a given number n.

2. Write a program to print a multiplication table of 10 in reverse order.

3.A do-While loop is executed
  1. at least once.
  2. at least twice.
  3. at most once.
Answer:- At least once.

4.What can be done using one type of loop can also be done using other type of loops
True or False ?

Answer :- True

5. Write a program to sum first ten natural number using while loop.


6. Write a program to calculate the factorial of the for loop.


7. Repeat the last program using the while loop.


8. Write a program top check whether the given number is prime or not using loops.

Project 1 : number guessing game

problem :-

We will Wrote  a program that generate the random number Ask the player to guess it. If the player,s guess is higher than  the actual number, the program display "Lower number please". Similarly if the user guess is higher than the program print "higher number please" .

when the player guesses the correct number, the program display the number of guesses the player use to arrive at the number .

Link :- Click here to get the link of the solution of this game.

 Function And Recursion:-

sometimes our program gets bigger in size and its not possible for a programmer to track which piece of code is doing what ..?
Function is a way to break our code into chunks so that it is possible for a programmer to reuse them.

What is function ....?
A function is a block of code which perform a particular task.
A function can be reused by the programmer in a given program in any number of time.

Example and syntax of a function

Void display(){   => Function prototype
           int main(){
          int a;
          display(); => Function call
          return 0;
            }
           }

Function prototype :- 

Function prototype is a way to tell the compiler about the function we are going to define in the program.
Here void indicate the function return nothing

Function call:-
Function call is a way to tell the compiler to execute the function body at the time the call is made.
Note that the program executed starts from the main function in the sequence the instruction  are written.

Function definition :-
This part contains the exact set of instructions Which are executed during the function call. When a function is called from main(), the main function falls asleep and gets temporarily Suspended. During the time the control goes to the function being called. when the function body is done executing main() resumes.

Important points :- 

  • Execution of a C program start from main()
  • A C program can have more than one function.
  • Every Function gets called directly or indirectly from main()
  • There are two types of function in c. lets talk about them.

Types of function

  1. Library Functions:- Commonly required functions grouped together in a library file on  disk.
  2. User Defined Functions :-These are the function declared and defined by the user.

Why use Function.....?

  1. To avoid recreating the same logic again and again.
  2. To keep track what we are doing in the program.
  3. To test and check logic independence

Passing values to Function. 

We can pass value to a function and get value return From the Function.
     
         int sum(int a, int b)
The above prototype mean that sum is a function which take value a (of type int) and b(of type int)
and return a value of type int.


Note:-
1. parameters are the values or variable place holder in the function definition. Ex a&b.
2. Arguments are the actual value passed to the function to make a call Ex:- 2&3.
3. A function can return only one value at a time. 
4. If the passed variable is changed inside the function , the function call doesn't changed the value in the calling function.

Quick Quiz:-
use the library function to calculate he area of a square with side a .


Recursion :-

A function defined in c can call itself This is called recursion.
A function calling itself is also called 'recursive' Function.
 
Example of recursion :-
A very good example of recursion is factorial.
    
    Factorial(n) = 1*2*3.......* n
    Factorial(n) = 1*2*3.....n-1* n
    Factorial(n) = factorial(n-1).....* n

Since we can write factorial of a number in terms of itself, we program it using recursion.

Important notes:-

  • Recursion is sometimes the most direct way to code an algorithm
  • The condition which doesn't call the function any Further in a recursive function is called as the base function
  • Sometimes, due to a mistake made by the programmer,  recursive function in a memory error.

Practice set:-

1. write a program using functions to find average of three numbers.


2.  Write a program to convert celsius to fahrenheit.


3. Write a function to calculate force of mass exerted on the body of mass m exerted by earth.


4. Write a program using recursion to calculate nth element of fibonacci series.


5.What will the following lie produce in a C program : 
          a = 3;
      printf("%d%d%d\n", a, ++a,a++);

Answer:-  Output :- Compiler take the arguments from left to write
( 5,5,3) is answer

6. Write the recursive function to calculate the sum of first n natural number.


7. Write a program using function to print the following pattern( first n line )
 
*
***
*****

Pointers

A pointer is a variable which store the address of another variable.


Memory block partition | Download Scientific Diagram
In our computer memory the data are stored in the form of block which contain 0 &  1 . because as we all know our computer work on the binary. and every block have a particular address through which we can access the data stored in the block in cause off pointers we stored the address of the block in a variable.

C Pointers Fundamentals Explained with Examples – Part I
As you can see in the image address of particular variable are stored in the another variable. so we can say that it's a pointer and pointing towards the variable in which the real data is stored.

The "Address of" (&) operator
& = used for obtaining the address of the particular variable. As we already saw it using with scanf.

Format specifier for printing pointer address is '%u'

The value of address operator (*)
The value of address or * operator is used to obtain the value present at a given memory address it is denoted by *

How to declare a pointer. ...?

A pointer is declared using the following Syntax

int*j; => declare a variable j of type int pointer
j = &i; => Store address of i in j.

Just like pointer of type integer , we also have pointer to char, float etc.

                 int * ch_ptr; => Pointer to a integer
                 char * ch_ptr; => Pointer to character
                 float*ch_ptr;  => Pointer to float

Although its a good practice to use meaningful variable names, we should be very careful while reading & working on a program from fellow programmers.

A Program to demonstrate pointer.

This program sums it all. If you understand it , you have got the idea of pointers.

Pointer to a pointer

As u saw in  above program just like j is pointing to  i or storing the address of i, we can have another variable K which can further store the address of j. What will be the type of k.


     int **k;
     k = &j;

We can even go Further one level and Create a variable l of type int*** to store the address of k. We mostly use int* and int** sometimes in real world programming.

Types of function call's :-

Based on the way we pass argument to the function, function call are of two types.
  • Call by value  => Sending the value of argument.
  • call by reference.  => Sending the address of argument.
Call by Value.
Here the value of the argument are passed to the function. Consider the Example.
     

If sum is defined as sum(int a,  int b), the value 3 and 4 are copied to a and b, nothing happen to the variable x and y.
if we change a and b , nothing happen to the variable of x and y.
This is call by value.

In c we usually make a call by value.

Call by reference. 

Here the address of the variable is passed to the Function as arguments.
Now since the addresses are passed to the function, the function can now modify the value of a variable
in calling function using * and &Example :-
The logic used in the above program.

Swapping two numbers using temporary variable and using arithmetic's

This function is capable of swapping the values passed to it . if a = 3 and b= 4 before a cal to swap(a,b),
a=4 and b=3 after calling swap.

Practice set:-

1. Write a program to print the address of a variable. Use this address to get the value of the variable.

2. Write a program having a variable i. print the address of i. pass this variable to a function and print its address . Arc this address same ..? why ...?

3. Write a program to change the value of a variable to ten times of its current value. Write a function and pass the value by reference.

4. Write the program using a function which calculate the sum and average of two numbers. use pointers and print the value of sum and average in main. 
 
5. Write a program to print the value of a variable i by using "pointer to pointer " type of variable. 

6. Try problem 3 using call by value and verify that it doesn't change the value of the said variable. 

 Arrays:- 

An array is a collection of similar elements. 

       one variable => Capable of storing multiple similar value. 

Syntax:- 

 The syntax of declaring an array look like this. 

  int marks[90]:  => integer array  which have capacity of storing 90 int data.

  int name[20]: => Character array or string. which have a capacity of storing 20 char data.

 int percentile[90]: => Float array which have a capacity of storing  90 float data.

 The  value can now be assigned to marks array like this. 

 
Note :- it's very important to note that he array index start with zero. 

 Accessing elements:- 

Elements of an array can be accessed using. 

    Link:- Click here to get the program of implementation of an array.

Quick quiz :- 

Write a program to accept marks of five students in an array and print them to the screen. 

Link :- Click here to get the solution of above quiz.

Initialization of an Array :-  

There are many others ways in which in which an array can be initialized.

 Link:- Click here to see the more way of initialization of array.

Array in memory. 

Consider this array 

int arr[3] = {1, 2 ,3 }  => 1 integer = 4 bytes 

This will reserve 4*3 = 12 bytes in memory 4 bytes for each integer. 

 array always store in continuous form in the memory. 

Pointer Arithmetic. 

A pointer can be incremented to point to the next memory location of that data type. 

Link:- Click here to get the example and implementation of pointer arthmatic.

 Following operation can be performed on a pointer. 
  • Addition of a number to a pointer. 
  • subtraction of a number from a pointer 
  • subtraction of one pointer from another 
  • comparison of two pointer variable. 
Quick Quiz :-  Try this operations on another variable by creating pointers in a separate program. 
 Demonstrate all the four operations.
 

Accessing Arrays using pointers.

Link:-  Click here to get implementation of initialization of array using the pointer.

 If ptr points to index 0 , ptr++ will points to index 1 & so on. 

passing arrays to functions:- 

Arrays can be passed to function like this 

Link:- Click here to get the implementation of passing the arrays to functions.

Multidimensional Arrays.

An array can be of  2 dimension/3 dimension / n dimensions. 

A 2 dimensional array can be defined as :

int arr[3][2] = { { 1, 4}

                            {7, 9}

                            {11, 22}};

We can access the elements of this array as arr[0][0], arr[0][1] & So on....!

Link:-  Click here to get the link of the implementation of 2d array.

Quick quiz. :- Create a 2-d array by taking input from the user. Write a display function to print the content of 2d array on the screen. 

Link:-

Practice set:- 

1. Create an array of 10 number. verify using pointer arithmetic that (ptr +2) points to the third element where ptr is the pointer pointing to the first element of array. 

Link :- Click here to get the solution of above practice problem.

2. If S[3] is a 1-D array  of integers then *(s+3) refers to the third elements. 

  1. True 
  2. False 
  3. Depends.
Answer:- False :- (Because it will point to the 4th element of the array . in c we start counting from zero.) 
 
 3. Write an program to create an array of 10 integer and store multiple table of 5 in it .
 

4. Repeat problem 3 for a general input provided by the user using  scanf . 

Link:- Click here to get the solution of above practice problem.

5. Write a program containing a function which reverse the array passed to it. 

Link:-  Click here ti get the solution of above practice problem.

6.  write a program containing Functions Which counts the number of positive integer in the array?

Link:- Click here to get the solution of the above practice problem.

7. Create an array of size 3*10  containing multiplication table of the number 2,7 and 9 respectively. 

Link:-  Click here to get the link of the above practice problem.

8. Repeat problem 7 for a custom input given by the user. 

link:-  Click here to get the link of the above practice problem.

 9. Create a three-Dimensional array and print the address of it's elements in increasing order.

 Link:- Click here to get the link of above practice problem.

 String:-

 A string is a 1-D Character array terminated by a null ('\0')

           ('\0') = null character 

Null character is used to store in a string termination Characters are stored in contiguous memory location  

Initializing String :-

 char s[] = {'D', 'E', 'E','P','A','K','\0'};

 There is another shortcut for initializing string in C language :

char s[] = "HARRY"; => In this cause c add the null character automatically

Link :- Click here to get the program of  The initialization of string.

String in a Memory:-

 A string stored just like array in the memory as shown below

 

Quick Quiz. :- Create a string using " " and print its content using a loop 

Link :- Click here to get the solution of quick quiz.

Printing String:- 

A string can be printed character by character using printf and %c

but there is another convenient way  to print the string in C language. 

Link :- Click here to see the more convenient way to print the string.

Taking String input from the user:-

We can use %s with scanf to take string input from the user.


Scanf automatically adds the null character the enter key is pressed.

Note:

  •  The string should be short enough to fit into the array

  • Scanf cannot be used to input multi-word strings with spaces.

Gets() and puts()

gets() is a function which can be used to receive a multi- word strings.


Multiple gets() calls will be needed for multiple strings 

Likewise puts can be be used to output a 

puts(st); => prints the string place the cursor on the next line. 

Declaring a string using pointers:-

we can declare strings using pointers.

              char *ptr = "Deepak";
This tells the compiler to store the string in memory and assigned address is stored in a char pointer.

Note :-

  • Once a string is in initialized using char st[] = "Deepak", it cannot be re - initialized to something else.

  • A string defined using pointers can be reinitialized ptr = "Randeep"

Standard library functions for strings.

C provide a set of standard library functions for string manipulation.

Some of the most commonly used string functions are :

Strlen()

This function is used to count the number of character in the string excluding the null('\0') character


These function are declared under <string.h> header file.

strcpy()

This function is used to copy the content of second string into first string passed to it  

        char soure[] = "Deepak"

        Char target[30];

        strcpy(target, source); target now contain "Deepak"


strcat() 

This is function used to concatenate two strings 
     char = s1[]  = "HELLO"
     char = s2[]  = "DEEPAK"
      strcat(s1,s2);      // now s2 contain "HELLODEEPAK" (no space between them)

strcmp()

This function is used to compare two string it returns :0 if the string are equal 
Negative value if first string's mismatching character's  Ascii value is not greater than second string correspondingly mismatching character. It returns positive values otherwise. 
      strcmp("for ", "joke"); // positive value 
      strcmp("joke","For"); // Negative value 

 Practice set :- 

1. Which of the following is used to appropriately read a multi-word string

  1. gets()
  2. puts()
  3. printf()
  4. scanf()
Answer :- gets()

 2. write a program to take string as an input from the user using %c and %s confirm that the string are equal . 

Link:-  Click here to get the solution of above practice problem.

3. write your own version of strlen function from <string.h>  

Link:-Click here to get the solution of above practice problem.

 4. Write a function slice() to slice a string, it should change the original string that it is now the sliced string . Take m and n as the start and ending position for slice. 

Link:-  Click here to get the solution of the above practice problem.

5. Write you own version of strcpy function from <string.h>

Link :-  Click here to get the solution of the above practice problem.

6. Write a program to encrypt a string by adding 1 to the ascii value of the characters.

Link:- Click here to get the solution of the above practice problem.

 7. Write a program to decrypt the string encrypted using encrypt function in problem 6.

Link:- Click here to get the link of above practice problem.

8. Write a program to count the Occurrence of a given character in a string.

Link:- Click here to get the solution of the above practice problem.

9. Write a program to check Whether a given character is present in a string or not. 

Link :- Click here to get the solution of the above practice problem.

 Structure :- 

Arrays and strings => similar data (int , float char)

Structures can hold => dissimilar data 

Syntax for creating Structure:-

A c Structure can be created as follows:- 

Struct Employee {

          int Code; 

         float Salary;

        char name[10];

}

We can use this User defined data types as follows:

Link :- Click here to get the program of the implementation of the structure. 

So a structure in C is a Collection of variables of different types under a single name.

Quick Quiz:- Write a program to store the details of # employees from user defined data. Use the Structure declared above. 

Link:- Click here to get the solution of the above Quick quiz.

Why use Structure....?

We can create the data types in the Employee Structure but When the number of properties in a Structure increases, it becomes difficult for us to create data variables Without Structures. In a nut shell
  • Structure keep the data organized 
  • Structure make data management easy for the programmer.

Array of Structure :- 

Just like an array of integers, an array of floats and an array of characters, we can create an array of  Structure . 

Struct employee facebook[100]; => An array of Structures 

We Can access the data using: 

    facebook[0].code = 100;

    facebook[1].code = 101;

Initializing Structures :- 

 Structures can also be initialized as follows:-

Link :- Click here to get the program of another way of initializing the structure.

Structure in memory:- 

Structure are stored in contiguous memory locations For the Structure e1 of type Struct employee , memory layout looks like this: 

C- Structure Memory mapping in Hindi and English | Todaytutorials

In an array of Structure these employee instances are stored adjacent to each other. 

Pointer to Structure :- 

A pointer to Structures can be created as follows: 

Struct employee*ptr;

ptr = &e;

Now we can print Structure elements

   printf("%d", (*ptr).code);

Link :- Click here to get the implementation of pointer to the structure.

Arrow Operator :- 

Instead of Writing  (*ptr).code , we can use arrow operator to access structure properties as follow 

             (*ptr).code     or ptr->code

here is known as the arrow operator 

Passing Structure to a Function:- 

A structure can be passed to a function just like another data types. 

    Void show(struct employee e);  => Function prototypes 

Quick Quiz :- Complete this show function to display the control of employee.

Link :- Click here to get the Solution of above quick quiz.

Type def keyword :- 

We can use the typedef keyword to create an alias name for data types in c. typedef is more commonly used with Structures. 

Struct complex {

      float real;          => Struct complex C1,C2 ; for defining complex numbers

     float img;

}

type def struct complex{

         float real;          => complex no C1 , C2; for defining complex numbers

         float img 

} complexno;

 Link:- Click here to get the practice problem of typedef keyword. 

Practice set :- 

1. Create a two dimensional Vector using Structure in C. 

Link :- Click here to get the Solution of above practice problem.

2. Write a Function sumvector Which return the sum of two vector passed to it . The vector must be two dimensional. 

Link :- Click here to get the solution of above practice problem.

3. Twenty integer are to be stored in the memory what would you prefer array or structure....? 

Answer :- Array because all those 20 are integer.

4. Write the program yo illustrate the use of arrow operator -> in C language. 

Link :- Click here to get the solution of the above practice problem.  

5. Write a program with a structure repeating the complex number ...?

Link :- Click here to get the solution of the above practice problem .

6. Create an array of 5 complex numbers created in problem 5 an display them with the help of display function The value must be taken as an input from the user. 

Link:- Click here to get the solution of the above practice problem.

7.Create a structure representing a bank account of a customer . what fields did you use and why...?

Link :- Click here to get the solution of the above practice problem.

8. Write a structure capable of storing data write a function to compare those dates. 

Link :- Click here to get the solution of the above practice problem.

9. Solve problem 9 for time using typdef keywords...?

Link :- Click here to get the link of the above practice problem.

File I/O:-

The random Access memory is volatile and its content is lost once the program terminates. A C program can talk to the file by reading  content from it and writing control to it. 

A file is data stored in  storage in a storage device. A C program can talk to the file by reading content from it and writing content to it . 

FILE pointer :- 

"FILE" is structure which needs to be created for opening the file. 

A file pointer is a pointer to this structure of the file. 

File pointer is needed for the communication between the file and program . 

A file pointer  can be created as follow:

    FILE *ptr;

    ptr = fopen("filename.ext", "mode");

Link :- Click here to get the program to open a file in read and right mode.

File opening modes in C. 

C offers the programmers to select a mode for opening a file. 

Following modes are primarily used in C file I/O


  "r"  --> open for reading

  "rb" --> open for reading in binary 

If the file does not exist while reading fopen return null.

  "w"    --> open for writing 
  "wb"  -->  open for writing in binary 
 
If the file exists , the contents will be overwrite 
 
  "a" --> open for append --> If the file does not exist it will be created. 
 

Type of Files

These are two types of files:

  1. Text files (.txt, .c)
  2. binary files(.jpg, .dat)

Reading a file 

A file can be opened for reading as follows:

    FILE *ptr;

    ptr = fopen("Deepak.txt","r");

    int num; 

Let us assume that "Deepak.txt" Contains an integer We can read that  integer using:

   fscanf(ptr, "%d", &num);  ==> fscanf is file counter part of Scanf 

Link :-  Click here to get the program of reading the file.

This will read an integer from file in num variable. 

Quick Quiz: Modify the program above to check whether the file exists or not before opening the file. 

Link:-  Click here to get the solution of the quick quiz.

Closing the file :- 

It is very important to close the file after read or write. this is achieved using fclose as follows : 

       fclose(ptr);

This will tell the compiler that we are done working with this file and the associated resources could be freed. 

Writing to a file:- 

we can write to a file in a very similar manner like we read the file

        FILE *ptr; 

        fptr = fopen("Deepak.txt", "w");

        int num = 432;

        fprintf(fptr, "%d", num);

        fclose(fptr);

link :-  Click here to get the program to write in a file.

 fgetc() and fputc()

fgets and fputc are used to read and write a character from/to a file

fgetc(ptr)    => used to read a character from file 

fputc('c', ptr); => used to write character c to the file. 

Link:- Click here to get the program of fgetc and fputc.

EOF : End of File 

fgtec returns EOF when all the character from a file has been read so we can write a check to detect the file . 

Link:- Click here to check the program of implementation of EOF .

When all the content of the file has been read break the loop.

Practice set:-

1. write a program to read three integer from a file. 

Link :- click here to get the solution of the above practice problem.

2. Write a program to generate multiplication table of a given number in text format make sure the file is readable and well formatted 

Link:- Click here to get the solution of above practice problem. 

3. Write a program to read a text file character by character  and write it context twice in a separate file 

Link :- Click here to get the solution of the above practice problem.

4. write a program to modify a file containing an integer to double its value. 

Link:- Click here to get the solution of the above practice problem.

Project 2: snake, water, gun:-

snake, water, gun or rock, paper, scissors is a game most of us played during the school time. 

 Write a c program capable of playing this game with you 

your program should be able to print the result after you choose snake /water  or gun. 

Link:- Click here to get the source code of the above game project.

Dynamic memory Allocation. 

C is a language with  some fixed rules of programming For example:- changing in size of array not allowed 

Dynamic memory allocation:- 

Dynamic memory allocation is a way to allocate memory to a data structure during the runtime We can use DMA function available in C to allocate and free memory during runtime. 

Function for DMA in C 

following  function are available in C to perform dynamic memory allocation . 

  1. malloc()
  2. calloc()
  3. free()
  4. recall()

Malloc() Function:- 

malloc stands for memory allocation. It takes number of bytes to be allocated as an input and returns a pointer of type void

Link:- Click here to check the program of implementation of malloc.

 The expression returns a null pointer if the memory cannot be allocated 

calloc() Function:-

 calloc stands for continuous allocation It initializes each memory block with a default value of 0.

Link:- Click here to check the implementation of calloc.

 If the space is not sufficient , memory allocation is failed and a null pointer is returned.

Quick Quiz :- Write a program to create an array of size n using calloc where n is an integer entered by the user. 

Link:- Click here to get the solution of above Quick quiz.

 free() Function :- 

we can use free() Function to de allocate the memory. 

The memory allocated using calloc/malloc is not de allocated automatically. 

syntax :- 

       free(ptr); => Memory of ptr is released. 

Realloc() Function :- 

sometimes the dynamically allocated memory is insufficient or more than required. 

realloc is used to allocate memory of new size using the previous pointer and size 

Synatx:- 

                  ptr = realloc(ptr, newsize);

                  ptr = realloc(ptr, 3*sizeof(int));

 ptr now points to this new block of memory capable of storing 3 integers.

 Link:- Click here to check the implementation of realloc function in the program.

 Practice set :

1. write a program to dynamically create an array of size 6 capable of storing 6 integers. 

Link:- Click here to get the solution of the above practice problem.

2. use the array in problem 1 to store 6 integer entered by user 

Link:- Click here to get the solution of the above practice problem.

3. solve problem 1 using calloc()

Link:- Click here to get the solution of above practice problem.

4. create an array dynamically capable of storing 5 integer . Now use realloc so that it can know store 10 integers. 

Link:- Click here to get the solution of the above practice problem.

5. create an array of multiplication table of 7 up to 10(7x10 = 70). use realloc to make it store 15 number (from 7x1 to 7x15)

Link:- Click here to get the solution of above practice problem.

6. Attempt problem 4 using calloc()

Link:- Click here to get the solution of the above practice problem. 

************* This is complete explanation of C language  hope u like it ******************

Contact me at:- 

Instagram

Twitter 

LinkedIn 

Comments

Post a Comment

Popular Posts