COMPUTER LANGUGES |PROGRAMING LANGUAGES | INTRODUCTION TO C LANGUAGE | C LANGUAGE FROM SCRATCH !!! | BCA PPA NOTES |

 

PROGRAMMING LANGUAGE :-

A programming language is a formal language that specifies a set of instructions that can be used to produce various kinds of output. Programming languages generally consist of instructions for a computer. Programming languages can be used to create programs that implement specific algorithms. A programming language is an artificial language that can be used to instruct a computer to do a particular task. To be considered a general programming language, it must be computationally complete, or Turing-Complete. It is nevertheless common to regard some languages that are not computationally complete, like database query languages and other domain-specific languages as programming languages as well.



Execution of program :- 

Computers are electronic device know only one language that is machine language. It contains only zeros and ones.so if you need to instruct a computer you need to give instructions in binary form that is ones and zeros. For a human it is very difficult to talk in this language. So we create a software(software or executable file always contain binary information or instructions to computer) which will convert our known language( high level language) into machine level language. thus computer can work. This software is known as compilers. Compiler is a software which converts high level language into machine level language. And this process is known as compilation. 

COMPILER :- A compiler is a software program that transforms high-level source code that is written by a developer in a high-level programming language into a low level object code (binary code) in machine language, which can be understood by the processor. The process of converting high-level programming into machine language is known as compilation. The processor executes object code, which indicates when binary high and low signals are required in the arithmetic logic unit of the processor.


ASSEMBLER :- An assembler is a type of computer program that interprets software programs written in assembly language into machine language, code and instructions that can be executed by a computer. An assembler enables software and application developers to access, operate and manage a computer’s hardware architecture and components .An assembler is sometimes referred to as the compiler of assembly language. It also provides the services of an interpreter.


INTERPRETER :- An interpreter is a computer program that is used to directly execute program instructions written using one of the many high-level programming languages. The interpreter transforms the high-level program into an intermediate language that it then executes, or it could parse the high-level source code and then performs the commands directly, which is done line by line or statement by statement.


Structure programming : – 

Structured programming is a logical programming method that is considered a precursor to object-oriented programming (OOP). Structured programming facilitates program understanding and modification and has a top-down design approach, where a system is divided into compositional subsystems. 

Modular Programming : – 

Modular programming is the process of subdividing a computer program into separate sub-programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system. Similar functions are grouped in the same unit of programming code and separate functions are developed as separate units of code so that the code can be reused by other applications. Object oriented programming (OOP) is compatible with the modular programming concept to a large extent. Modular programming enables multiple programmers to divide up the work and debug pieces of the program independently.

COMPUTER LANGUAGES :-

They are of three types –

1.MACHINE LANGUAGE (low level language)

2.ASSEMBLY LANGUAGE (middle level language)

3.USER ORIENTED LANGUAGE (higher level language)



Machine language depends on the hard ware and comprises of 0 and 1 .This is tough to write as one must know the internal structure of the computer. At the same time assembly language makes use of English like words and symbols. With the help of special programs called Assembler, assembly language is converted to machine oriented language. Here also a programmer faces practical difficulties. To over come this user depends on Higher level languages, which are far easier to learn and use. To write programs in higher level language, programmer need not know the characteristics of a computer. Here he uses English alphabets, numerals and some special characters. Some of the Higher level languages are FORTRAN, BASIC, COBOL, PASCAL, C, C++, ADA etc. We use C to write programs. Note that Higher level languages can not directly be followed by a computer. It requires the help of certain soft wares to convert it into machine coded instructions. These soft wares are called Compiler, Interpreter, and Assembler. The major difference between a compiler and an interpreter is that compiler compiles the user’s program into machine coded by reading the whole program at a stretch where as Interpreter translates the program by reading it line by line.


PROGRAMMING METHODOLOGY :

STEPS :-

 1. Analyze the problem .  
 2. Identify the variables involved .
 3. Design the solution .
 4. Write the program . 
 5. Enter it into a computer .
 6. Compile the program and correct errors .
 7. Correct the logical errors if any .
 8. Test the program with data .
 9. Document the program .

ALGORITHM : Step by step procedure for solving a problem is called algorithm.

EXAMPLE :- To make a coffee .

Step1: Take proper quantity of water in a cooking pan 
Step2: Place the pan on a gas stow and light it 
Step3: Add Coffee powder when it boils 
Step4: Put out the light and add sufficient quantity of sugar and milk 
Step5: Pour into cup and have it.

To add two numbers .

Step1: Input the numbers as x, y 
Step2: sum=x + y 
Step3: print sum .

To multiply two numbers .

Step1: Input the numbers as a and b 
Step2: find the product a x b 
Step3: Print the result .

For a better understanding of an algorithm, it is represented pictorially.

FLOWCHART : The pictorial representation of an algorithm is called as flowchart .



In the above examples execution is done one after another and straight forward. But such straight forward problems occur very rarely. Some times we have to depend on decision making at certain stage in a normal flow of execution. This is done by testing a condition and appropriate path of flow is selected. 

For example :  (consider the following problem)

To find the highest of three numbers .

ALGORITHM :

Step 1: read the numbers as x ,y and z 
Step 2: compare x and y 
Step 3: if x > y then compare x with z and find the greater 
Step 4: Otherwise compare y with z and find the greater .

FLOWCHART :

C FUNDAMENTALS :-

A Brief History Of C :

C evolved from a language called B, written by Ken Thompson at Bell Labs in 1970. Ken used B to write one of the first implementations of UNIX. B in turn was a descendant of the language BCPL (developed at Cambridge (UK) in 1967), with most of its instructions removed. So many instructions were removed in going from BCPL to B, that Dennis Ritchie of Bell Labs put some back in (in 1972), and called the language C. The famous book The C Programming Language was written by Kernighan and Ritchie in 1978, and was the definitive reference book on C for almost a decade. The original C was still too limiting, and not standardized, and so in 1983 an ANSI committee was established to formalise the language definition. It has taken until now (ten years later) for the ANSI ( American National Standard Institute) standard to become well accepted and almost universally supported by compilers .

Structure of C :

Every C program consists of one or more modules called functions. One of these functions is called main. The program begins by executing main function and access other functions, if any. Functions are written after or before main function separately. A function has 

(1) heading which consists of name with list of arguments ( optional ) enclosed in parenthesis, 

(2) argument declaration (if any) and 

(3) compound statement enclosed in two braces { } such that each statement ends with a semicolon. 

Comments, which are not executable statement, of necessary can be placed in between /* and */. 

Example :-

/* program to find the area pf a circle */ 

#include 

 main( ) 

float r, a; 

printf(“radius”);

 scanf(“%f”, &r); 

a=3.145*r*r; 

printf(“area of circle=%f”, area); 

ENVIRONMENT FOR C PROGRAMING :

STEPS FOR EXECUTION OF C PROGRAMING :-

1. Program creation (source code)

2. Program compilation (object code)

3. Program execution (.exe file )

-All these steps can be performed in a IDEs (integrated developing environment) using shortcut keys or menu option . You can learn about and can download the softwares or IDEs from my last blog too . I had covered the top IDEs in the below blog , must check for better understanding .

TOP IDEs : https://computer-languages-at-ease-4-u.blogspot.com/2022/04/c-programing-software-download-vs-code.html

https://computer-languages-at-ease-4-u.blogspot.com/2022/04/c-programing-c-c-language-computer.html

-In turbo c/c++ , Borland C program creation : new file can be created using new option . File can be saved by menu option 'save' or by F2 key .

-file compiled by menu option 'compiled' or Alt+F9 .

-file can be executed by menu option 'run' or Ctrl+F9 .

-output appears in the output window that can be seen by using keys Alt+F5 .

ELEMENTS OF C PROGRAMING :

The basic element are character set , variables , data types , constants , keywords , identifiers , variable declaration , expression , or statements. All of these are used to construct C program .

1. CHARACTER SET : C used the upper cases A,B,…….,Z, the lower cases a ,b,…..,z and certain special characters like + - * / = % & # ! ? ^ “ ‘ ~ \ < > ( ) = [ ] { } ; : . , _ blank space @ $ . also certain combinations of these characters like \b, \n, \t, etc…

2. IDENTIFIERS : Identifiers are names given to various program elements like variables, arrays and functions. The name should begin with a letter and other characteers can be letters and digits and also can contain underscore character ( _ ) . Example: area, average, x12 , name_of_place etc………

All the words that we use in C program will be either keyword or identifier . Keywords are predefined and can not be changed by the user , identifiers are user defined words .

3. KEYWORDS : Key words are reserved words in C language. They have predicted meanings and are used for the intended purpose. Standard keywords are auto, break, case, char, const, continue, default, do, double, else enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while. (Note that these words should not be used as identifiers and written in lower case since C is case sensitive language). They are 32 in total .

4. DATA TYPE : The C language has a rich set of data types to handle different kind of data entered by programmer. Basically a data type informs compiler about how much memory a declared variable required to store input. Data types are used extensively for declaring variables and functions of different types. 

  1. char for character
  2. int for integer 
  3. float for single precision number (decimal)
  4. double for double precision 

-Char will take 1 byte , int will take 2 bytes , float takes 4 bytes and double takes 8 bytes .

5. VARIABLES : It is the name that can be use to store values . Variables can take different value but one at a time . These value can be change during execution of the program . Data type is associated with each variable . Data type of variables decides what value it can take .

6. CONSTANTS : The constant is the value that can not be change during the execution of a program .There are 4 basic types of constants . They are integer constants, floating-point constants, character constants and string constants. 

(a) integer constants: It is an integer valued numbers, written in three different number system, decimal (base 10) , octal(base8), and hexadecimal(base 16). A decimal integer constant consists of 0,1,…..,9.. Example : 75 6,0,32, etc….. 5,784, 39,98, 2-5, 09 etc are not integer constants. An octal integer constant consists of digits 0,1,…,7. with 1st digit 0 to indicate that it is an octal integer. 

Example : 0, 01, 0756, 032, etc….. 32, 083, 07.6 etc….. are not valid octal integers. 12 A hexadecimal integer constant consists of 0,1, …,9,A, B, C, D, E, F. It begins with 0x. 

Example: 0x7AA2, 0xAB, etc…… 0x8.3, 0AF2, 0xG etc are not valid hexadecimal constants. Usually negative integer constant begin with ( -) sign. An unsigned integer constant is identified by appending U to the end of the constant like 673U, 098U, 0xACLFU etc. Note that 1234560789LU is an unsigned integer constant. 

( b) floating point constants : It is a decimal number (ie: base 10) with a decimal point or an exponent or both. Ex; 32.65, 0.654, 0.2E-3, 2.65E10 etc. These numbers have greater range than integer constants.

 (c) character constants : It is a single character enclosed in single quotes like ‘a’. ‘3’ , ‘?’ , ‘A’ etc. each character has an ASCII to identify. For example ‘A’ has the ASCII code 65, ‘3’ has the code 51 and so on. 

(d) escape sequences: An escape sequence is used to express non printing character like a new line, tab etc. it begin with the backslash ( \ ) followed by letter like a, n, b, t, v, r, etc. the commonly used escape sequence are \a : for alert \n : new line \0 : null \b : backspace \f : form feed \? : question mark \f : horizontal tab \r : carriage return \’ : single quote \v : vertical tab \” : quotation mark .

(e) string constants : it consists of any number of consecutive characters enclosed in double quotes .Ex : “ C program” , “mathematics” etc……

7. STATEMENTS : It is executable part of the program . It can be categorised in expression statement , compound statement and selection statement (if-else , switch) , iterative statement (for , while , do-while) , jump statement (goto , break , continue) and label statements (case , default) .

Compound statement consist of several statements . It is also called block of statements . 

8. COMMENTS : It They are used for increasing , readability of the program . They explain the purpose of the program and helpful in understanding the program . Comments are written inside /* */. There can be a single line or a multiple line comment . We can write comment anywhere in a program .

1. // I love U (single line comment)

2. /* I love U

I love U

I love U */ (multiple line comment)

9.  ARRAY : An array is an identifier which is used to store a collection of data of the same type with the same name. the data stored is an array are distinguished by the subscript. The maximum size of the array represented by the identifier must be mentioned .

Example : int mark[100] . With this declaration n, mark is an array of size 100, they are identified by nark[0], mark[1],……….,mark[99].

10. DECLARATIONS : This is for specifying data type. All the variables, functions etc must be declared before they are used. A declaration tells the compiler the name and type of a variable you'll be using in your program. In its simplest form, a declaration consists of the type, the name of the variable, and a terminating semicolon: 

Example : int a,b,c; Float mark, x[100], average; char name[30]; char c; int i; float f; You may wonder why variables must be declared before use. 

There are two reasons:

 1. It makes things somewhat easier on the compiler; it knows right away what kind of storage to allocate and what code to emit to store and manipulate each variable; it doesn't have to try to intuit the programmer's intentions. 

2. It forces a bit of useful discipline on the programmer: you cannot introduce variables willy-nilly; you must think about them enough to pick appropriate types for them. (The compiler's error messages to you, telling you that you apparently forgot to declare a variable, are as often helpful as they are a nuisance: they're helpful when they tell you that you misspelled a variable, or forgot to think about exactly how you were going to use it.)

11. EXPRESSIONS : This consists of a single entity like a constant, a variable, an array or a function name. it also consists of some combinations of such entities interconnected by operators. 

Example : a, a+b, x=y, c=a+b, x<=y etc……..

12. SYMBOLLIC CONSANTS : A symbolic constant or macro function is a name that substitutes for a sequence of characters, which represent a numeric, character or string constant. A symbolic constant is defined in the beginning of a program by using #define, without: at the end. 

Example : #define pi 3.1459 

#define INTEREST P*N*R/100

 With this definition it is a program the values of p, n ,r are assigned the value of INTEREST is computed. Note : symbolic constants are not necessary in a C program.

OPERATORS OF C :

C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler to perform a certain mathematical or logical manipulation. Operators are used in programs to manipulate data and variables. C operators can be classified into following types:

 • Arithmetic operators 

• Relational operators

 • Logical operators 

• Bitwise operators 

• Assignment operators 

• Conditional operators 

• Special operators

1. ARITHMETIC OPERATORS : C supports all the basic arithmetic operators. The following table shows all the basic arithmetic operators .



2. RELATIONAL OPERATORS : The following table shows all relation operators supported by C .

3. LOGICAL OPERATORS : C language supports following 3 logical operators. Suppose a = 1 and b = 0,



4. BITWISE OPERATORS : Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bits from right to left. Bitwise operators are not applied to float or double.


5. ASSIGNMENT OPERATORS : Assignment operators supported by C language are as follows.


6. CONDITIONAL OPERATORS : The conditional operators in C language are known by two more names -

 1. Ternary Operator 

2. ? : Operator 

It is actually the if condition that we use in C language decision making, but using conditional operator, we turn the if condition statement into a short and simple operator.

Explanation:

 • The question mark "?" in the syntax represents the if part. 

• The first expression (expression 1) generally returns either true or false, based on which it is decided whether (expression 2) will be executed or (expression 3) .

• If (expression 1) returns true then the expression on the left side of " : " i.e. (expression 2) is executed. 

• If (expression 1) returns false then the expression on the right side of " : " i.e. (expression 3) is executed .

7. SPECIAL OPERATORS :






printf 

In C programming language, printf() function is used to print the (“character, string, float, integer, octal and hexadecimal values”) onto the output screen. 

We use printf() function with %d format specifier to display the value of an integer variable. 

Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal variable. 

To generate a newline,we use “\n” in C printf() statement. 

printf(“string/format specifiers”,variable names) .

scanf 

The scanf function allows you to accept input from standard in, which for us is generally the keyboard. 

The scanf function can do a lot of different things, but can be unreliable because it doesn’t handle human errors very well. But for simple programs it’s good enough and easy to use. 

The simplest application of scanf looks like this:

 scanf("%d", &b);

 The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is printf, so b must be declared as an int) and place that value into b. 

The scanf function uses the same placeholders as printf: 

• int uses %d 

• float uses %f 

• char uses %c 

• character strings (discussed later) use %s 

You must put & in front of the variable used in scanf. The reason why will become clear once you learn about pointers. It is easy to forget the & sign, and when you forget it your program will almost always crash when you run it. 

In general, it is best to use scanf as shown here -- to read a single value from the keyboard. Use multiple calls to scanf to read multiple values. In any real program, you will use the gets or fgets functions instead to read text a line at a time. Then you will "parse" the line to read its values. The reason that you do that is so you can detect errors in the input and handle them as you see fit. 

scanf(“%d%f%c”, &I,&j,&k); 

getchar() 

The function getchar() reads the character from the standard input while getc() reads from the input stream. So, getchar() is equivalent to getc(stdin).

 Here is the syntax of getchar() in C language, 

int getchar(void); 

Here is an example of getchar() in C language, 

#include 

int main()

 { char val; val = getchar();

 printf("Enter the character : \n"); 

printf("Entered character : %c", val); return 0; } 

Output 

Enter the character : n 

Entered character : n 

getch() 

The function getch() is a non-standard function. It is declared in “conio.h” header file. Mostly it is used by Turbo C. It is not a part of C standard library. It immediately returns the entered character without even waiting for the enter key.

 Here is the syntax of getch() in C language, 

int getch(); 

Here is an example of getch() in C language, 

Example 

#include 

int main() { 

char val; val = getch(); 

printf("Enter the character : ");

 printf("Entered character : %c", val); return 0; }

 Output 

Enter the character : m 

Entered character : m 

getche() 

Like getch(), the getche() function is also a non-standard function and declared in “conio.h” header file. It reads a single character from the keyboard and returns it immediately without even waiting for enter key. 

Here is the syntax of getche() in C language,

 int getche(void); 

Here is an example of getche() in C language,

 Example 

#include 

#include 

int main() {

 char val; val = getche();

 printf("Enter the character : "); 

printf("Entered character : %c", val); return 0; } 

Output 

Enter the character : s 

Entered character : s 

#include pre-processor directive A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.

 You request to use a header file in your program by including it with the C preprocessing directive #include, like you have seen inclusion of stdio.h header file, which comes along with your compiler.

 Including a header file is equal to copying the content of the header file but we do not do it because it will be error-prone and it is not a good idea to copy the content of a header file in the source files, especially if we have multiple source files in a program. A simple practice in C or C++ programs is that we keep all the constants, macros, system wide global variables, and function prototypes in the header files and include that header file wherever it is required. 

Include Syntax

 Both the user and the system header files are included using the preprocessing directive, #include. It has the following two forms − 

#include<FILE>

  This form is used for system header files. It searches for a file named 'file' in a standard list of system directories. You can prepend directories to this list with the -I option while compiling your source code. 

#include "file" 

This form is used for header files of your own program. It searches for a file named 'file' in the directory containing the current file. You can prepend directories to this list with the -I option while compiling your source code.

 putchar() function in C

 The putchar(int char) method in C is used to write a character, of unsigned char type, to stdout. This character is passed as the parameter to this method.

 Syntax: 

int putchar(int char) 

Parameters: This method accepts a mandatory parameter char which is the character to be written to stdout. 

Return Value: This function returns the character written on the stdout as an unsigned char. It also returns EOF when some error occurs. 

Below examples illustrate the use of putchar() method: 

Example :

 // C program to demonstrate putchar() method 

#include<stdio.h>

int main()

 { // Get the character to be written 

 char ch = 'G'; 

 // Write the Character to stdout 

 putchar(ch);

 return (0); } 

CONTROL STATEMENTS 

When we run a program ,the statements are executed in the order in which they appear in the program. Also each statement is executed only once. But in many cases we may need a statement or a set of statements to be executed a fixed no of times or until a condition is satisfied. Also we may want to skip some statements based on testing a condition. For all these we use control statements . Control statements are of two types – branching and looping.

 BRANCHING 

It is to execute one of several possible options depending on the outcome of a logical test ,which is carried at some particular point within a program. 

LOOPING 

It is to execute a group of instructions repeatedly,a fixed no of times or until a specified condition is satisfied. 

BRANCHING 

1. if else statement

 It is used to carry out one of the two possible actions depending on the outcome of a logical test. The else portion is optional. The syntax is

 If (expression) statement1 [if there is no else part] 

Or If (expression)

Statement 1 

else Statement 2

 Here expression is a logical expression enclosed in parenthesis. If expression is true , statement 1 or statement 2 is a group of statements ,they are written as a block using the braces { } .

Example: 

1. if(x<0) 

printf(“\n x is negative”); 

2. if(x<0) 

printf(“\n x is negative”); 

else

 printf(“\n x is non negative”); 

3.if(x<0) { 

x=-x; s=sqrt(x); } 

else s=sqrt(x);

2. nested if statement 

Within an if block or else block another if – else statement can come. Such statements are called nested if statements. 

The syntax is 

If (e1) 

s1

 if (e2) 

s2 

else

 s3 

else

3. Ladder if statement

In order to create a situation in which one of several courses of action is executed we use ladder – if statements. 

The syntax is 

If (e1) s1 else 

if (e2) s2 else

 if (e3) s3 ………………. else sn 

Example: if(mark>=90) printf(“\n excellent”); else 

if(mark>=80) printf(“\n very good”); else

 if(mark>=70) printf(“\n good”); else

 if(mark>=60) printf(“\n average”); 

else printf(“\n to be improved”);

SWITCH STATEMENT 

It is used to execute a particular group of statements to be chosen from several available options. The selection is based on the current value of an expression with the switch statement. The syntax is:

switch(expression) {

 case value1:

 s1

 break;

 case value 2:

 s2 

break; 

……. 

…….. 

default:

 sn } 

All the option are embedded in the two braces { }.Within the block each group is written after the label case followed by the value of the expression and a colon. Each group ends with ‘break’ statement. The last may be labeled ‘default’. This is to avoid error and to execute the group of statements in default if the value of the expression does not match value1, value2,…….. 

LOOPING 

1. The while statement 

This is to carry out a set of statements to be executed repeatedly until some condition is satisfied. The syntax is: 

While (expression) statement

 The statement is executed so long as the expression is true. Statement can be simple or compound.

Example 1:

 #include <stdio.h>

while(n > 0) {

 printf("\n");

 n = n - 1; } 

Example 2: 

#include <stdio.h>

main() { 

int i=1;

 while(x<=10) { 

printf(“%d”,i); ++i; } 

2. do while statement 

This is also to carry out a set of statements to be executed repeatedly so long as a condition is true. 

The syntax is:

 do statement while(expression) 

Example: 

#include<stdio.h> 

main() { 

int i=1; 

do 

{ printf(“%d”,i);

 ++i; }

while(i<=10); 

THE DIFFERENCE BETWEEN while loop AND do – while loop

 1) In the while loop the condition is tested in the beginning whereas in the other case it is done at the end.

 2) In while loop the statements in the loop are executed only if the condition is true. Whereas in do – while loop even if the condition is not true the statements are executed at least once.

3. for loop 

It is the most commonly used looping statement in C. The general form is

 For(expression1;expression2;expression3)statement

 Here expression1 is to initialize some parameter that controls the looping action, expression2 is a condition and it must be true to carry out the action,expression3 is a unary expression or an assignment expression. 

Example:

#include<stdio.h>

main() { 

int i; 

for(i=1;i<=10;++i) 

printf(“%d” ,i); } 

Here the program prints i starting from 1 to 10.First i is assigned the value 1 and than it checks whether i<=10 If so i is printed and then i is increased by one. It continues until i<=10.

 An example for finding the average of 10 numbers;

 #include<stdio.h> 

main() {

 int i;

 float x,avg=0;

 for(i=1;i<=10;++i) {

 scanf(“%f”,&x); avg += x; } 

avg /= 10; 

printf(“\n average=%f”,avg); } 

Note: Within a loop another for loop can come Example : for(i=1;i<=10;++i) for(j=1;j<=10;++j); 

The break statement

 The break statement is used to terminate4 loop or to exit from a switch. It is used in for, while, do-while and switch statement. The syntax is 

break; 

Example 1: A program to read the sum of positive numbers only 

#include<stdio.h>

 main() { 

int x, sum=0;

 int n=1; 

while(n<=10) { 

scanf(“%d”,&x);

 if(x<0) 

break; 

sum+=x; } 

printf(“%d”,sum); } 

Example 2 :A program for printing prime numbers between 1 and 100: 

#include<stdio.h>

#include <conio.h>

main() {

 int i, j; 

printf("%d\n", 2); 

for(i = 3; i <= 100; i = i + 1) {

 for(j = 2; j < i; j = j + 1) 

{ if(i % j == 0) 

break; 

if(j > sqrt(i)) 

{ printf("%d\n", i); 

break;

 } 

return 0; 

}

 Here while loop breaks if the input for x is –ve.

The continue statement 

It is used to bypass the remainder of the current pass through a loop. The loop does not terminate when continue statement is encountered, but statements after continue are skipped and proceeds to the next pass through the loop. In the above example of summing up the non negative numbers when a negative value is input, it breaks and the execution of the loop ends. In case if we want to sum 10 nonnegative numbers, we can use continue instead of break .

 Example :

 #include<stdio.h> 

main() { 

int x, sum=0, n=0;

 while(n<10) {

 scanf(“%d”,x);

 if(x<0) 

continue; 

sum+=x; ++n; } 

printf(“%d”,sum); 

GO TO statement

 It is used to alter the normal sequence of program execution by transferring control to some other part of the program .The syntax is 

goto label ; 

Example : 

#include<stdio.h>

main( ) {

 int n=1,x,sum=0;

 while(n<=10) { 

scanf(“%d” ,&x);

 if(x<0)goto error; sum+=x; ++n; }

 error:

 printf(“\n the number is non negative”); 

}

FUNCTIONS :-

A function is itself a block of code which can solve simple or complex task/calculations. A function performs calculations on the data provided to it is called "parameter" or "argument". A function always returns single value result.

Types of function: 

1. Built in functions(Library functions) Or Predefined functions

 a.) Inputting Functions. 

b.) Outputting functions. 

2. User defined functions.

a.) fact();

 b.) sum(); 

Parts of a function: 

1. Function declaration/Prototype/Syntax. 

2. Function Calling. 

3. Function Definition. 





Passing parameters to a function: Firstly, what are parameters? parameters are the values that are passed to a function for processing. There are 2 types of parameters: 

a.) Actual Parameters. 

b.) Formal Parameters. 

a.) Actual Parameters: These are the parameters which are used in main() function for function calling. Syntax :<variable name>=<function name><actual argument>

Example: fact= fact(n);

b.) Formal Parameters: These are the parameters which are used in function definition for processing.

 Methods of parameters passing: 

1.) Call by reference 

2.) Call by value. 

1.) Call by reference: In this method of parameter passing , original values of variables are passed from calling program to function. Thus, Any change made in the function can be reflected back to the calling program

 2.) Call by value: In this method of parameter passing, duplicate values of parameters are passed from calling program to function definition. Thus, Any change made in function would not be reflected back to the calling program. 



Types of user defined functions in C :

Different types of user-defined functions: A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories.

  Category 1: Functions with no arguments and no return values 

 Category 2: Functions with no arguments and with return values 

 Category 3: Functions with arguments and no return values 

 Category 4: Functions with arguments and with return values








STORAGE CLASSES :

Every Variable in a program has memory associated with it. Memory Requirement of Variables is different for different types of variables. In C, Memory is allocated & released at different places . 

Storage class of variable Determines following things 

1. Where the variable is stored 

2. Scope of Variable 

3. Default initial value 

4. Lifetime of a variable 

A. Where the variable is stored

Storage Class determines the location of variable, where it is declared. Variables declared with auto storage classes are declared inside main memory whereas variables declared with keyword register are stored inside the CPU Register. 

B. Scope of Variable 

Scope of Variable tells compile about the visibility of Variable in the block. Variable may have Block Scope, Local Scope and External Scope. A scope is the context within a computer program in which a variable name or other identifier is valid and can be used, or within which a declaration has effect.

 C. Default Initial Value of the Variable 

Whenever we declare a Variable in C, garbage value is assigned to the variable. Garbage Value may be considered as initial value of the variable. C Programming have different storage classes which has different initial values such as Global Variable have Initial Value as 0 while the Local auto variable have default initial garbage value. 

D. Lifetime of variable 

Lifetime of the = Time Of variable Declaration - Time of Variable Destruction Suppose we have declared variable inside main function then variable will be destroyed only when the control comes out of the main i.e. end of the program. 

Different Storage Classes: 

-Auto Storage Class 

-Static Storage Class 

-Extern Storage Class 

-Register Storage Class 

Automatic (Auto) storage class 

This is default storage class All variables declared are of type Auto by default In order to Explicit declaration of variable use ‘auto‘ keyword auto int num1 ; // Explicit Declaration 

Features: 

Storage- Memory 

Scope- Local / Block Scope 

Life time- Exists as long as Control remains in the block

 Default initial Value- Garbage 

Note : Two variables are declared in different blocks , so they are treated as different variables .

External (extern) storage class 

Variables of this storage class are ―Global variables‖ Global Variables are declared outside the function and are accessible to all functions in the program Generally , External variables are declared again in the function using keyword extern In order to Explicit declaration of variable use ‗extern‘ keyword extern int num1 ; // Explicit Declaration .

Features: 

Storage- Memory 

Scope- Global/File Scope 

Life time- Exists as long as variable is running retains value within the fucntion 

 Default initial Value-  Zero

Note : Declaration within the function indicates that the function uses external variable Functions belonging to same source code , does not require declaration (no need to write extern) If variable is defined outside the source code , then declaration using extern keyword is required .

Static storage class 

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. In C programming, when static is used on a class data member, it causes only one copy of that member to be shared by all the objects of its class. 

Register storage class 

Register keyword is used to define local variable. Local variable are stored in register instead of RAM. As variable is stored in register, the Maximum size of variable = Maximum Size of Register unary operator [&] is not associated with it because Value is not stored in RAM instead it is stored in Register. This is generally used for faster access. Common use is ―Counter ― Syntax { register int count; } .

 Why we need Register Variable ? 

Whenever we declare any variable inside C Program then memory will be randomly allocated at particular memory location. We have to keep track of that memory location. We need to access value at that memory location using ampersand operator/Address Operator i.e (&). If we store same variable in the register memory then we can access that memory location directly without using the Address operator. Register variable will be accessed faster than the normal variable thus increasing the operation and program execution. Generally we use register variable as Counter. 

Note : It is not applicable for arrays, structures or pointers. 

LET US PRACTICE SOME IMPORTANT PROGRAMS OF C :











THANKS A LOT FOR VISITING !!! I HOPE THE CONTENT WAS UPTO YOUR EXPECTATIONS . IF YOU HAVE ANY ISSUE WITH THE CONTENT OR YOU FOUND ANY MISTAKE IN THE ABOVE BLOG  THEN YOU CA COMMENT BELOW . YOUR COMMENTS WILL BE TAKEN INTO CONSIDERATIONS FOR SURE .

Comments

Popular posts from this blog

C PROGRAMING SOFTWARE DOWNLOAD | VS CODE | CODEBLOCKS |ATOM | NETBEANS | TOP IDEs FOR C OR C++ | MOST POPULAR COMPILER |