Introduction to C
C Programing is compiled, structural, middle level programing language developed at AT & T’s Bell Laboratories of USA in 1972, designed and written by Dennis Ritchie to redeveloped UNIX operation system. It is improved version of B language which is developed by Ken Thompson.
During the 1980s, C gradually gained popularity. It has become one of the most widely used programming languages. C programming is an excellent language to learn to program for beginners. Many popular software are written in C like Oracle, MySQL, core library of Android, almost every Device Driver. Major parts of WINDOWS, LINUX and Web Browsers are written in C. If you have to closely interact with the hardware without compromising the performance, C is going to be your choice.
A certification in C programming can improve your chances of getting hired for relevant roles. Check out Great Learning academy’s free course on introduction to c programming to upskill yourself and stay ahead of the curve.
Application of C Programing
C is used to development of Operating System (like Windows, Linux), Graphical User Interface, Integrated Development Environment, Browser Design, Compiler Design, Data Base Design, Graphics packages, Word Processor, spreadsheets, mobile and computer game are written in C. C is used in Embedded system, Network devices Specially, C program is used to develop Desktop Application.
History of C Language
- The C Programing language is a structure oriented programing language, developed at Bell Laboratories in 1972 by Dennis Ritchie.
- C programing language features were derived from an earlier language called “B” (Which is upgraded version of Basic Combined Programming Language “BCPL”). BCPL was developed by Martin Richards in 1966.
- C language was invented for implementing UNIX Operating system.
- In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C programming language” and commonly known as K&R C.
- In 1983, The American National Standard Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C’’, was completed late 1988.
Features of C: There are lots of features or characteristics of C language due to which it is still famous enough even after around 50 years of development. It provides:
Features of C Language
- Simple
- General Purpose Programming Language
- Reliability
- Powerful/Robust
- Portability
- Modular/Procedure oriented
- Flexibility
- Structured Programing Language Interactivity
- Modularity
- Efficiency And Effectiveness
Compilation Process in C: The computer understands only machine language. So to make our software to run on a machine, we need a process which can translate this code into a language that computer can understand. This process of translation is called compilation. Or we can say- compilation is the process of translating the code you write into a language that is native to the machine you are targeting. The source code has to pass through set of sub processes.
The instruction written in the c programming language is called as C source code. When we write a C program we are going to store that in the computer memory as a computer file and the file which is containing source code is called as the source file and if the file containing the source code written in the C Programming language, that file is called as C source file. The file which is containing the C source code will be saved with “.C” extension.
The compilation process can be split into four separate stages: which are preprocessing, compilation, Assembly and Linking. The first stage of compilation is called preprocessing. Which takes the source file as input and scan it for all preprocessor directives or simply “#codes”. It generates the preprocessed file with “.i” extension and in this output file, all the macros will be resolved and comments will be taken out. The next stage is compilation which takes preprocessed file as input and converts the high level source code into assembly instruction. Which are specific to the target processor architecture. It generates a file with “.s” extension. The next stage is Assembly which converts the assembly instruction resulted from the compilation and generate object code with “.o” extension (Linuxed based platform) and “.obj” extension (Windows based platform). The O/P consists of actual instructions to be run by the target processor. Till now we have included only header file which contains function declaration. Functions like scanf and printf used in our program still have no definition. They will be define in some library files. Linking is the final stage of compilation. Which takes all the static libraries and object files and generate single executable file with “.out” extension in Linux based platform and “.exe” extension in Windows based platform.
Why to learn C Programming–
- C is a mother of all languages because C is the first complete language.
- C helps you build a strong programming foundation which is ever lasting and which help you all through your life.
- The object oriented programming methods present in C++, C# and Java provides huge advantage for programmers but the basic programming elements like looping, variable declaration, logical and arithmetic operation are almost similar in C. So learning C definitely gives you an extra edge before jumping on learning C++, C#, Java.
- The programs written in C are very efficient. Its performance and speed of execution is unique. Even todays device drivers are also written in C.
- C is basically a middle level language. It is an interface between assembly language and high level languages. C can interface with both of them. When you know C you can get introduced to the computer architecture, you can understand memory management, CPU cache, you can know port programming, as well as you can also have Database programming because of files in C are very strong.
- C programs can be easily embedded in other languages which is very big asset of C.
- Most 3D Gaming framework like DirectX are built in C programming language. Because for any Game user experience that is speed of execution is very important and C suits best for its because it’s speed reliability and performance.
- Using C we can directly access hardware. C is easy to learn and understand.
- C is efficient, powerful, portable and flexible. Flexible because of its memory management. Portable because it can take the same source code, compiled and execute it to get the object which is same in all machine.
- C being a structure language. Once you learn how to use a structure programming language, it becomes a programming language which will help you lifetime.
- If you learn new languages like C++, Java, Python, once you know C porting to these language is so easy.
Environment Setup/Installation Process– If you want to set up your environment for C programming language, you need the following two software tools available on your computer, (a) Text Editor and (b) The C Compiler but now to start learning C programming, you can only have to install the C compiler in your system, and nowadays C and C++ both compilers come as a single integrated package, which serves the purpose of C and C++ both program development.
Installation on UNIX/Linux–
If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line –
$ gcc -v |
If you have GNU compiler installed on your machine, then it should print a message as follows –
Using built-in specs.Target: i386-redhat-linuxConfigured with: ../configure –prefix=/usr …….Thread model: posixgcc version 4.1.2 20080704 (Red Hat 4.1.2-46) |
If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/
This tutorial has been written based on Linux and all the given examples have been compiled on the Cent OS flavor of the Linux system.
Installation on Mac OS
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple’s web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++.
Xcode is currently available at developer.apple.com/technologies/tools/.
Installation on Windows
To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe.
While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names.
After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.
List of C Compilers for Windows OS– Since there are various compilers available into the online market, here are the lists of some of the frequently used ones:
List of C Compilers for Windows OS
- CCS C Compiler
- Turbo C
- Minimalist GNU for Windows (MinGW)
- Portable C Compiler
- Clang C++
- Digital Mars C++ Compiler
- Intel C++
- IBM C++
- Visual C++ : Express Edition
- Oracle C++
All of these above compilers for C are free to download, but there are some other paid C compilers also available, or programmers can get it for trial version:
- Embarcadero C++
- Edison Design Group C++
- Green Hills C++
- HP C++ for Unix
- Intel C++ for Windows, Linux, and some embedded systems.
- Microsoft C++
- Paradigm C++
The following are IDE’s (Integrated Development Environments) that will automatically download everything you need to begin programming and running the C-Programming language.
Install Dev C++ – Install Dev C++ from sourceforge.com. Dev-C++ is a integrated development environment (IDE) for programming in C and C++. It is bundled with, the MinGW or TDM-GCC 64bit port of the GCC as its compiler.
Install Code::Blocks -Install codeblocks-17.12mingw-setup.exe . Codeblocks is a cross-platform IDE built around wxWidgets, designed to be extensible and configurable. Runs on Windows and Linux. If the link to the installation file is not working, go to codeblocks.org and install the program.
Install Cygwin- Okay, so this method does not use an IDE like the previous methods, but it’s still another way that you can get a C-Program to run on your Windows Operating System through command prompt.
First install GNU Compiler Collection or GCC for short, on Microsoft Windows. I will show you different ways to install GCC which was originally written as the compiler for the GNU operating system (A Unix like Operating System).
Cygwin (a software interface that has the look and feel of a Unix environment, but is run within the Windows operating system was created). Cygwin allows for integration between Windows applications, Unix-like applications and data.
The install steps are:
- Install Cygwin, which gives us a Unix-like environment running on Windows.
- Install a set of Cygwin packages required for building GCC.
- From within Cygwin, download the GCC source code, build and install it.
- Test the new GCC compiler in C++14 mode using the -std=c++14 option.
C Program structure–
Documentation Section |
Link Section |
Definition Section |
Global declaration section |
Main(){Declaration SectionExecution Section} |
Function 1 ………. |
UserFunction n |
Documentation Section– The first section is documentation section. It consists of comments lines which are not compiled by compiler. Comments are added in a program to increase it’s readability and understandability. They are written by two reverse slashes “//” before the statements. This is use to write single line comment. A multiline comment is written by typing a reverse slash and a star “/*” followed by the comment lines which is followed by the star and reverse slash “*/”.
Comments are specify the name of program, author and other details related to the program. It is used for future reference.
Link Section – All the library file that are included in the program are mention in the section. The compiler is informed about the library files to be linked with the program. This process is called as Linking. All the statements is starts with the “#” include text belong to the link section. For example the statement “#include<stdio.h>” links library file “stdio” to the program.
Definition Section – All the symbolic constants that are to be used in the program are defined here. All statements are starts with the “#” define text belong to the definition section.
#define pi=3.14;#define true=1;#define false=0; |
Global Declaration Section– All the variables which are used is more than one function are called as Global variables. And they should be declare before they are used anywhere in the program in the section. All the user defined functions are also declare here.
//Globall declaration Sectionint green;//user defined function |
function1()
{ green=0; }
function2()
{ green=1; }
Here “green” is global variable. |
Main function definition section – Every c program must have one main function. All the statements in the main section must have must appear between the opening and closing braces. This section has two parts. First part is declaration part. As every c variable must be declare before its use. Therefore all the variable to be used in the main section are declare here in declaration section.
Main(){ //Declaration int principle, rate, time, interest;//Executionprinciple=20000;rate= 15;time=7;interest=(principle*time*rate)/100; } |
User defined function definition section – All the user defined functions are calling by the main function. All the section except the main section may not be present in the program if not required but every program must have one main section.
C Basic Syntax –
Token in C – A program consists various tokens. Token could be Keyword, Identifier, Constant, string or any symbol.
Example:
#inclde<stdio.h>int main(){Printf(“ Hello World… \n”);} |
Here every word of this program are called token.
Semicolon : This is statement terminator. Each statement must be terminate with “;”.
Comments: It is used to increase the readability of the program. This is two type 1)one line comment, 2)Multiple line comment.
//Think Green and increase Green./*Let’s move to the sky….…….to protect Earth. */ |
Identifier: Identifier is name used to identify the variable, functions and user defined items. Identifier is specific form of token. An identifier starts with a letter A to Z, a to z, or an “_” followed by zero or more letters, underscores and digits (0 to 9). C does not allow punctuation characters such as @,$, and % within identifiers.
C is case-sensitive programing language. Thus Manpower and manpower are two different identifiers in C.
Keyword: Keywords are one kind of token. Reserved word of language is called keyword. These keyword can’t be used as identifiers. We can use within it but not alone. There are 33 keywords in C language.
auto | else | long | switch | double |
break | enum | resister | typedef | |
case | extern | return | union | |
char | float | short | unsigned | |
const | for | signed | void | |
continue | goto | sizeof | volatile | |
default | If | static | While | |
do | int | struct | packed |
Whitespace : A line containing only whitespace or comments is called blank line. C compiler totally ignore the blank line. Whitespace is the term used in C to describe blank lines, tabs, newline character and comments. Whitespace separate one element to another, in a statement so that compiler can recognize. int var_a; If whitespace required we have to give at least one.
Syntax to write main() or a program in c:
#include<stdio.h>int main(){ //Statements… return(0);} |
Syntax of variable definition or declarations:
datatype variable-name;Example: int a; |
Some Escape Sequences;
\a : bell sound\b : backspace \f : form feed\n : new line\t : tab\0 : null character\v : vertical tab |
Input Output functions:
- Character input
Variable-name=getchar();Example: b=getchar(); |
- Character output
putchar(var-name);example-putchar(b); |
Formatted Input-Output function syntaxes:
Scanf(“format specifier”,&variable-name);Example- scanf(“%d”,&a);Printf(“format specifier”,variable-name);Example: printf(“%d”,a); |
Some format Specifier:
%d,i => decimal no%o => octal%f => float%c => single character%u => unsinged decimal no%x,X => hexadecimal |
Conditional statements:
- If statement
if(condition){ //statements…} |
- If-else statements:
if(condition){ //statement 1}else{ //statement 2} |
- Nested if-else:
if(condition 1){ //statement 1}else if(condition 2){ //statement 2}else//statement 3 |
- Switch case statement
Switch(choice-case-variable){Case1: //statement 1 break;Case2: //statement 2 Break;Default: //statement 3 |
- Conditional operator/Ternary operator
Variable = (condition) ? execute if true : execute if false;Example- a = (b>c) ? b : c; |
Loops Syntaxes:
- While loop:
while(expressions){ //statements} |
- Do-While Loop:
do{ //statements} while(expression); |
- For Loop:
For(exp1;exp2;exp3){ //statements} |
Datatypes: Datatype is a type of data which is used in the program. In other word, we can say that it is used to declare a variable. Datatype specify how we entered data in our program and what type of data we entered. There are two types of datatype: a) primary datatype, b) secondary datatype
- Primary or Basic Datatype- i)int, ii) char, iii)float, iv) double
- Secondary or Derived Datatype– i) Array, ii) Pointer, iii) Structure, iv) Union
Modifiers: Modifiers are used as a prefix to the datatype to redefined the size and range of the datatype.
Systax: modifier datatype variable-name;
There are two types of modifiers: i) size modifier (short, long, longlong), ii) sign modifier( signed, unsigned)
Short modifier– We can use short modifier only with the “int” datatype. As a explain earlier int take different memory space like 2 bytes, 4 bytes or 8 bytes; it depends on the computer architecture and compiler. If you want to allocate fixed memory space for the int then you can used short modifier. So size of the short modifier is two bytes. So, If you want to store small integer value then you can use this modifier with the int data type.
Short int a;
Long and longlong modifier: You can use these two modifiers when you want to increase the size of the current datatype you can use these long modifier with int and double. We can’t use these with character or float. The size of the long modifier is 4 bytes or 8 bytes; it depends on the computer architechture and compiler.
long int a;
long double b;
we can use longlong only with the integer. The size of longlong is 8 bytes.
Longlong int a;
Unsigned modifier : We can use this unsigned modifier with the int and character datatype. This keyword can be used for those variable which can take only value which are “0” and “positive value”, it don’t take negative value.
unsigned int a;
unsigned char b;
If we didn’t mention any
C Data Types– Data Type is used to declare or define a variable. It specifies the data storage format for the variable. In the declaration of every variable, it is mandatory to specify it’s data type. There are three types of Data Type:
- Primary or Primitive Data Type
- char
- int
- float
- double
- void
- User Defined Data Type
- typedef
- enumerated
- Derived Data Type
- Array
- structure
- pointer
- Union
Data Type | Size(Byte) | Range of Value | Format Specifier |
Signed char | 1 | -128 to 127 | %c |
Signed int | 2 | -32768 to 32767 | %d, %i |
float | 4 | 1.2E-38 to 3.4E+38 | %f |
double | 8 | 2.3E-308 to 1.7E+308 | %lf |
unsigned char | 1 | 0 to 255 | %u |
unsigned int | 2 | 0 to 65,535 or 0 to 4,294,967,295 | %llu |
signed short int | 1 | -128 to 127 | |
unsigned short int | 1 | 0 to 255 | |
signed long int | 4 | -2147483648 to 21471483647 | %ld, %li |
Unsigned long int | 4 | 0 to 4294967295 | %lu |
Long double | 10 | 3.4E-4932 to 1.1E+4932 | %Lf |
For example,
int greenWorld; |
Here, greenWorld is a int (integer type) variable where we can store only integer value like 2,4. We can’t store here 2.6(use float data type to store it).
C Variables – An variable is an entity that does change or vary in respect of time. In programing we have to store results of calculations, and it is stored in the computer memory. The computer memory consisting of a lots of small memory cells. And each memory cell has it’s own address. Variable names are the names given to the memory locations. We don’t need to worry about at which location of the memory your value is stored. Our task is just to provide the name and internally it will point some memory location.
9 | |||
As shown in figure, 12345 is the address of the memory cell which contain a constant 9. To make the usage of memory cell easy we give the memory cell a name as greenWorld. So 9 is stored in the memory cell named greenWorld. Here 10 is constant and the name of the memory cell is called as variable name. This variable can contain other value at another time.
If you assign some value to a variable at the time of declaration, then it is called initialization.
int greenWorld = 9; |
Constant: As the name suggests constant is something that never change. Or we can say, Constant is an entity that refers to fixed values and it can’t be modified. We can define constant in our code by using #define or using const keyword.
Define constant using #define:
Syntax for #define: #define NAME(macro) value
Job of preprocessor (not compilar) to replace name with value. The preprocessor does the job of replacing the header files with their actual content as example #include<stdio.h> is going to get replaced by preprocessor. The “NAME” is also going to get replaced by this “value” available over here.
#include <stdio.h>#define PI 3.14159int main(){ printf(“%.3f”, PI); return 0;} |
Here we define a “PI” with 3.14159 where “PI” is the NAME and “3.14159” is value. We are simply going to print this “PI” instead of using “3.14159” constant and printed up to 3 decimal points. The output will be “3.141”.
What should or should not we do in the time of define the constant:
- Please don’t add semicolon at the end.
- Choosing capital letter for NAME is good practice.
#include<stdio.h>#define value 60int main(){ int value = 51; (int value 60=51;) printf(“%d”,value);return 0;} |
Here you can see we are not use the capital letter for “NAME”. So, what is the disadvantages you may get; It is possible that we declare the variable with the same name assign to it the value 51, and if we simply print that value. We got an error out of this because our macro is also with same name. Now the preprocessors does its job and replace this value with 60 wherever it finds its out. Here also the variable value is replace with 60. This is the disadvantage.
- Whatever inside double quotes “ “ won’t get replaced.
- We can use macros like functions.
#include<stdio.h>#define add(x, y) x+yint main(){ printf(“addition of two numbers: %d”, add(4,3)); return 0;} |
We use the add(x,y) just like a function and after that I perform some operation which is x+y. I want to perform the addition of two numbers 4 and 3. We simply call the macro, this is going to get replace with this x+y which is nothing but 4+3, this gives us the output as 7.
- We can use multiple lines using “\”
#include<stdio.h>#define greater(x,y) if (x>y)\ printf(“%d is grater than %d”,x,y); else\ printf(“%d is lesser than %d”,x,y);int main(){ greater(5,6); return 0;} |
- First expansion then evaluation.
#include<stdio.h>#define add(x,y) x+yint main(){ printf(“result of expression a*b+c is:”, 5* add(4,3)); return 0;} |
Here 5 is multiplied with macro, first the replacement is going to get done. First expansion then evaluation. Here the expansion simply means that this macro is expanded to x+y and it is getting replaced over here which is nothing but 5*4+3 and then the whole expression is evaluated. Result of 5*4+3, according to the BODMAS rule 5*4 is evaluated first which gives us 20 then it will add with 3, the result will 23.
- Some predefined macros like __DATE__,__TIME__ can print current date and time .
#include<stdio.h>int main(){ printf(“Date %s\n”, __DATE__); printf(“Time %s\n”, __TIME__); return 0;} |
Define Constant using const: You would be able to use const keyword in front of a variable. For example we can define a variable like “int var” by simply putting const keyword in front of that variable, we won’t be change its value anywhere in the code. Suppose for example we want to assign a different value to a variable that we want be able to do that because when we defined it as a constant you won’t be able to changed its value. Constant simply means that this value whatever its being assigned to a variable is permanent.
Syntax: const data_type variable_name;
#include<stdio.h>int main(){ int var=73; var=62; printf(“%d”,var); return 0;} |
Here we defined a variable and assigned it a value equals to 73 and we simply going to print this value with the help of “printf” function. We got 73 as the output. Now we are assign different value to this variable. Then if we print the value of “var” we will get 62. So we would be able to assign any number of time values to it as whenever we want in our code. It is not necessary that once we initialize with this value we won’t be able to assign any different value latter in our code. Now if we put “const” keyword in front of this variable then let’s see what will happen?
#include<stdio.h>int main(){ const int var=73; var=62; printf(“%d”,var); return 0;} |
We will get an error (assignment of read only variable ‘var’). Because we are trying to assign a different value to it which is after the initialization step. We are already initialize it the value is equal to the 73 and now this becomes a constant. We won’t be able to change its value further in the code. And that is why this kind of error is produced. We can also declare this variable as global and no function would be able to assign the value to it. That is the functionality of the const variable.
Type of constant:
- Primary Constant
- Integer Constant
- Real constant
- Character Constant
- Secondary Constant
- Array
- String
- Pointer
- Union
- Structure
- Enumerator
Storage classes: A storage class defines the scope and life time of variables and functions.
Types of storage classes:
- Auto
- Register
- Static
- Extern
Int x=5; |
From this declaration statement we can easily find three characteristics or property of variable:
- Name of the variable
- Size of the memory block
- Data type of the content
There are more properties of variable:
- Default Value
- Storage
- Scope
- Life
If we don’t mention storage class in declaration statement then it will consider as “auto” storage class.
Storage class | Keyword | Default Value | Storage | Scope | Life |
Automatic | auto | Garbage | RAM | Limited to the block in which it is declared | Till the execution of the block in which it is declared |
Register | resister | Garbage | register | same | same |
static | static | Zero(0) | RAM | same | Till the end of program |
External | extern | Zero(0) | RAM | Global | Same |
Operators: Operator is a symbol that used to perform mathematical or logical operation on variables and values.
Type of operator according their priority(High to Low):
- Unary Operators
- Arithmetic Operators
- Bitwise Operators
- Relational Operators
- Logical Operators
- Conditional Operators
Unary Operator- To work this operator one operads is needed. There are five type of unary operator: +(positive sign), -(negative sign), ++(increment operator), –(decrement operator),sizeof() operator.
use of post increment operator:
main(){ int x=3; clrscr(); x++; //x=x+1 printf(“%d”,x); getch();} O/P is =4 |
Use of pre increment:
main(){ int x=3; clrscr(); x++; //x=x+1 ++x; printf(“%d”,x); getch();}O/P is =4 |
Sizeof() operator: It tells the size of data type or variable:
Main(){ int x; clrscr(); x=sizeof(float); printf(“%d”,x); getch();} |
main(){ int x; float k; clrscr(); x=sizeof(y); printf(“%d”,x); getch();} |
Arithmetic Operator: *(multiply), /(devide), %(modulo) [High Priority]
+(addition), -(subtraction) [Less Priority]
Here no BODMAS rule is applied. If there are more than one arithmetic operators in a expression, the priority of these are same but they are solved from left to right. So, the associativity rule of arithmetic operators is left to right.
Bitwise Operator–
Bitwise AND | & |
Bitwise OR | | |
Bitwise XOR | ^ |
Bitwise NOT | ~ |
Right Shift | >> |
Left Shift | << |
Relational Operator– <(less than), >(Greater than), <=(Less than equal to), >=(greater than equal to)
“==”, “!=”
Relational operator always yields result either 0 or 1. Every non zero value is “True” and Zero is “False”.
Main(){ int x; clrscr(); x=3>4; printf(“%d”,x); getch();} O/P is= 0 |
Logical Operators: ! (NOT Operator)
&& (AND Operator)
|| (OR Operator)
NOT operator is a unary operator because its required one operand to work.
main(){ Int x=5,y; clrscr(); y=!x>4; printf(“%d”,y); getch();} |
main(){ int x=5,y; clrscr(); y=x>4 && x<10; Print(“%d”,y); getch();} |
Conditional Operator: It is also called Ternary Operator.
Syntax: Condition ? statement : statement;
Main(){ int x; clrscr(); printf(“Enter a number”); scanf(“%d”,&x); x>0 ? printf(“positive”) : printf(“non positive”); getch();} |
Loops: Any repeated task more than one time is called Loop. Loop is also called Iterative control Instruction.There are three type of loop:
- While Loop
- Do-While Loop
- For Loop
main(){ int i=1; while(i<5) { print(“Green Way”); i++; } getch();} |
main(){ int i=1; do { printf(“Green Way”); i++; } while(i<5); getch();} |
main(){ int i; for(i=1; i<5;i++) { printf(“Green Way”); } while (i<5); getch ();} |
Functions: Function is basically a set of statements that takes inputs, perform some computation and produces output.
Syntax: Return_type function name (set_of_inputs);
Return_type indicates the type of output returned by the function, function_name indicates the name of the function and the set_of_input indicates inputs provided to the function. It is not necessary to provide the inputs to the function. Without inputs it can performs some computation and it can return some output as well. Return_type indicates the type of the output and the output could be integer type, it could be character type or it could be float type and so on.
There are two important reasons of why we are using function:
- Reusability– Once the function is defined, it can be reused over and over again. You can reuse the function again and again in your code without define its functionality.
- Abstraction- If you are just using the function in your program then you don’t have to worry about how it works inside. Example: scanf function
You can reuse scanf function multiple number of times without defines its functionality again and again in your code and also it provides the level of abstraction.
#include <stdio.h>int areaOfRect ( int length, int breadth);{ int area; area = length * breadth; return area ;int main(){ int l=10, b=5; int area = areaOfRect(l, b); printf(“%d\n”, area);} |
We all know that, when we declare a variable, we declare its properties to the compiler.
For example: int var;
Here var is the name of variable and int is type of the variable. Similarly, function declaration (also called function prototype) means declaring the properties of the function to the compiler.
Example: int func (int,char);
Here name of the function is func, return type of the function is int, no of parameters is 2, type of parameter 1 is int and type of parameter 2. It is not necessary to put the name of the parameters in function prototype.
Example: int func (int var1, char var2);
Here var1 and var2 is the name of the parameter which is not necessary to mention. It is important to mention the name of the parameter in the function definition but it is not important to mention the name of the parameters in function declaration.
#include <stdio.h>char func();int main(){ char c = func(); printf(“character is: %c”, c);}char func(){ return ‘a’;} |
It is not necessary to declare the function before using it but is preferred to declare the function before using it.
In C language, function is divided into two parts:
- Library Function (printf, scanf etc.)
- User defined Function
Calling of function is two types:
- Call by value
- Call by reference
We can write program using function of four types:
No Argument and No Return value |
No Argument and a Return value |
Argument and No Return value |
Argument and Return value |
Function Definition: Function definition consists of block of code which is capable of performing some specific task.
int add ( int a, int b ){ int sum; sum = a+b; return sum;} |
Here is the block of code which can perform the addition between two numbers available inside these two variable a and b.
Structure in C Program- Structure is user defined data type that can be used to group elements of different types into single type or we can say it is a collection of similar or different data type.
You can store atomic value or single value by use of primitive data types like char, int, float, double etc. You can’t store multiple value into a single variable, to store multiple data into a single variable structure is needed.
Suppose we have some mobiles and there are different specifications of these mobiles like:
Mobile 1 | |
Brand | Samsung |
RAM | 8 |
Battery | 4000 |
Camera | 48 |
Display | 15.8 |
Mobile 2 | |
Brand | MI |
RAM | 4 |
Battery | 4000 |
Camera | 32 |
Display | 15.7 |
If I want to store all these information somewhere, we need to create different variables for different types to store ‘Brand’ we need string variable; to store ‘RAM’, ‘Battery’ and ‘Camera’ we need integer variable; to store ‘Display’ value we need float variable.
But it is not good idea to store all these information in separate variable. Suppose we have 1000 mobiles, then storing all the information in different variables is time consuming as well as memory consuming. Therefore this is not good idea. Array is not also good option because Array has the capability to store more than one elements but they all must be of same types. But our requirement is to store data of different types. Structure is one stop solution. So we have a structure which is giving us the power to define our own type that can be used to group elements of different types into a single type.
Defining a structure –
Struct mobile{string Brand;int RAM,Battery,Camera;float Display; //member variable declaration here }; Void main() { ………… } |
This is global definition of structure. That means we can use ‘mobile’ data type in anywhere within the program. Here mobile is data type. No memory is consumed for definition of structure because we don’t create the variable using these data type. We can define structure within the function or outside the function.
Void main(){ Struct mobile{string Brand;int RAM,Battery,Camera;float Display; //member variable declaration here };……………………….} |
This is local definition of structure. We can use ‘date’ function within this main function.
How to declare the variable?
Struct mobile{string Brand;int RAM,Battery,Camera;float Display; //member variable declaration here }; Void main() { struct mobile m1;……………………………… } |
Here m1 is local variable, we can access this variable within main function.
Struct mobile{string Brand;int RAM,Battery,Camera;float Display; //member variable declaration here }; struct mobile m2; Void main() { ………… } |
Here m2 is globall variable.
Struct mobile{string Brand;int RAM,Battery,Camera;float Display; //member variable declaration here }m3; Void main() { ………… } |
m3 is also global variable, here d1,d2,d3 contains memory according their initialization.
How to initialize the structure?
Struct mobile{string Brand;int RAM,Battery,Camera;float Display; //member variable declaration here }; Void main() { struct mobile m1={“Samsung”,8,4000,48,15.8}; ………… } |
We can also initialize like this:
Struct mobile{string Brand;int RAM,Battery,Camera;float Display; //member variable declaration here }; Void main() { struct mobile m1; m1.Brand=”Samsung”; m1.RAM=8; m1.Battery=4000; m1.Camera=48; m1.Display=15.8; ………… } |
User Input–
Struct mobile{string Brand;int RAM,Battery,Camera;float Display; //member variable declaration here }; Void main() { struct mobile m1; printf(“Enter mobile1 specification:”); scanf(“%s%d%d%d%f”,&m1.Brand,&m1.RAM,&m1.Battery,&m1.Camera,&m1.Display);printf(“Mobile1 specification: %s%d%d%d%f”,m1.Brand,m1.RAM,m1.Battery,m1.Camera,m1.Display); getch();………… } |
Whether you are looking to develop your skills as a software developer or you just started programming because of your interest in it, then C is the programming language that you can start learning first. Though there are various languages available in the market to learn, but C programming language has its benefits. C programming language can help you develop your skills throughout your professional career as it will work as a stepping stone towards learning other programming languages. From microcontrollers to the operating system, everything is written in the C programming language because of its flexibility and versatility.
What is C Programming Language?
C is a Procedural Programming Language that was developed between 1969 and 1973 by Dennis Ritchie. The main reason for its development is to write an operating system. There are various features of the C language which make it beneficial to learn such as its low-level access to the storage, clean style and syntax for programming, and the simple keywords available to use. These features make the use of C programming very efficient for system programming or the development of Compilers.
There are several benefits that you can get from learning the C language. And the most important benefit of all is that the language is recognized worldwide and used for the development of applications, software, and operating systems. Learning C is very useful when we look from a career perspective.
Some Useful Features of C Programming Language:
- Fast Execution: C language is fast in execution as compared to other programming languages. It doesn’t have additional overheads such as memory leak prevention or garbage collection, etc. So, the execution time it takes is very less.
- Middle-level Language: C language provides a layer between low-level and high-level programming languages and works as a middle-level programming language. C language can be used to write operating systems and for application development. As it is a middle-level language, it reduces the complexity of high-level language and the gap between low-level and high-level programming languages.
- Compatibility: C language is compatible with all operating systems. And any operating system can be used to write C programs. Its compatibility enhances its use on various platforms.
- Support of Libraries: C provides a little number of libraries as compared to other programming languages. As it provides only a few libraries, learning becomes easy. Other programming languages have a large number of libraries and it is difficult to learn all the libraries, so C programming is easy to learn as it only has a little number of libraries.
- Inbuilt functions and operators: C programming language provides several inbuilt functions and operators that can be used in our programs. These functions are very useful in solving all kinds of complex problems in programming.
What are the Applications of the C programming language?
There are various applications of the C programming language. Out of all, there are some important and useful applications we are going to discuss in this section.
We will see the applications of C programming language across industries and for individual purposes:
- To develop system applications
- For the development of desktop applications
- To develop compilers
- C is also useful in embedded systems
- C language is very useful for the development of browser applications and their extensions
- To develop databases such as MySQL
- For the development of Operating Systems
- For Game Development
- The majority of Adobe applications are developed by C language
Advantages of learning C programming language
Learning C programming as your first programming language is very helpful for anyone. It will create a base to learn other programming languages too. Let us see some advantages of Learning the C programming language below: It works as a stepping stone to learn other programming languages: C programming language will help you start your programmer career and it will help you to learn other programming languages easily. When you will start learning C, you will develop the understanding of working behind the programming languages and it will help you a lot in learning other programming languages too.
It helps to understand how a computer works: C programming language can be used to develop operating systems and it will help you to understand how a computer works, its architectures, and other concepts of programming. C programming language lets you write complex programs that will help you learn how to write efficient code than other programming languages.
Learning C helps you to interface with other programming languages: The other programming languages such as Python, Java, JavaScript, and C++ can be interfaced with the C programming language easily as they are high-level languages. So it becomes easy to interface other programming languages with C. The program written in the C programming language can be executed on another computer which makes it very useful.
Learning C is easier than other languages: Various languages are related to C programming and learning the C language will help you to easily learn other programming languages. Some languages have the same syntax, operators, data types, and functions as of C language.
It helps to work on open-source projects: Aside from other applications of the C programming language, it can be used for open-source projects. Working on open-source projects will help you enhance your knowledge of the C language. There are many open-source projects based on the C programming language in which you can make your contribution that will help other programmers to learn worldwide.
C programming language is efficient for learning: C programming language provides 32 keywords, built-in functions, and operators which are very useful in writing the code. Also, the C programming language contains pre-built libraries that can be used in our programming and these libraries save our time and code complexity. These attributes contribute to making C more efficient and simple to start programming.
Career Options in C programming:
- Junior Programmer
- Senior Programmer
- Software Developer
- Quality Analyst
- Game Programmer
- Software Developer Engineer
- C/C++ Analyst
- Programming Architect
How to start learning the C programming language for free:
- Get Enrolled in our Learn C Programming Online Free Course offered by Great Learning Academy: Great Learning Academy provides C programming courses for free. You can enroll in that course and start learning. The course will cover all the concepts of the C programming language. The motive of the course is to help you understand the concepts of the C programming language.
- Enhance your knowledge by Self Study: Self Study is the best way to learn anything. And to increase your knowledge in C programming, you should start learning it by yourself. You can find resources online on the internet and also you can create notes from the Great Learning Course on C programming. It will help you learn more about C programming.
- Implement your learnings: To learn something effectively, it is vital to apply the concepts practically. The concepts that you have learned in the course, you need to apply practically to get hands-on experience with this language. It is the best way to learn the working of C programming language.
- Practice your skills in programming: To learn programming effectively and efficiently, you need to practice your coding skills. There are many ways that you can practice your skills such as by working on open-source projects, by working on your projects and creating interesting applications which are easy to develop. Another way to practice in C programming is to help others who are facing difficulty in C programming. You can submit your solutions to problems in C language on the internet.
It is recommended that, after you have learned all the concepts in C programming, you have to take further steps in your learnings. You can choose another language that seems similar to C to take your learnings to the next level. C programming language works as a base programming language for various languages such as C++, Java, etc. It will help you to develop your career in programming.
Learning C programming is easy because all the basic commands that you write in your code are in English. Great Learning Provides a free live course of C programming language that is also beneficial for your exams if you are a student of Computer Science.
If you are interested in learning the C programming language then you can start with our free course offered by Great Learning Academy Computer Programing . After the successful enrolment in this course, you will get notifications of the classes that will be held online. The benefit of enrolling in this course is that this is a live course in which the tutor will teach you to live and you can ask any of your doubts or questions at that time. Also, you will get the recording of the missed classes and practice questions. Overall it will help you develop your career in Programming.