Spread the love

Free Learning C Programming Language Step By Step

Spread the love

Table of Contents

Introduction to Learning C Programming

Let’s touch on a few important goals of these tutorials before we get started on Free Learning C Programming Language Step By Step. For instance, books will skip programming style sections, common pitfalls, debugging, good /bad programming practices and debugging. This tutorial covers best programming practice exercises and programs for you to learn and understand easily.

  • This Blog Tutorial consists of a lot of daily life example programs for understanding concepts, which helps learners to understand in an effective and better way.
  • Provide practice programs at the end of tutorial documents.

‘C’ seems a bizarre title for a programming language. But this weird sounding language is one particular of the most common laptop language today simply because it is structured, higher stage, machine unbiased language. It will allow computer software developers to establish applications without the need of stressing about the components platforms the place they will be implemented.

The root of all present-day language is ALGOL, introduced in the early 1960s. C was developed from ALGOL, BCPL, and B by Dennis Ritchie at the Bell Laboratories in 1972.

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A. Dennis Ritchie is known as the founder of the c language. It was developed to overcome the problems of previous languages such as B, BCPL, etc.

Language designers: Bjarne Stroustrup

Language paradigmsProcedural programming.

  • C language was initially used for system development work, in particular, the programs that make-up the operating system.
  • C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. …
  • Today C is the most widely used System Programming Language.

C makes use of lots of concepts from these languages and adds the concepts of knowledge sorts and other strong features. Due to the fact it was produced together with the UNIX working technique, it is strongly affiliated with UNIX. In the course of the 1970’s, C experienced advanced what is recognized as ‘traditional C’.

To guarantee that C language stays conventional, in 1983, American National Benchmarks Institute(ANSI) appointed a complex committee to define a standard for C. The committee accepted an edition of C in December 1989 which is now identified as ANSI C. It was then approved by Global Benchmarks Firm(ISO) in 1990. This version of C is also referred to as C89.

Major Applications of C

The escalating acceptance of C is almost certainly owing to its many fascinating qualities. It is a strong language whose wealthy set of crafted-in features and operators can be utilized to write any elaborate method.

The C compiler brings together the abilities of an assembly language with capabilities of a higher stage language and hence it is nicely suited for crafting the two technique program and business deals. In numerous of C compilers accessible in the marketplace are published in C.

Courses prepared in C are productive and quick. This is because of its wide range of facts kinds and effective operators. C is really moveable. This suggests that C packages composed for one particular pc can run on a further with minimal or no modification.

Portability is essential if we system to use a new computer system with a unique operating method. C language is very well suited for structured programming, consequently demanding the user to assume a challenge in conditions of operating modules or blocks.

  • Operating Systems
  • Language Compilers
  • Assemblers
  • Text Editors
  • Print Spoolers
  • Network Drivers
  • Modern Programs
  • Databases
  • Language Interpreters
  • Utilities

An appropriate assortment of these modules would make a comprehensive system. This modular structure makes application debugging, tests and upkeeps simpler. One more crucial element of C is its potential to lengthen alone.

A C method is essentially collections of functionality that are supported by the C library. We can continually incorporate our individual function to the C library. With the availability of a significant quantity of capabilities, the programming tasks develop into simple.

Topics I am going to cover

Basics

  • Setting Up Compiler
  • Applications of C
  • #include < stdio.h >

·         Tokens in C

  • Introduction to # include directives
  • Variables and the Assignment Statement
  • Literals
  • Identifiers
  • Writing your first C program.
  • Integer Data Types
  • Floating-Point Data Types
  • The char
  • The String
  • The bool data type
  • Arithmetic Operators
  • Programming Style

 Decision Making in C

  • Relational operators
  • If Statements
  • If/else statements
  • Nested if/else if statements
  • Nested if statements
  • The switch Statement
  • Enumerated Data Types

Looping Concepts in C

  • While loop
  • Using the while Loop for Input Validation
  • Nested while loop
  • Do while loop
  • For loop
  • For each loop
  • Nested for loop
  • Breaking Out of a Loop

 Functions in C 

  • Function Prototypes
  • Sending Data into a Function
  • Passing Data by Value
  • The return Statement
  • Returning a Value from a Function
  • Returning a Boolean Value
  • Local and Global Variables
  • Static Local Variables
  • Default Arguments
  • The exit() Function

Advanced Concepts

  •  Arrays
  • Arrays Hold Multiple Values
  • Accessing Array Elements
  • Inputting and Displaying Array Data
  • Array Initialization
  • Arrays as Function Arguments
  • Two-Dimensional Arrays
  • Arrays of Objects

 Pointers in C

  •  Pointers and the Address Operator
  • Pointer Variables
  • Array vs Pointers
  • Pointer Initialization
  • Advanced topics on Pointers

 Structures in C

  • Basic Syntax
  • Structures with Array
  • Structures Passing into Functions
  • Structures with pointers

 

Installation of Compiler

System Requirements for dev c+ 

  • Windows 95 or higher.
  • 32 MB of RAM.
  • The executables compiled by DevC++will need MSVCRT. DLL (comes with Windows 95 OSR 2 or higher)

Note: Dev c++ can also be used for C language

Other Compilers are as below:

  • MS Visual Studio
  • Turbo C
  • Code Blocks

 How to download C

Click on the link below for downloading the compiler for c.

Steps to download:
C Download -Learning C Programming
C Download -Learning C Programming
  •  Click on the Download button shown in the picture.
download C link
download C link
  • Scroll down from top to bottom and search for Dev c++.
Download Dev C++
Download Dev C++
  • Then click on download and setup will start downloading and then install it into your drive c.
Go to download page
Go to the download page

Steps to install:

  1. This is a 9 MB file approx.
  2. Double click the executable file.
  3. Start the installation by clicking the Next button.
  4. Choose the destination folder and install it.
  5. Once the installation is complete, go to My Computer > Properties > Advanced System Settings > Advanced Tab.
  6. Now click on the “Environment variables” button > new.
  7. Change the system variable name as PATH.
  8. Change the variable value as C:\Dev-Cpp\bin;
  9. Click OK and start Dev C to write the program.

#include < stdio.h >

The first line of the program #include < stdio.h > is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation. #include directives are not C statements. They are commands to the pre-processor which runs prior to the compiler. Their job is to set programs up in a way that makes life easier for the programmer.

For example, any program that uses the print object must contain the extensive setup information found in the conio.h file. The programmer could type all this information into the program, but it would be very time-consuming.  So that’s why we use this approach to make the more less and efficient way of programming for the developer.

Tokens in C

A ‘C’ program is composed of different tokens and a token is either a keyword, an identifier, a constant, a literal string, or a symbol.

For example, statement C below consists of five tokens

Variables and the Assignment Statements in C 

Basic Concept:

Variables represent storage locations in the computer’s memory. Values can be stored in them by using an assignment statement.

The most common form of a statement in a program uses the assignment operator, =, and either an expression or a constant to assign a value to a variable:

 variable = expression;
 variable = constant;

 

The symbol of the assignment operator looks like the mathematical equality operator but in C its meaning is different. The assignment statement indicates that the value given by the expression on the right-hand side of the assignment operator (symbol =) must be stored in the variable named on the left-hand side.

The assignment operator should be read as “becomes equal to” and means that the variable on the left-hand side has its value changed to the value of the expression on the right-hand side.

Example Program:

This program has a variable.

#include<stdio.h>
#include<conio.h>

 int main ()
 {
    int X;
    X = 5;	
   printf ("X is assigned to value %d ", X);
}

Output Displayed on the compiler
X is assigned to value 5

Literals

A literal is a piece of data that is written directly into a program’s code. A literal is a piece of data written directly into a program’s code. One of the most common uses of literals is to assign a value to a variable. A literal is a piece of data written directly into a program’s code.

One of the most common uses of literals is to assign a value to a variable. In Program the following statement assigned the literal value 5 to the variable number. This can be directly assigned value to a variable without declaring again.

This Is an example of declaring string literals in C.


"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

Identifiers in C

A variable name should indicate what the variable is used for. An identifier is a programmer-defined name that represents some element of a program.

Variable names are examples of identifiers. You may choose your own variable names in C, as long as you do not use any of the C keywords.

The following table shows us the Examples of Identifiers which are commonly used in c.

identifiers in C
identifiers in C

Input Statement in C

Statement Input and Output are used in C programming to read and write the data. In stdio.h (standard header input/output file) these are embedded.  For this reason, there are primarily two Input / Output functions used.

Those are addressed as follows:

#include<stdio.h>
#include<conio.h>

  
int main() 
{ 
    int age; 
  
    printf("Enter your age below in integer foam:"); 
    scanf(“%d”,age);
    printf ("Your age is: ", age); 
  
    getch(); 
} 

Input:
5

Output on Screen:

Your age is: 5

The above program asks the user to input the age. The object scanf is connected to the input device. The age entered by the user is extracted from scanf using the operator and the extracted data is then stored in the variable age present on the right side of the extraction operator.

Integer Data Types

There are many different types of data. Variables are classified according to their data type, which determines the kind of information that may be stored in them. Integer variables can only hold whole numbers.

Integers are whole numbers like -2, 19, and 24. Floating-point numbers have a decimal point like -2. 35, 19.0, and 0.024. Additionally, the integer and floating-point data types are broken into even more classifications.

Your primary considerations for selecting the best data type for a numeric variable are the following:

  • Whether the variable needs to hold integers or floating-point values.
  • The largest and smallest numbers that the variable needs to be able to store.
  • whether the variable needs to hold signed (both positive and negative) or only unsigned (just zero and positive) numbers.
  • The number of decimal places of precision needed for values stored in the variable.
Datatypes in C
Datatypes in C

Declaration of Integers in c syntax is as below:

The declaration of integer in C are as follows:

int a;
int b;
int c;

Floating-Point Data Types

Floating-point data types are used to define variables that can hold real numbers.

 C uses the decimal point to distinguish between floatingpoint numbers and integers, so a number such as 5.0 is a floatingpoint number while 5 is an integer. Floatingpoint numbers must contain a decimal pointNumbers such as 3.14159, 0.5, 1.0, and 8.88 are floatingpoint numbers.

Basic Syntax to Declare floating-point values:

float distance = 1 .496E8;

This table below shows the processing and memory consumption of floating-point values in c as below:

precision table in C
the precision table in C

The char data type in C

The char data type is used to store individual characters. To this point, the fundamental data types we’ve looked at have been used to hold numbers (integers and floating-point) or true/false values (Booleans). But what if we want to store letters? The char data type was designed for such a purpose.

The char data type is an integral type, meaning the underlying value is stored as an integer, and it’s guaranteed to be 1-byte in size. However, similar to how a Boolean value is interpreted as true or false, a char value is interpreted as an ASCII character.

ASCII stands for American Standard Code for Information Interchange, and it defines a particular way to represent English characters (plus a few other symbols) as numbers between 0 and 127 (called an ASCII code or code point). For example, ASCII code 97 is interpreted as the character ‘a’.

The ASCII table is also below.

ASCII Table
ASCII Table

Example of a char data type program:

#include<stdio.h>
#include<conio.h>
 
 
int main()
{
    char ch1=  { 'A' }; // (preferred)
    printf(“%d”, ch1); // printf prints a character
 
    char ch2 = { 98 }; // code point for 'b' (not preferred)
    printf(“%d”, ch2); // printf prints a character
 
 
    getch();
}

Output on Screen:
A 98

Strings in c

A string variable contains a collection of characters surrounded by double-quotes.Let’s take an example program:

string greeting = "Hello";
This is the basic syntax for declaring string in c
We also have to include string library for this purpose
// Include the string library
#include 
// Create a string variable
string greeting = "Hello"

The Difference Between Character Literals and String Literals in C

printf(“%d”, ‘ H’); This displays a character literal.
printf(“%d”, ‘ Hello’); This displays a string literal.

This means to say that character literal consists of a single alphabet and string literal consists of a group of alphabets and in the form of word.

Boolean data type in C

The Boolean data type is used to declare a variable whose value will be set as true (1) or false (0). To declare such a value, you use the bool keyword. The variable can then be initialized with the starting value. A Boolean constant is used to check the state of a variable, an expression, or a function, as true or false.

Syntax of Boolean in C

bool GotThePassingGrade = true;

Example program of boolean data type:

void main()
{
bool isaFun = true;
bool isNotaFun = false;
printf(“%d”,isaFun);   
printf(“%d”,isNotaFun);  
}

Output on Screen:
True
False

How to determine the size of a data type in C?

The size of the operator may be used to determine the size of a data type on any system. In general computers, we do not have a lot of memory for management so we need to declare variables according to their sizes and preference so it is known fact and important to know how to calculate the size of data types this program below shows us the same thing.

#include<stdio.h>
#include<conio.h>

Void main()
{
printf("The size of short is: %d\n", sizeof(short x));
printf("The size of char is %d\n", sizeof(long y));
}

Output on Screen:
The size of the short is: 1
Size of char is: 4

Arithmetic Operators In C

Here are C’s five basic arithmetic operators:

  • The +operator adds its operands. For example, 4 + 20 evaluates to 24.
  • The -operator subtracts the second operand from the first. For example, 12 – 3 evaluates to 9.
  • The *operator multiplies its operands. For example, 28 * 4 evaluates to 112.
  • The /operator divides its first operand by the second. For example, 1000 / 5 evaluates to 200. If both operands are integers, the result is the integer portion of the quotient. For example, 17 / 3 is 5, with the fractional part discarded.
  • The %operator finds the modulus of its first operand with respect to the second. That is, it produces the remainder of dividing the first by the second. For example, 19 % 6 is 1 because 6 goes into 19 three times, with a remainder of 1. Both operands must be integer types; using the % operator with floating-point values causes a compile-time error. If one of the operands is negative, the sign of the result depends on the implementation.

Of course, you can use variables as well as constants for operands. Listing 3.10 does just that. Because the % operator works only with integers, we’ll leave it for a later example.

This table shows us the major function and use of arithmetic operators

Arithmetic Operator in Java
Arithmetic Operator in Java

Let’s take an example that shows us the perfect use of arithmetic operators and make us more clear.

#include<stdio.h>
#include<conio.h>

void main() 
{

// we will add these two numbers 
  int n = 25;
  int m = 13;
  printf("Total of n + m = ", (n + m));

}

Output on Screen:
Total of n + m = 38;

Increment and decrement operators

Increment operators are used for increasing the value of the variable by one and decrement operators are used to decrease the value of the variable by one.

Both increment and decrement operator are used on single operand or variable, so it is called as unary  operator.  Unary operators are having a higher priority than the other operators it means unary operators are execute before other operators.
Example program;

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=++i;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

 Output on Screen:

 X: 11

I: 11

Comments in C

Comments are notes of explanation that document lines or sections of a program.
Single-Line Comments – This can be done by using “//” this symbol at the start of the line.
Example:
// This is a single-line comment
Multiple Line Comments – This can be done by using “/*” this symbol at the starting point and ends with “*/” this symbol at the endpoint.

Example:
/*
This is multiple
Line 
Comment 
Example
*/

Programming Style in C

Programming style refers to the way a programmer uses identifiers, spaces, tabs, blank lines, and punctuation characters to visually arrange a program’s source code.

Best programming styles to use in a program to make more readable and good looking with professional approach.

  • Readability
  • Maintainability
  • Comments
  • Naming

Decision Making Programming in c

Relational Operators

Relational operators allow you to compare numerically and char values and determine whether one is greater than, Jess than, equal to, or not equal to another.

The table below shows the exact detail of relational operators

Relational Operators in C
Relational Operators in C

So, we already understand from the table above now it’s time to understand through the example of this understanding, here below is the example with the solution.

Expressions in C
Expressions in C

Logical Operators

Logical operators connect two or more relational expressions into one or reverse the logic of an expression.

Logical Operators in C
Logical Operators in C

In the above table, I created is just to show you what is the purpose of these operators in c program with if/else/if/else if statement
Note: This program shows us about OR operator and AND operator with if statement.

Branching statements in C

If statement

The if statement can cause other statements to execute only under certain conditions. The figure below is the famous figure associated with all books and it is the best way of understanding if statement.

Without a conditional statement such as the if statement, programs would run almost the exact same way every time. If statements allow the flow of the program to be changed, and so they allow algorithms and more interesting code.

Below this is the perfect example that shows the use of if statement in c with basic syntax and conditions statement.

If condition in C
If condition in C

Example of If in C


#include<stdio.h>
#include<conio.h>

int main()
{
    int x = 20;
    int y = 22;
    if (x<y)
    {
        printf("Variable x is less than y");
    }
    return 0;
}

Output on Screen:
Variable x is less than y

Furthermore, examples for a better understanding of if the statement is as below in the table

more examples of if in C
more examples of if in C

Note: you should not miss brackets of if statement and braces of if statement at the start and endpoint.

The if /else statement in C

If else statements in C is also used to control the program flow based on some condition, only the difference is: it’s used to execute some statement code block if the expression is evaluated to true, otherwise executes else statement code block.

The example of if/else statement in the foam on the table is as below:

if else in C
if-else in C

This example shows us that if the condition in if statement is true then it will be executed and else the statement will be neglected and will not be checked and if the statement is false then the compiler goes down and check the else statement and print the else statement answer.

The if-else Syntax in C
if(test_expression)
{
   //execute your code
}
else
{
   //execute your code
}
if-else Sample example
#include<stdio.h>
#include<conio.h>

int main()
{
    int x, y;
    printf("enter the value of x:");
    scanf("%d", &x);
    printf("enter the value of y:");
    scanf("%d", &y);
    if (x>y)
    {
	printf("x is greater than y\n");
    }
    if (x<y)
    {
	printf("x is less than y\n");
    }
    if (x==y)
    {
printf("x is equal to y\n");
    }
    printf("End of Program");
    return 0;
}

Output on Screen:
enter the value of x:20
enter the value of y:20
x is equal to y
End of Program

Nested if/else if Statements

The if-else if the statement is a chain of if statements. They perform their tests, one after the other until one of them is found to be true.

Nested If else in C
Nested If else in C

Sample program of if/else if statement-

This example shows us about the grading system in various colleges in India.

First, if statement will be checked and then if it is true then print the if statement and if it becomes false then goes on else/if statement if will be checked and so on at the end, it will go to else statement which is far more easy to code instead of using if/else chain.

Nested if statement in C

To test more than one condition, an if statement can be nested inside another if statement.

Nested if it can be used in menu-driven programs in which we have to check more than one condition at the same time. Like we saw the point of sale system in which there is a menu for the user.

#include<stdio.h>
#include<conio.h>

int main()
{
	int num=1;
	if(num<35)
	{
		if(num==1)
		{
			printf("The value is as below :%d\n",num);
		}
		else
		{
			printf("The value is greater than 1 then below see");
		}
	}
	else
	{
		printf("The value is greater than 10 so lets check");
	}
	return 0;
}

Output on Screen:
You passed.
Perfect!

Another example of this approach is as below:

complex if else in C
complex if else in C

Switch statement in C

The switch statement uses the value of a variable or expression to determine where the program will branch to.

The switch case statement is used when we have multiple conditions as we deal in point of sale system where the user comes and want to purchase things of multiple-choice, and we need to perform different action based on the condition. When we have multiple conditions and we need to execute a block of statements when a particular condition is satisfied.

In such a case either we can use lengthy if or else or if/else or maybe nested if statements or switch case. The problem with lengthy if or else or if/else or maybe nested if statements are that it becomes complex when we have several conditions.

The switch case is a short and efficient method of handling such scenarios with a smaller number of lines of code and with more readability.

Important tip: if the switch condition becomes true then it goes down and checks the case of switch cases one by one like else if statements.

Switch Statement in C
Switch Statement in C

In the above, there is a basic syntax of a switch statement which shows us the first expression statement in which we pass a single value or variable which considers as a primary condition and other cases below will be checked on the basis of this condition.

Example of Switch case in C

 /* C program to implement simple functions of a calculator*/


#include<stdio.h>
#include<conio.h>

 
int main()
{
    int num1,num2;
    float result;
    char ch;    //to store operator choice
     
    printf("Enter first number: ");
    scanf("%d",&num1);
    printf("Enter second number: ");
    scanf("%d",&num2);
     
    printf("Choose operation to perform (+,-,*,/,%): ");
    scanf(" %c",&ch);
     
    result=0;
    switch(ch)    
    {
        case '+':
            result=num1+num2;
            break;
             
        case '-':
            result=num1-num2;
            break;
         
        case '*':
            result=num1*num2;
            break;
             
        case '/':
            result=(float)num1/(float)num2;
            break;
             
        case '%':
            result=num1%num2;
            break;
        default:
            printf("Invalid operation.\n");
    }
 
    printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
    return 0;
}

Output on Screen:

First run:
Enter first number: 10
Enter second number: 20
Choose operation to perform (+,-,*,/,%): +
Result: 10 + 20 = 30.000000

Second run:
Enter first number: 10
Enter second number: 3
Choose operation to perform (+,-,*,/,%): /
Result: 10 / 3 = 3.333333

Third run:
Enter first number: 10
Enter second number: 3
Choose operation to perform (+,-,*,/,%): >
Invalid operation.
Result: 10 > 3 = 0.000000

Enumerated Data Types in C

An enumerated data type in C is a programmer-defined data type whose legal values are a set of named integer constants.


#include<stdio.h>
#include<conio.h>


enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun}; 
  
int main() 
{ 
    enum week day; 
    day = Wed; 
    printf("%d",day); 
    return 0; 
}

Output on Screen:

Day name is 4

Looping concepts in C

The while Loop

while loop statement repeatedly executes a statement that is in the brackets as long as a given condition in brackets is true and it will stop executing when the condition becomes false.

While loop in C
While loop in C

This diagram shows the basic syntax of while loop execution and below there is a program of while loop.

Example of while loop in C
#include 
int main()
{
   int count=1;
   while (count <= 4)
   {
	printf("%d ", count);
	count++;
   }
   return 0;
}

Output on Screen:

1
2
3
4

Note: if the condition in while loop becomes more problematic it will execute on compile time as infinite and cannot control until we stop the execution.

Tips for while loop: 
  • Use where we need targeted situation
  • Do not forget braces at start and endpoint it is a syntax error in c.
  • Do not forget the semicolon.

Using the while Loop for Input Validation

The while loop can be used to create input routines that repeat until acceptable data is entered.

While loop in C example
An example of While loop for input validation
While (age < 13 || age > 99) {
  printf("Invalid age, re-enter: ");
  sacanf(“%d”,age);
}

Do while loop in C

The do-while loop is a post-test loop, which means its expression is tested after each iteration.

do while loop in C
do-while loop in C

In this above diagram, it shows us that everything is in the do braces and at the end, we insert while loop braces and it will execute at the end after everything is run at compile time.

Why we use the do-while loop?

The C dowhile loop is used to iterate a part of the program several times. If the number of iterations is not fixed and you must have to execute the loop at least once, it is recommended to use the dowhile loop. The C dowhile loop is executed at least once because the condition is checked after the loop body.
Example


#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}
while (j<=3);
return 0;
}

Output on Screen:

Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3

The difference between while and do-while loop

  1. The while loop checks the condition at the starting of the loop and if the condition is satisfied statement inside the loop, is executed. As against, in the do-while loop, the condition is checked after the execution of all statements in the body of the loop.
  2. If the condition in a while loop is false, not a single statement inside the loop is executed. In contrast, if the condition in the ‘do-while’ loop is false, then also the body of the loop is executed at least once then the condition is tested.
  3. The while loop is also known as the entry-controlled and pre-checking loop because in this loop, the body of the loop is executed prior to checking the condition. Conversely, the alternate name for the do-while loop is the exit-controlled and post-checking loop, the reason behind this is that the checking of the loop condition is followed by the execution of the body of the loop.
  4. The syntax of a do-while loop includes a semi-colon to terminate the loop. On the contrary, there is no use of the semi-colon in the while loop syntax.

For Loop

The for loop is a pretest loop (means it is more versatile) that combines the initialization, testing, and updating of a loop control variable in a single loop header.

syntax for for loop in C
the syntax for loop in C

In the above diagram, this shows us the basic foam of for loop the initial statement is called the statement which executes the for loop and it will execute on the base of test condition which is in the second place and at the end, it checks the update statement.

Example of for loop
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; i--)
    {
     printf("%d ", i);
     }
return 0;
}

Output on Screen:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, goodbye!

Nested for loop in C

Nested for loop is used to calculate the sum of two 2-dimensional matrices. The program consists of three for nested loops where the outer loop runs equal to the size of row and the inner loop runs equal to the size of the column. Basic Syntax of nested loop. It can also be used to print some specific patterns for the sake of the user. It is also called a loop in a loop.

The syntax for nesting for loop in C

for ( initial_condition; testcondition; incrementcondition ) {
   for ( initial_condition; testcondition; incrementcondition ) {
      statement(s);
   }
   statement(s); // put as many as you want!
}
Example of nesting for loop
#include <stdio.h>
int main()
{
    int i=1,j;
    while (i <= 5)
    {
        j=1;
        while (j <= i)
        {
            printf("%d ",j);
            j++;
        }
        printf("\n");
        i++;
    }
    return 0;
}

Output on Screen:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

How to break out of a loop in C

Break; is the keyword we need to use to break out of a loop in C.

The break statement gets you out of a loop. No matter what the loop’s ending condition, break suddenly. The program continues with the next statement immediately following the loop. Break stops only the loop in which it resides. It also does break from nested loops.

Why we use Functions in C or what is C function?

function is a block of code that only runs when it is called.it will not automatically run on run time like other if statements and tells us the result. You can pass data, known as parameters, into a  function.

Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times as you want it to lessen the number of lines of code and make code more efficient and readable and faster and more understandable.

Benefits of Functions:
  • By using functions, we can avoid rewriting the same logic/code again and again in a program.
  • We can call C functions any number of times in a program and from any place in a program.
  • We can track a large C program easily when it is divided into multiple functions.
  • Reusability is the main achievement of C functions.
  • However, Function calling is always overhead in a C program.

How to prototype a Function?

  • A function prototype is a declaration of the function that tells the program about the type of value returned by the function and the number and type of arguments.
  • Function prototyping is one very useful feature of C function. A function prototype describes the functional interface to the compiler by giving details such as the number and type of arguments and the type of return values.
  • The prototype declaration looks just like a function definition except that it has no body i.e., its code is missing. This is the time you knew the difference between a declaration and a definition.
  • A declaration introduces a (function) name to the program whereas a definition is a declaration that also tells the program what the function is doing and how it is doing.
  • Thus, the above-given examples are function definitions and the following are declarations or shall we say function prototypes:

Example of the prototype function in C

int functiona(int a); 
// this is function of type int return type
int funb(int n1, int n2);

Hoe to send data into a Function?

Once we declared the function, we can send parameters into the function to do more tasks. In the example below int, a and int n1 and int n2 are the data that can be sent into the functions.
Example:


int a(int a);
int b(int n1, int n2);

Passing Data by Value in C

In call by value, the actual value that is passed as argument is not changed after performing some operation on it. When call by value is used, it creates a copy of that variable into the stack section in memory. When the value is changed, it changes the value of that copy, the actual value remains the same.

Example of Call by value in C
#include <stdio.h>
int addNumbers(int a, int b);         // function prototype
int main()
{
    int n1,n2,sum;
    printf("Enters two numbers: ");
    scanf("%d %d",&n1,&n2);
    sum = addNumbers(n1, n2);        // function call
    printf("sum = %d",sum);
    return 0;
}
int addNumbers(int a, int b)         // function definition   
{
    int result;
    result = a+b;
    return result;                  // return statement
}

Call by Reference in C

In call by reference, the actual value that is passed as argument is changed after performing some operation on it. When a call by reference is used, it creates a copy of the reference of that variable into the stack section in memory. Is uses a reference to get the value? So, when the value is changed using the reference it changes the value of the actual variable.

Example of Call by Reference in C
#include <stdio.h> 
/* function declaration */
void swap(int *x, int *y);
 int main () {
   /* local variable definition */
   int a = 100;
   int b = 200;
    printf("Before swap, value of a is as below : %d\n", a );
   printf("Before swap, value of b is as below: %d\n", b );
    swap(&a, &b);
   printf("After swap, value of a is changing : %d\n", a );
   printf("After swap, value of b is changing : %d\n", b );
    return 0;
}

Output on screen:
Before swap, value of a is as below :100
Before swap, value of b is as below :200
After swap, value of a is changing :200
After swap, value of a is changing :100

Tips for this coding:

  • The call by reference is mainly used when we want to change the value of the passed argument into the invoker function.
  • One function can return only one value. When we need more than one value from a function, we can pass them as an output argument in this manner.

The return Statement

The return statement stops execution and returns to the calling function. When a return statement is executed, the function is terminated immediately at that point, regardless of whether it’s in the middle of a loop, etc.

Example of the return statement
int max(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}//end max

How to Return a Value from a Function?

We can also return value from a function at the end of the function.

Function structure in C
Function structure in C
Example of return from function in C
int max(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
int r = a+b;
return r; // this is the return value from a function
}//end max

How to return a Boolean Value from function in C?

Functions may return true or false values. In the first case that is when C is used it is better to use return type bool.

Local and Global Variables in C

  • Variable Scope in C Inside a function or a block which is called local variables, the variables which are declared outside of all the function and accessible from all functions including the main function are known as Global variables.
  • Consider the program: In this example, we have shown how global and local variable behaves and to manipulate them.
Example of Local and Global Variable in C
#include 
 
int main () 
{

// this is local variable
  int a, b;
  int c;
 
  a = 15;
  b = 20;
  c = a + b;
 

  printf ("local a = %d, b = %d and c = %d\n", a, b, c);
 
  return 0;
}

Output on screen:

Local a = 15, b = 20, c = 35

What are static Local Variables in C?

Static variables in a Function: When a variable is declared as static, space for it gets allocated for the lifetime of the program. Even if the function is called multiple times, space for the static variable is allocated only once and the value of the variable in the previous call gets carried through the next function call.

Example of a static local variable in C
#include<stdio.h> 
int fun() 
{ 
  static int count = 0; 
  count++; 
  return count; 
} 
   
int main() 
{ 
  printf("%d ", fun()); 
  printf("%d ", fun()); 
  return 0; 
}

Output on screen:

1 2

What are Default Arguments in C

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function doesn’t provide a value for the argument with a default value.

Following is a simple C example to demonstrate the use of default arguments. We don’t have to write 3 sum functions, only one function works by using default values for 3rd and 4th arguments.

Example of Default Arguments in C
int x(int = 1, int); // error, assuming there's no previous declaration of x
 
void f(int n, int k = 1);
void f(int n = 0, int k); // OK: k's default supplied by previous decl in the same scope
 
void g(int, int = 7);
void h() {
  void g(int = 1, int); // Error: not the same scope
}

How to exit from Function?

The exit () Function- Terminates the process normally, performing the regular clean-up for terminating programs. Normal program termination performs the following (in the same order):

  • Objects associated with the current thread with thread storage duration are destroyed (C only).
  • Objects with static storage duration are destroyed (C) and functions registered with atexit are called.
  • All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed.
  • Control is returned to the host environment.

This statement can be used as an exit statement in C

void exit(int status);

How to clear the Screen

The following command can be used to clear screen on the window

System(“pause”);

Arrays in C or concept of Array in C language

Array is  a very important concept while Learning C Programming. An array allows you to store and work with multiple values of the same data type. Learning C Programming is not completed without the concept of Array.

Array decleration in C
Array declaration in C
Arrays in C
Arrays in C

Arrays Hold Multiple Values

The array can hold multiple values and can be used consecutive space in the memory. It is one of the major drawbacks of the array but it also has benefits.

Benefits of Array in C: 
  • Arrays represent multiple data items of the same type using a single name.
  • In arrays, the elements can be accessed randomly by using the index number.
  • Arraysallocate memory in contiguous memory locations for all its elements.

Drawbacks of Array in C:

  • Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
  • Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.
How to Access Array Elements in C

The elements of the array can be assessed using loops i.e mostly we use for loop for this purpose. The individual elements of an array are assigned unique subscripts. These subscripts are used to access the elements. Subscript numbering in C always starts at zero. The subscript of the last element in an array is one less than the total number of elements in the array.

An Example of an Array
// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

How to pass Arrays as Function Arguments in C?

C does not allow to pass an entire array as an argument to a function. However, you can pass a pointer to an array by specifying the array’s name without an index.

If you want to pass a single-dimension array as an argument in a function, you would have to declare function formal parameters.

The basic syntax for passing the array to function
void my_Function(int param[10]) {
   .
   .
   .
}
Arrays holding multiple values
#include <stdio.h>
void display(int age1, int age2)
{
    printf("%d\n", age1);
    printf("%d\n", age2);
}

int main()
{
    int ageArray[] = {2, 8, 4, 12};

    // Passing second and third elements to display()
    display(ageArray[1], ageArray[2]); 
    return 0;
}

Output on screen:

8
4

Two-Dimensional Arrays in C

A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data.

The declaration of 2d array looks like this in the following table below:

two dimentional array in C
two-dimensional array in C

We use nested for loop generally to initialize 2d arrays.

Example of two-dimensional array in C
#include
int main(){
   /* 2D array declaration*/
   int disp[2][3];
   /*Counter variables for the loop*/
   int i, j;
   for(i=0; i<2; i++) {
      for(j=0;j<3;j++) {
         printf("Enter value for disp[%d][%d]:", i, j);
         scanf("%d", &disp[i][j]);
      }
   }
   //Displaying array elements
   printf("Two Dimensional array elements:\n");
   for(i=0; i<2; i++) {
      for(j=0;j<3;j++) {
         printf("%d ", disp[i][j]);
         if(j==2){
            printf("\n");
         }
      }
   }
   return 0;
}

Output on Screen:

Enter value for disp[0][0]:1
Enter value for disp[0][1]:2
Enter value for disp[0][2]:3
Enter value for disp[1][0]:4
Enter value for disp[1][1]:5
Enter value for disp[1][2]:6
Two Dimensional array elements:
1 2 3
4 5 6

Pointers in C

This is another  very important concept while Learning C Programming. Every variable is assigning memory location whose address can be retrieved using the address operator &. The address of a memory location is called a pointer.

Pointers and the Address Operator
#include <stdio.h>
int main()
{
	int x=10;	//integer variable
	int *ptrX;	//integer pointer declaration
	ptrX=&x;	//pointer initialization with the address of x
	
	printf("Value of x: %d\n",*ptrX);
	return 0;
}

Output

Value of x: 10

What is the pointer variable in C?

A pointer variable is a variable that holds s addresses of memory locations. It can be declared as below:

int *x; 
Sample program to work with pointer variables
#include <stdio.h>
int main()
{
   int* pc, c;
   
   c = 22;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c);  // 22
   
   pc = &c;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 22
   
   c = 11;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 11
   
   *pc = 2;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c); // 2
   return 0;
}

Output on screen:

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784
Content of pointer pc: 22

Address of pointer pc: 2686784
Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

Array vs Pointers in C

Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing. Consider the following program.

Example Array vs Pointers in C
#include <stdio.h>
const int MAX = 3;
 
int main () {

   int  var[] = {10, 100, 200};
   int i, *ptr[MAX];
 
   for ( i = 0; i < MAX; i++) {
      ptr[i] = &var[i]; /* assign the address of integer. */
   }
   
   for ( i = 0; i < MAX; i++) {
      printf("Value of var[%d] = %d\n", i, *ptr[i] );
   }
   
   return 0;
}

Output on screen:

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Address of var[2] = 0xbfa088b8
Value of var[2] = 200

Structures in C

This is a very important concept while Learning C Programming. Pointers and arrays are inextricably connected. In addition, in many cases, the pointers and arrays are interchangeable. For example, by using either pointer arithmetic or array style indexing, a pointer pointing to the beginning of an array may access the array Consider the program which follows.

For example: 

You want to store some information about a person: his/her name, citizenship number, and salary. You can easily create different variables name, citNo, salary to store this information separately.

However, in the future, you would want to store information about multiple persons. Now, you’d need to create different variables for each information per person: name1, citNo1, salary1, name2, citNo2, salary2, etc.

Basic Syntax for Structure
struct Person
{
    char name [50];
    int age;
    float salary;
};

How to create Structures with Array?

Structures can be mostly used with arrays because we have to access data in the form of partitions.

Sample program to work with Structure with Array
#include <stdio.h>
#include <string.h>
struct Distance
{
    int feet;
    float inch;
} dist1, dist2, sum;

int main()
{
    printf("1st distance\n");
    printf("Enter feet: ");
    scanf("%d", &dist1.feet);

    printf("Enter inch: ");
    scanf("%f", &dist1.inch);
    printf("2nd distance\n");

    printf("Enter feet: ");
    scanf("%d", &dist2.feet);

    printf("Enter inch: ");
    scanf("%f", &dist2.inch);

    // adding feet
    sum.feet = dist1.feet + dist2.feet;
    // adding inches
    sum.inch = dist1.inch + dist2.inch;

    // changing to feet if inch is greater than 12
    while (sum.inch >= 12) 
    {
        ++sum.feet;
        sum.inch = sum.inch - 12;
    }

    printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);
    return 0;
}

Output on screen:

1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances = 15′-5.7″

How to pass Structures into Functions?

This is a very important concept while Learning C Programming. A structure variable can be passed to a function in a similar way as a normal argument. Consider this example:

#include <stdio.h>
#include <string.h>
struct student 
{
            int id;
            char name[20];
            float percentage;
};
 
void func(struct student record);
 
int main() 
{
            struct student record;
 
            record.id=1;
            strcpy(record.name, "Raju");
            record.percentage = 86.5;
 
            func(record);
            return 0;
}
 
void func(struct student record)
{
            printf(" Id is: %d \n", record.id);
            printf(" Name is: %s \n", record.name);
            printf(" Percentage is: %f \n", record.percentage);
}

Output on screen:

Id is: 56747
Name is: Animesh
Percentage is: 86.500000
Practice question on C

10 Causes Why C is the Best Programming Language For Beginners

With the myriad of programming languages these days, and the huge programming facts available in the World wide web, it can be tough for a beginner like you to know the place to begin. When it comes to programming language for newcomers, C is an great alternative. Not only will it teach you of programming fundamentals, this language is also effective and is extensively used in the marketplace these days.

Here are the factors why C is a fantastic programming language to start off with:

1.    You can not learn Java or C instantly.

For you to study and grasp C and Java languages, you need to have a rock-sound concept of the things of programming like classes, polymorphism, inheritance, and others. Appear to believe about it, how will you understand intricate principles like these if you are not even familiar with the basic things of personal computer programming? The language that starts from scratch is C and its foundational principles are the basis of any other programming principles we have these times.

2.    It is the foundation of C , C#, and Java.

C and C# are programming languages primarily based on C. Java also derives its syntax and programming notion from C. This is identified as the world’s most dominant programming language and it is also derived from C language.

3.    Programs that will need Object Oriented Programming (OOP) are prepared in C.

Java, C#, and C make use of OOP. Inspite of remaining highly effective, not all systems use it and those people utilizing it are nonetheless published in C.

4.    C features unbeatable functionality.

When it will come to velocity of execution, C is continue to unmatched.

5.    Most areas of Linux, Windows, and Unix are published in C.

So if you want to plan these OS, or if you wish to have your applications run in the claimed operating units, far better be common with C.

6.    Drivers of contemporary gizmos are composed in C.

Why is this so? Very well only because C provides users accessibility to the computer’s simple components. It also gives you with direct obtain to your CPU’s memory by means of ideas. You can also use C to control bits and bytes.

7.    Mobile telephones, PDAs, palmtops and other handheld products as properly as appliance are becoming a lot more popular than ever.

You may perhaps not be knowledgeable of it, but your handheld equipment and property appliances may well incorporate CPU that involves programming and has computer software dubbed as embedded program systems.

8.    Most Computer system game titles employ C as their basis.

No one particular will be intrigued in video games if it requires way too much time for commands to be carried out. C is utilized to make things quickly and prompt.

9.    C is regarded as a mid-level language.

Programming languages are classified into 3 – Low Degree, Middle Level, and Significant Level. Apart from staying consumer-oriented, high stage languages also make progress of systems speedy sufficient.

Equipment oriented, minimal level languages execute applications more rapidly. Center degree languages like C brings together the best characteristics of the higher and reduced amount of languages.

10.     C is a block-structured language.

This suggests each and every code is composed in an independent block and is not connected with the code in the following block. With this, you can make programming less complicated and you can reduce the options of unwanted aspect effects.

With the previously mentioned-stated factors, do you even now have uncertainties why C is the ideal pc programming language for newbies?

Questions on basic to Loops concepts:

Learning C Programming does not get completed if we do not learn coding in C. Coding is the ultimate help to Learn C. These question set will guide you further on How to code in C.

  • Draw patterns of various shapes like diamond and triangle with the help of for loop it may be nested loops.
  • Make point of sale system using while loop and for loop
  • Write a program in C to find the sum of first 10 natural numbers
  • Write a program in C to find the factorial of a number
  • Write a program in C to find the Greatest Common Divisor (GCD) of two numbers
  • Write a program in C to asked the user to input positive integers to process count, maximum, minimum, and average or terminate the process with -1. Hint (using while loop).

Questions on arrays and functions

  • Basically, the same as exercise 1, but this time, the function that adds the numbers should be void, and takes a third, pass by reference parameter; then puts the sum in that.
  • Create a calculator that takes a number, a basic math operator (+,-,*,/,^), and a second number all from user input, and have it print the result of the mathematical operation. The mathematical operations should be wrapped inside of functions.
  • Write a C program to find the most occurring element in an array of integers
  • Write a C program to sort a given unsorted array of integers, in the waveform.

Mix Practice Question of C

Practice Examples

Analyze the problem, design an unambiguous and precise algorithm and draw a flowchart for each of the following problems.

  • Compute the cost per square foot of living space for a house, given the dimensions (Length, Width) of the house, the number of stories, the size of the non-living space (garage, closets), the total cost of the house.
  • Given a positive integer number, find whether the number is even or odd.
  • Given a positive integer number, find display if the number is a prime number.
  • Find the slope of a line through two points using formula m =. The values of y1, y2, x1, and x2 are given. If x1 equals x2, the line is vertical and the slope is undefined. If y1 equals y2, the line is horizontal.
  •  Write code to calculate and print the diameter, the circumference, or the area of a circle given the radius. The input is two data items. The first is a character – ‘D’ (for diameter), ‘C’ for circumference, or ‘A’ for the area – to indicate the calculation needed. The next data value is a floating-point number indicating the radius of the particular circle.
  • A company manufactures a line of traffic cones. It requires painting its cones in different colors. The company has hired you to write a program that will compute the surface area of the cone, and the cost of painting it, given its radius, height and the cost per square foot of three different colors of paint. The surface area of the cone can be calculated using a formula.
  • Mother had just filled the cookie jar when the three children went to bed. That night one child woke up, ate half of the cookies and went back to bed. Later, the second child woke up, ate half of the remaining cookies and went back to bed. Still later, the third child woke up, ate half of the remaining cookies, leaving 5 cookies in the jar. How many cookies were in the jar, to begin with? Find a generic solution to this problem.
  • Find and display the sum of numbers from 1 to n where n is input by the user.
  •  Display a line of n stars.
  • Input an integer value and if the input value is equivalent to the value of a British coin, print it out in words. Otherwise, it should print an error message.
    Input Print
    1 One Penny
    2 Two Penny
    5 Five Penny
    10 Ten Pence
    50 Fifty Pence
  • Add a series of numbers input by the user and find the average of these numbers. It is not known in advance how many values will be input.
  • Display the status of the students (Pass or Fail) based on the marks entered by the user. It is not known in advance how many marks will be entered.
  • Find the hypotenuse of the right-angled triangle given its two sides using the Pythagorean Theorem.
  • Write a program that reads the lengths of the sides of a triangle from the user and computes and displays the area of the triangle using Heron’s formula. The Heron’s formula is:
    Area calculation
    Area calculation

Where A, B, C are three sides of a triangle and S is half perimeter and is calculated by

perimeter calculation
perimeter calculation
  • Given the cost of a sales item, calculate the amount of sales tax and total cost of the sales item including tax assuming 7% sales tax.
  •  A person’s weekly pay is Rs. 2500/-. He is scheduled to receive a 3% pay raise next week. Calculate the amount of his new salary.
  • In a video store, a daily rental fee of a video is Rs. 50/-. Customers are charged a late fee of Rs. 20/- per day when the video is returned past the due date. Assume that a customer can return only one video at a time, calculate the amount the customer owes when he/she returns the video.
  • Given a positive integer number N, find display all the prime numbers that is less than or equal to N.
  • A woman is going shopping to buy fifteen items only. Find the total cost of these fifteen items given the price of each item. Also, display the highest price and the lowest price.
  • A perfect number is a positive integer such that the sum of proper divisors equals the number. Thus 28 = 1 + 2 + 4 + 7 + 14 is a perfect number. If the sum of proper divisors is less than the number, it is deficient. If the sum exceeds the number, it is abundant. Write a program that allows the user to enter a positive integer N and then displays all perfect, deficient, and abundant numbers less than or equal to N.






Spread the love
Animesh Chatterjeehttps://techtravelhub.com/
I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on ani01104@gamil.com

Related Articles

Comments

  1. I?¦ve learn some excellent stuff here. Definitely price bookmarking for revisiting. I wonder how much effort you set to create such a wonderful informative website.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Recent Posts

Super Keyword in Java Simplified

Super Keyword Super Keyword in Java Simplified: Java defines a special...

Learn Object Repository in UFT in An Efficient and Fast Manner

Object Repository in UFT The post will cover the following...

Learn What Primary Tools For Test Automation

Primary Tools For Test Automation According to the Gartner report...

EDITOR PICKS


Spread the love