1st unit c

Embed Size (px)

Citation preview

  • 7/30/2019 1st unit c

    1/152

    UNIT 1

    Syllabus:-Programming in C: Structure of C Program, Concept of Preprocessor, MacroSubstitution,Intermediate code, Object Code, Executable Code. Compilation Process,Basic Datatypes, Importance of braces ({ }) in C Program, enumerated data type, Identifiers,Scope of

  • 7/30/2019 1st unit c

    2/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Variable, Storage Class, Constants, Operators & Expressions in C, Type Casting,printf( ) andscanf ( ) with format specifires, reading single character.

    Structure of a C Program:-

    C is a general-purpose high level language that was originally developed by Dennis Ritchie forthe Unix operating system. It was first implemented on the Digital Eqquipment Corporation DP-11 computer in 1972.

    The Unix operating system and virtually all Unix applications are written in the C language. Cas now become a widely used professional language for various reasons.

    Easy to learn Structured language It produces efficient programs. It can handle low-level activities. It can be compiled on a variety of computers.

    Facts about C:-

    C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around 1970 The language was formalized in 1988 by the American National Standard Institue

    (ANSI). By 1973 UNIX OS almost totally written in C. Today C is the most widely used System Programming Language. Most of the state of the art software have been implemented using C

    Why to use C?

    C was initially used for system development work, in particular the programs that make-up theoperating system. C was adoped as a system development language because it produces code thatruns nearly as fast as code written in assembly language. Some examples of the use of C mightbe:-

    Operating Systems Language Compilers Assemblers

    Text Editors Print Spoolers Network Drivers Modern Programs Data Bases Language Interpreters Utilities

  • 7/30/2019 1st unit c

    3/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    All the C programs are writen into text files with extension ".c" for example hello.c. You can use"vi" editor to write your C program into a file. .

    C Compilers:-

    When you write any program in C language then to run that program you need to compile thatprogram using a C Compiler which converts your program into a language understandable by acomputer. This is called machine language (ie. binary format). So before proceeding, make sureyou have C Compiler available at your computer. It comes alongwith all flavors of Unix andLinux. If you are working over Unix or Linux then you can typegcc -v orcc -v and check theresult. You can ask your system administrator or you can take help from anyone to identify anavailable C Compiler at your computer.

    If you don't have C compiler installed at your computer then you can use below given link todownload a GNU C Compiler and use it.

    C language is very popular language among all the languages. Sometimes I think that had therebeen no "C" language there would have no C++ and even Java. So let me explain you the basicstructure ofaClanguage.

    The structure of a C program is a protocol (rules) to the programmer, while writing a C program.The general basic structure of C program is shown in the figure below. The whole program iscontrolled within main ( ) along with left brace denoted by { and right braces denotedby }.If you need to declare local variables and executable program structures are enclosed within {

    and } is called the body of the main function. The main ( ) function can be preceded by

    documentation, preprocessor statements and global declarations.

    Figure:-Sturucture of C program

    Documentations:-

    The documentation section consist of a set of comment lines giving the name of the program, theanother name and other details, which the programmer would like to use later.

  • 7/30/2019 1st unit c

    4/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Preprocessor Statements:-

    The preprocessor statement begin with # symbol and are also called the preprocessor directive.These statements instruct the compiler to include C preprocessors such as header files andsymbolic constants before compiling the C program. Some of the preprocessor statements are

    listed below.

    Figure:-header files & Symbolic constants

    Global Declarations:-The variables are declared before the main ( ) function as well as user defined functions arecalled global variables. These global variables can be accessed by all the user defined functionsincluding main ( ) function.

    The main ( ) function:-

    Each and Every C program should contain only one main ( ). The C program execution startswith main ( ) function. No C program is executed without the main function. The main ( )function should be written in small (lowercase) letters and it should not be terminated bysemicolon. Main ( ) executes user defined program statements, library functions and user definedfunctions and all these statements should be enclosed within left and right braces.

    Braces:-

    Every C program should have a pair of curly braces ({,}). The left braces indicates the beginning

    of the main ( ) function and the right braces indicates the end of the main ( ) function. Thesebraces can also be used to indicate the user-defined functions beginning and ending. These twobraces can also be used in compound statements.

    Local Declarations:-

    The variable declaration is a part of C program and all the variables are used in main ( ) function

  • 7/30/2019 1st unit c

    5/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    should be declared in the local declaration section is called local variables. Not only variables,we can also declare arrays, functions, pointers etc. These variables can also be initialized withbasic data types. For examples.

    Code:

    Main ( ){int sum = 0;int x;float y;

    }

    Here, the variable sum is declared as integer variable and it is initialized to zero. Other variablesdeclared as int and float and these variables inside any function are called local variables.

    Program statements:-

    These statements are building blocks of a program. They represent instructions to the computerto perform a specific task (operations). An instruction may contain an input-output statements,arithmetic statements, control statements, simple assignment statements and any other statementsand it also includes comments that are enclosed within /* and */ . The comment statements arenot compiled and executed and each executable statement should be terminated with semicolon.

    User defined functions:-

    These are subprograms, generally, a subprogram is a function and these functions are written bythe user are called user ; defined functions. These functions are performed by user specific tasks

    and this also contains set of program statements. They may be written before or after a main ()function and called within main () function. This is an optional to the programmer.Now, let us write a small program to display some message shown below.

    Code:# include main(){printf ("welcome to the world of C/n");}

    C is a Structured programming language, so we have to write our C Programs in a StructuredFormat framed for it.

    Header Files.

    main()

    {

  • 7/30/2019 1st unit c

    6/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    C Statements and Functions;

    }

    Every C Statements should end with a semicolon (;).

    Based on this, we will write a Simple Hellow World program in C in the next Section.

    Hellow World Program in C

    hellow_world.c

    #include#includevoid main(){printf("Hellow World in C");

    getch();}

    Program Algorithm / Explanation:-

    1. #include header file is included because, the C in-built statement printfweused in this program comes understdio.h header files.

    2. #include is used because the C in-built function getch() comes underconio.hheader files.

    3. main () function is the place where C program execution begins.4. printfis used to display Hellow World. printf is the C in-built function, to display to

    the standard output device (Monitor).5. Since C program execution happen in milliseconds, we cannot see the output (Hellow

    World) in the screen. Thats because Program output window closes immediately afterexecution. So we need a way to stop the program output window from closing. getch()will wait for keypress in our program execution and hence, we can see the result HellowWorld. After viewing the output we can close the output by pressing any key in thekeyboard.

    Output :

  • 7/30/2019 1st unit c

    7/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    C is a Structured Programming Language (program executes line by line). Even though manyAdvanced modern programming languages have emerged, C still remains the most powerfulprogramming language ever invented.

    Why C is the most powerful language?To put that in a simple way,

    Almost all modern programming languages are built from C. Almost all the modern Operating Systems that control the PCs are made of C. Windows,

    Linux, FreeBSD you name it.

    Even though modern programming languages are created to provide additional features and easeof implementation for programmers, I would say, modern languages are created to prevent usfrom using / practising C, because C provides a special feature, which was completely eliminatedfrom modern programming languages.

  • 7/30/2019 1st unit c

    8/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    figure:-BIOS System

    Now consider a situation, we want to copy a file to our PC Hard Disk. When we initiate copyprocess in our Operating System the operating system communicates with BIOS (Firmware) withthe help of Interrupts Request (IR) instructions to do the Job. The BIOS after receiving thesuitable IR Instructions moves the Read/Write Head of hard Disk to the appropriate Location anddoes the file copy job in the Hardware Level. So for every job like copy, format, delete etc, thereare separate IR Instructions.

    Memory Specifications :-

    It is very important that every C programmer should be aware of memory.

    1 BitSpace required to store a single character (eg :- a or , oror /or . or 4 etc)1 Byte8 Bits1 Kilo Byte (KB)1024 Bytes1 Mega Byte (MB)1024 KB1 Giga Byte (GB)1024 MB1 Tera Byte (TB)1024 GB

    1 bit x 8 byte x 1024 kb x 1024 mb x 1024 gb = 8589934592 Bits (1 TB).

    Variables in C :-

    Variable is used to store the values temporarily during the execution (runtime) of the program.Variables are allocated Memory Space (in RAM) depending on the data type. First we have todeclare the needed variables in our program before actually using it. Declaring the variablesdoesnt guarantee that space is allocated in the Main Memory (RAM). The space is allocated

    during the execution (runtime) of the program.

  • 7/30/2019 1st unit c

    9/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Rules for declaring Variables in C :-

    1. The 1st letter should be alphabet.2. Variables can be combination of alphabets and digits.3. Underscore ( _ ) is the only special character allowed.4. Variables can be written in both Uppercase and Lowercase orcombination of both.5. Variables are Case Sensitive.6. No Spaces allowed between Characters.7. Variable name should not make use to the C Reserved Keywords.8. Variable name should not start with a number.

    Example : - a, number, s5, book_no etc.

    Data types in C :-

    Data types define the type of data to be stored in variables. So it is important that we mention the

    data type, when a variable is declared.There are many different data types in C.

    Data Types Format String

    int %d

    unsigned int %u

    float %f

    long %ld

    unsigned long %lu

    double %lf

    long double %lf

    char %c / %sunsigned char %c / %s

    Table:-different data types in C

    Syntax for declaring Variables in C :-

    data_type variable_name ;

    Where,Data_typeValid C data type.

    (eg : int, char, float etc)Variable_namevalid user defined C variable.

    Example :- int i, char name, float no etc.

  • 7/30/2019 1st unit c

    10/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Sample Program :-

    variables.c

    #include

    #includevoid main(){int i=10;float f=10.5;char c='s';char s[10]="hellow";

    printf("\n Integer : %d",i);printf("\n Float : %f",f);printf("\n Character : %c",c);

    printf("\n String : %s",s);

    getch();}

    Program Algorithm / Explanation

    1. #include header file is included because, the C in-built statement printf weused in this program comes understdio.h header files.

    2. #include is used because the C in-built function getch() comes underconio.hheader files.

    3. main () function is the place where C program execution begins.4. Variable i of type int is declared and initialised with value of10.5. Variable fof type float is declared and initialised with value of10.5.6. Variable c of type char is declared and initialised with value ofs.7. Array s[] of type char with size 10 is declared and initialised with value ofhellow.8. Now i is displayed using control string %d, fusing control string %f, c using control

    string %c, and array s using control string %s.

    Output :

  • 7/30/2019 1st unit c

    11/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    variable_size.c

    #include#includevoid main(){

    printf("\n Size of Int : %d",sizeof(int));printf("\n Size of short Int : %d",sizeof(short int));printf("\n Size of long Int : %d",sizeof(long int));printf("\n Size of Double : %d",sizeof(double));printf("\n Size of Long Double : %d",sizeof(long double));

    getch();}

    Program Algorithm / Explanation:-

    1. #include header file is included because, the C in-built statement printfwe usedin this program comes understdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4.

    sizeof() is used to display the size of different datatypes.

  • 7/30/2019 1st unit c

    12/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    Constants in C:-

    Constants can be also called as static variables. In variables values can be changed to anynumber of times during execution, whereas in constants value once assigned will remain staticthroughout the entire period.Rules for declaring a constant is exactly the same as variables,except constant declaration is preceded by the keyword constant.

    Syntax for Constant :-

    const data_type constant_name = value;

    Where,constC keyworddata_typevalid C data type (eg : int, char, float etc)constant_nameuser defined namevaluestatic value assigned to constant by the programmer.

    Types of Constants in C:-

    1. Integer constant2. Real Constant3. Single Character constant4. String constant

    1) Integer Constant :Integer constant can have integer values.Eg : 1, 100, -20 etc.

    2) Real constant :Real constant can also be called floating point constants. Because, we can store values with

  • 7/30/2019 1st unit c

    13/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    decimal places.Example:- 1.00, 100.50, etc

    3) Character Constant :Character constant is used to store a single character.

    Example :- a, b, 1, 5 etc.

    4) String constant :String Constants are used to store a string of characters.Example :- hi, welcome, 666 etc.

    Sample Program :-

    constant.c

    #include

    #includevoid main(){const int i=10;const float f=5.5;const char c='c';const char *s="hellow";

    printf("\n Integer Constant : %d",i);printf("\n Real Constant : %f",f);printf("\n Single Character Constant : %c",c);

    printf("\n String Constant : %s",s);

    getch();}

    Program Algorithm / Explanation

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Constant i of type int is declared and initialised with value of10.5. Constant fof type float is declared and initialised with value of10.5.6. Constant c of type char is declared and initialised with value ofs.7. Constant s of type char is declared and initialised with value ofhellow.8. Now i is displayed using control string %d, fusing control string %f, c using control

    string %c, and s using control string %s.

  • 7/30/2019 1st unit c

    14/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    Formatted I/O in C :

    The formatted Input / Output functions can read and write values of all data types, provided theappropriate conversion symbol is used to identify the datatype.scanfis used for receivingformatted Input and printfis used for displaying formatted output.

    Syntax for scanf :

    scanf(control_string 1, - - , control_string n,&variable1, - - - - ,variable n);

    Syntax for printf :

    printf(control_string 1, - - , control_string n,variable1, - - - - , variable n);

    Sample Program :

    printf_scanf.c

    #include#includevoid main(){int no;char ch;char s[20];

  • 7/30/2019 1st unit c

    15/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    printf("Enter a character : ");scanf("%c",&ch);

    printf("Enter a No : ");scanf("%d",&no);

    printf("Enter a Word or String : ");scanf("%s",&s);

    printf("\n Character : %c",ch);printf("\n No : %d",no);printf("\n String : %s",s);

    getch();}

    Program Algorithm / Explanation

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Variable no of type int is declared.5. Variable ch of type char is declared.6. Array s[] of size 20 and type char is declared.7. printfis used to prompt the user to input data to the above variables.8. scanfis used to receive the datas.9. Control string %d used for receiving user input for integer data, %c for character and

    %s for receiving in a array.10.The user input datas are displayed using printf.

    Output :

  • 7/30/2019 1st unit c

    16/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Syntax for getch () in C :-

    variable_name = getch();

    getch() accepts only single character from keyboard. The character entered through getch() is notdisplayed in the screen (monitor).

    Syntax for getche() in C :

    variable_name = getche();

    Like getch(), getche() also accepts only single character, but unlike getch(), getche() displays theentered character in the screen.

    Syntax for getchar() in C :

    variable_name = getchar();

    getchar() accepts one character type data from the keyboard.

    Syntax for gets() in C :

    gets(variable_name);

    gets() accepts any line of string including spaces from the standard Input device (keyboard).gets() stops reading character from keyboard only when the enter key is pressed.

  • 7/30/2019 1st unit c

    17/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    The unformatted output statements in C are putch, putchar and puts.

    Syntax for putch in C :

    putch(variable_name);

    putch displays any alphanumeric characters to the standard output device. It displays only onecharacter at a time.

    Syntax for putchar in C :

    putchar(variable_name);

    putchar displays one character at a time to the Monitor.

    Syntax for puts in C :

    puts(variable_name);

    puts displays a single / paragraph of text to the standard output device.

    Sample program :

    gets_puts.c

    #include

    #includevoid main(){char a[20];gets(a);puts(a);

    getch();}

    Program Algorithm / Explanation

    1. #include header file is included because, the C in-built statements gets andputs we used in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Array a[] of type char size 20 is declared.

  • 7/30/2019 1st unit c

    18/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    5. gets is used to receive user input to the array. gets stops receiving user input only whenthe Newline character (Enter Key) is interrupted.

    6. puts is used to display them back in the monitor.Output :

    Functions in C:-

    When we write large complex programs, it becomes difficult to keep track of the source code.The job of functions is to divide the large program to many separate modules based on theirfunctionality.

    There are 4 types of functions in C.

    1. Functions with no arguments and no return value.2. Functions with arguments but no return value.3. Function with no arguments but with return value.4. Functions with arguments and with return value.

    1) Functions with no arguments and no return value in C :

    Syntax :

    function_name (){

    Valid C Statements;}

    Sample Program :

    function1.c

    #include

  • 7/30/2019 1st unit c

    19/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    #includevoid main(){funct();getch();

    }funct(){printf("hi, this is display from function funct()");}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printf andscanfwe used in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. funct() is actually the function call to execute the function funct().5. Function funct() is written outside the main () function with no arguments and no

    return value.6. printfis used to display the text hi, this is display from function funct().7. getch() is used to wait for key press so that displayed result can be viewed.

    Output :

  • 7/30/2019 1st unit c

    20/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    2) Functions with arguments and no return value in C :

    Syntax :

    function_name(argument 1, - - - -, argument n)

    {Valid C Statements;}

    Sample Program :

    function2.c

    #include#includevoid main()

    {int a,b;printf("Enter a value for a :");scanf("%d",&a);printf("Enter a value for b :");scanf("%d",&b);funct(a,b);getch();}funct(int a1, int b1){

    int c;c=a1+b1;printf("\n Result = %d",c);}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Two Integer variable a & b are declared.5. printfis used to ask the user to input value of a and b and the same is received using

    scanf.6. The values received in a & b are passed as arguments to function call funct(a,b).7. The arguments from main() function are received in a1 & b1. funct(int a1, int b1).8. Inside funct() a new variable c of type int is declared.9. The values in a1 and b1 are added and stored in variable c.

  • 7/30/2019 1st unit c

    21/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    10.The result in c are printed using printf.Output :

    3) Function with no arguments but with return value in C :

    Syntax :

    data_type function_name(){Valid C Statements;return(value);}

    Sample Program :

    function3.c

    #include#includevoid main(){int result;

    result=funct();printf("\n Result = %d",result);getch();}int funct(){int a,b,c;

  • 7/30/2019 1st unit c

    22/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    printf("Enter a value for a :");scanf("%d",&a);printf("Enter a value for b :");scanf("%d",&b);c=a+b;

    return(c);}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Variable result of type int is declared. int result;5. Function call is assigned to variable result. result = funct() .6. Inside function funct(), 3 variables a, b and c are declared of type int.7. printfis used to prompt the user to Enter value fora & b.8. scanfis used to receive the values ofa and b.9. The values received in a & b are added and stored in variable c.10.The result in c is returned back using return(c).11.Back in main() the returned value is stored in the variable result. result = funct()12.And the value in result is displayed using printf.

    Output :

  • 7/30/2019 1st unit c

    23/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    4) Functions with arguments and with return value in C :

    Syntax :

    data_type function_name(arguments)

    {Valid C Statements;return(value);}

    Sample Program :

    function4.c

    #include#include

    void main(){int a,b,result;printf("Enter a value for a :");scanf("%d",&a);printf("Enter a value for b :");scanf("%d",&b);result=funct(a,b);getch();}int funct(int a1, int b1)

    {int c;c=a1+b1;printf("\n Result = %d",c);return(c);}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printf andscanfwe used in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Three variables a, b and result of type int are declared inside main().5. scanfis sued to receive user Input from a and b.6. function call is made by passing a and b as arguments to funct() .7. In function funct() the arguments passed from main() are received through a1 and b1.

    int funct(int a1, int b1)

  • 7/30/2019 1st unit c

    24/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    8. Another variable c is declared inside funct().9. a1 and b1 are added and the result is stored in c.10.The value in c is returned. return(c)11.Back in main(), return value is stored in variable result.result = funct(a,b)12.And the result is printed using printf.

    Output :

    Conditional Statements in C :-

    Conditional statements are used to execute a statement or a group of statement based on certainconditions.

    1.

    if2. if else3. else if4. switch5. goto

    1) if conditional statement in C :

    Syntax for if statement in C :

    if(condition)

    {Valid C Statements;}

    If the condition is true the statements inside the parenthesis { }, will be executed, else the controlwill be transferred to the next statement after if.

    if.c

  • 7/30/2019 1st unit c

    25/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    #include#includevoid main(){int a,b;

    a=10;b=5;if(a>b){printf("a is greater");}getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Two variables a&b of type int is declared.5. Variable a is assigned a value of10 and variable b with 5.6. A ifcondition is used to check whethera is greater than b. if(a>b)7. As a is greater than b the printf inside the if { }is executed with a message a is

    greater.

    Output :

    2) if else in C :

    Syntax for if :

    if(condition){

  • 7/30/2019 1st unit c

    26/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Valid C Statements;}else{Valid C Statements;

    }

    In if else if the condition is true the statements between if and else is executed. If it is false thestatement after else is executed.

    if_else.c

    #include#includevoid main(){

    int a,b;printf("Enter a value for a:");scanf("%d",&a);printf("\nEnter a value for b:");scanf("%d",&b);

    if(a>b){printf("\n a got greater value");}else

    {printf("\n b got greater value");}printf("\n Press any key to close the Application");getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Two integer variable a and b are declared.5. User Input values are received for both a and b using scanf.6. An if else conditional statement is used to check whethera is greater than b.7. Ifa is greater than b, the message a got greater value is displayed using printf.8. Ifbis greater the message b got greater value is displayed.

  • 7/30/2019 1st unit c

    27/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    3) else if in C :-

    Syntax :

    if(condition){Valid C Statements;}else if(condition 1){

    Valid C Statements;}--else if(condition n){Valid C Statements;}else{Valid C Statements;

    }

    In else if, if the condition is true the statements between if and else if is executed. If it is false thecondition in else if is checked and if it is true it will be executed. If none of the condition is truethe statement under else is executed.

  • 7/30/2019 1st unit c

    28/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    else_if.c

    #include#includevoid main()

    {int a,b;printf("Enter a value for a:");scanf("%d",&a);printf("\nEnter a value for b:");scanf("%d",&b);if(a>b){printf("\n a is greater than b");}else if(b>a)

    {printf("\n b is greater than a");}else{printf("\n Both a and b are equal");}printf("\n Press any key to close the application");getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Two variables a & b of type int are declared.5. Values for a & b are received from user through scanf.6. ifcondition is used to check whethera is greater than b. if(a>b)

    If the condition is true the statement between if and else if is executed.

    1. If the condition is not satisfied else if() condition is checked. Else if(b>a)Ifb is greater than a the statement between else ifand else is executed.

    1. If both the conditions are false the statement afterelse is executed.

  • 7/30/2019 1st unit c

    29/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    4) Switch statement in C :-

    Syntax :

    switch(variable){case 1:Valid C Statements;break;--case n:Valid C Statements;break;default:Valid C Statements;break;}

    Switch statements can also be called matching case statements. If matches the value in variable(switch(variable)) with any of the case inside, the statements under the case that matches will beexecuted. If none of the case is matched the statement under default will be executed.

    switch.c

    #include#include

  • 7/30/2019 1st unit c

    30/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    void main(){int a;printf("Enter a no between 1 and 5 : ");scanf("%d",&a);

    switch(a){case 1:printf("You choosed One");break;case 2:printf("You choosed Two");break;case 3:printf("You choosed Three");

    break;case 4:printf("You choosed Four");break;case 5:printf("You choosed Five");break;default :printf("Wrong Choice. Enter a no between 1 and 5");break;}

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Variable a of type int is declared.5. scanfis used to get the value from user for variable a.6. variable a is included forswitch case. switch(a).7. If the user Input was 1 the statement inside case 1: will be executed. Likewise for the rest

    of the cases until 5.8. But if the user Input is other than 1 to 5 the statement underdefault : will be executed.

  • 7/30/2019 1st unit c

    31/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    5) goto statement in C :-

    goto is a unconditional jump statement.

    Syntax :

    goto label;

    so we have to use the goto carefully inside a conditional statement.

    goto.c

    #include#includevoid main()

    {int a,b;printf("Enter 2 nos A and B one by one : ");scanf("%d%d",&a,&b);if(a>b){goto first;}else{goto second;

    }

    first:printf("\n A is greater..");goto g;

    second:printf("\n B is greater..");

  • 7/30/2019 1st unit c

    32/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    g:getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main () function is the place where C program execution begins.4. Two variables a & b of type int are declared.5. User Inputs are received fora & b using scanf.6. ifcondition is used to check whethera is greater than b. if(a>b).7. if it is true goto statement is used to jump to the label first : and the statement underfirst

    : is executed and then again jump is performed to get to the end of the program. goto g:8. if the condition is false a statement is used to jump to label second. goto second : and the

    statement under second : is executed.

    Output :

    Looping Statements in C :-

    Looping statements are used to execute a statement or a group of statements repeatedly until thecondition is true.

    1. for loop2. while loop3. do while

  • 7/30/2019 1st unit c

    33/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    1) for Loop in C :-

    Syntax :

    for(variable_initialisation;condition;increment/decrement)

    {Valid C Statements;}

    In for loop first the variable is initialised and checks for the condition. If the condition is true.The statement inside for loop will be executed. On the next cycle the initialised variable will beeither incremented or decremented and again checks for the condition. If the condition is true,again the statement inside will be executed. This process will continue until the condition is true.Once the condition fails the control jumps out of for loop.

    for.c

    #include#includevoid main(){int i,a=0;for(i=1;i

  • 7/30/2019 1st unit c

    34/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    10.The cycle continues until i is 10. When i becomes 11 the condition i

  • 7/30/2019 1st unit c

    35/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. Variable a of type int is declared and initialised with value of1. int a = 1;5. A while loop is started with condition a

  • 7/30/2019 1st unit c

    36/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    #include#includevoid main(){int a=1;

    do{printf("\n %d",a);a++;}while(a

  • 7/30/2019 1st unit c

    37/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    {int a=1;

    do{

    printf("\n %d",a);a++;}while(a

  • 7/30/2019 1st unit c

    38/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    In the above example at 1st printf() the value of a (i.e) 5 is printed. Then when a is assigned avalue of 6 and then 6 is printed. This means in variables we can only replace that value. If wewant many values to be stored simultaneously, we need to have as many variables declared,which will make things complicated.In such places arrays can be used. Only condition si, we canstore only one type of datas in array (i.e) In Integer array we can store only nos in char array

    only characters cab be stored.

    Note:-Arrays always starts from location 0.

    There are three types of arrays in C,

    1. Single Dimensional Array.2. Two dimensional Array &3. Multi Dimensional Array.

    1) Single Dimensional Arrays in C :-

    Syntax for declaring single dimensional array in C :

    data_type array_name[size];

    single_array1.c

    #include#includevoid main(){

    int a[5]={1,2,3,4,5};printf("%d",a[0]);getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. Array a[] of type int is declared and initialised with 5 values.int a[5]={1,2,3,4,5}5. a[5] which means size of the array is 5 and array locations starts from 0.6. So when a[0] is printed using printfthe very first data in our array 1 is printed.

  • 7/30/2019 1st unit c

    39/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    single_array2.c

    #include

    #includevoid main(){int a[5]={1,2,3,4,5};int i;for(i=0;i

  • 7/30/2019 1st unit c

    40/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    single_array3.c

    #include#includevoid main(){int a[20];int n,i;printf("\n Enter the size of array :");scanf("%d",&n);printf("%d",n);printf("\n Enter Values to store in array one by one by pressing ENTER :");for(i=0;i

  • 7/30/2019 1st unit c

    41/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    8. Inside for loop values for array is received using scanf(%d,&a[i]).9. Anotherfor loop is used to print all the values ofarray.

    Output :

    Two Dimensional Arrays in C :-

    Syntax for 2D array in C :

    data_type array_name[row][column];

    2d_array1.c

    #include#includevoid main(){int i,j;int a[2][2]={{11,12},{21,22}};

    for(i=0;i

  • 7/30/2019 1st unit c

    42/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A two dimensional array is declared and initialised with values.int

    a[2][2]={{11m12},{21,23}}; 5. Nested for loop is used to print data in two dimensional array.6. In the first cycle offor loop both i & j are 0, so the first data at location a[0][0] is

    displayed.7. On the 2nd cycle i remains 0, whereasj is incremented to 1.So, a[0][1] is displayed.

    Output :

    2d_array2.c

    #include#includevoid main(){int i,j,n;int a[6][6];printf("\n Enter the Size (row x column) of a square matrix :");scanf("%d",&n);for(i=0;i

  • 7/30/2019 1st unit c

    43/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    for(j=0;j

  • 7/30/2019 1st unit c

    44/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Syntax for declaring a structure in C :

    struct structure_name{data_type variable_name 1;

    --data_type variable_name n;};

    Where,structkeyword.structure_name - user defined name.

    After declaring structure to access the datas (variables) inside the structure, we have to create

    structure variables.

    Syntax :

    struct structure_name structure_variable;

    Then datas inside structure can be accessed using,

    structure_variable.variable_name;

    Sample programs :

    structure_basic.c

    #include#includevoid main(){struct employee{char name[20];int age;

    };struct employee emp={"sat",27};printf("\n Name : %s",emp.name);printf("\n Age : %d",emp.age);getch();}

  • 7/30/2019 1st unit c

    45/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A structure with structure name employee is declared.5. It got a char type array name[20] and a int type variable age.6. Values are assigned to the structure using structure variable emp. struct employee

    emp={sat,27};7. And they are displayed using, structure_variable.variable.

    Output :

    structure.c

    #include#includevoid main(){struct employee{char name[20];int age;};struct employee emp;printf("\n Enter Name:");

    scanf("%s",emp.name);printf("\n Enter Age:");scanf("%d",&emp.age);printf("\n Name : %s",emp.name);printf("\n Age : %d",emp.age);getch();}

  • 7/30/2019 1st unit c

    46/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A structure with structure name employee is declared.5. It got a char type array name[20] and a int type variable age.6. Values for structure are received from user input using scanf.7. And displayed using printf.

    Output :-

    Array of structures in C :-

    It is a known fact that even though array can be store multiple values, they all can be of only onedata type.Whereas structure can store different data types. So by declaring structure variable as aarray, we can store many values of different data types.

    structure_array.c

    #include#includevoid main(){

    int i,j,n;i=0;j=0;struct emp{char emp_name[40];int emp_no;

  • 7/30/2019 1st unit c

    47/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    };

    struct emp emp_details[10];

    printf("No of Emploees to be Entered : ");

    scanf("%d",&n);

    while(i

  • 7/30/2019 1st unit c

    48/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    The above example is the cleardemonstration of storing multiple datas in a structure using theconcept Array of Structures.

    Structures and Functions in C :-

    We can use structure members to pass values (arguments) to a function.

    structure_function.c

    #include#includevoid main(){

    struct emp{char emp_name[40];int emp_no;

    };

    struct emp d={"sat",1};

    display(d.emp_name,d.emp_no);getch();}

  • 7/30/2019 1st unit c

    49/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    display(char *name,int no){printf(" Name : %s \n No : %d",name,no);}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A structure with structure name emp is declared with two members. char

    emp_name[40]; int emp_no;5. A structure variable d is declared to access structure member variables and the

    members are assigned values. struct emp d={sat,1}

    6. Now the values are passed as arguments using structure_variable.structure_member toa function display().display(d.emp_name,d.emp_no);

    7. The function display() receives the values from structure member to the functionarguments name and no and the values are displayed using printf.

    Output :

    structure_function1.c

    #include

    #includestruct emp{char emp_name[40];int emp_no;};void main(){

  • 7/30/2019 1st unit c

    50/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    struct emp d={"sat",1};

    display(d);getch();

    }

    display(struct emp x){printf(" Name : %s \n No : %d",x.emp_name,x.emp_no);}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A structure with structure name emp is declared with two members. char

    emp_name[40]; int emp_no;5. A structure variable d is declared to access structure member variables and the

    members are assigned values. struct emp d={sat,1}6. Then the structure variable d itself passed as argument to function display()display(d); 7. In function display() the argument is received by creating a structure named x for the

    structure emp. display(struct emp x)8. Now to print values, we use,

    structure_varaible.structure_member;x.emp_name,x.emp_no

    Output :

  • 7/30/2019 1st unit c

    51/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Structure within Structure using C :-

    structure_in_structure.c

    #include

    #includevoid main(){struct family_members{char dad[20];char mom[20];int kids;};

    struct family

    {struct family_members family_name;};struct family f;printf("\n Father's Name :");scanf("%s",f.family_name.dad);

    printf("\n Mom's Name :");scanf("%s",f.family_name.mom);

    printf("\n No of Kids :");

    scanf("%d",&f.family_name.kids);

    printf("\n Daddy :%s",f.family_name.dad);printf("\n Momy :%s",f.family_name.mom);printf("\n Kids :%d",f.family_name.kids);

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A structure by name family_members is declared with 3 member variables.

  • 7/30/2019 1st unit c

    52/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    5. Another structure by name family is declared.6. Structure variable family_name for the structure family_members is declared in the 2nd

    structure family.7. Then structure variable for the structure family is declared as f.8. Now to access members of structure family_members we have to

    use,f.family_name.dad, f.family_name.mom, f.family_name.kids9. scanfis used to receive user input for members of the structure.10.And the received datas are displayed suing printf.

    Output :

    Enumeration in C :-

    Enumeration is used to create our user-defined data types.

    enum.c

    #include#includevoid main(){

    int j;enum countries{india=1,uk,usa};

    scanf("%d",&j);

  • 7/30/2019 1st unit c

    53/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    switch(j){case india:printf("\n asia");

    break;

    case uk:printf("\n europe");break;

    case usa:printf("\n north america");break;}

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A int type variablej is declared.5. A enumeration data type countries is declared with 3 members. And the 1st member

    India is assigned a value of1.6. scanfis used to receive user input forj.7. And variablej is used in switch case.8. Ifj is 1 case India will be matched and the result will be asia.9. Ifj is 2 case ukwill be matched and the result will be Europe. Similarly, north America

    ifj is 3.

    Output :

  • 7/30/2019 1st unit c

    54/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Pointers in C-

    Pointers are special variables which not only stores data to the memory but also keep track ofthose memory locations (address).

    Syntax for declaring Pointers in C :

    data_type *pointer_name;

    Pointer declarations are same as variable declaration, except that star(*) in the front of pointername,

    pointer1.c

    #include#include

    void main(){int *ptr,x=10;ptr=&x;printf("\n memory Address of X %d",&x);printf("\n memory Address of ptr %d",ptr);printf("\n %d",*ptr);getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. Pointer variable *ptr is declared and also a int variable x with value of10 is assigned.5. The memory location of variable x is stored in pointer using &. ptr=&x;6. Now printing ptr gives the memory address.7. And printing *ptr gives the value 10, which we assigned in the variable . because pointer

    *ptr is assigned the memory location of variable x.

  • 7/30/2019 1st unit c

    55/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    pointer2.c

    #include#includevoid main(){char *ptr="sat";printf("%s",ptr);getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A pointer*ptr of type charis declared and assigned a data sat.5. Now just printing ptrdisplays the entire data sat.

    Output :

  • 7/30/2019 1st unit c

    56/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Pointer as array in C :-

    pointer3.c

    #include

    #includevoid main(){int i;char *ptr[2]={"hi","bye"};for(i=0;i

  • 7/30/2019 1st unit c

    57/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Pointer as Function Arguments in C :-

    pointer4.c

    #include

    #includevoid main(){int a,b;printf("\n Enter the value of a :");scanf("%d",&a);printf("\n Enter the value of b :");scanf("%d",&b);sum(&a,&b);getch();}

    sum(int *ptr1,int *ptr2){int total;total=*ptr1+*ptr2;printf("\n Sum Value = %d",total);}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. Variable a & b of type int is declared.5. User input is received fora & b using scanf.6. Now the memory location ofa and b are passed as arguments to a function call sum().7. Back in the function sum() the memory location are received through two int type

    pointer*ptr1 & *ptr2.8. A int type variable totalis declared and assigned with result adding datas of*ptr1 &

    *ptr2 . total=*ptr1+*ptr2;9. And when total is printed the sum value of variable a+b is displayed.

  • 7/30/2019 1st unit c

    58/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Output :

    Structures using pointers in C :-

    pointer5.c

    #include#includevoid main(){struct emp{char emp_name[40];int emp_no;};

    struct emp emp_details,*ptr;

    printf("\n Enter Employee Name :");scanf("%s",&ptr->emp_name);printf("\n Enter Employee No :");scanf("%d",&ptr->emp_no);

    printf("\n Enter Employee Name : %s",ptr->emp_name);printf("\n Enter Employee No : %d",ptr->emp_no);

    getch();

    }

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

  • 7/30/2019 1st unit c

    59/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    3. main() function is the place where C program execution begins.4. A structure with structure name emp is declared with two data members emp_name[40]

    and emp_no.5. A structure pointer variable *ptr is declared to access the member inside the structure.6. Datas are received from user input using scanfand displayed using printf.

    Output :

    String Manipulation using Pointers :-

    pointer6.c

    #include#includevoid main(){

    int i;char name[20],*ptr;printf("\n Name : ");scanf("%s",&name);ptr=name;printf("\n The Name you Entered = ");while(*ptr!='\0'){printf("%c",*ptr);ptr++;}

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

  • 7/30/2019 1st unit c

    60/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A char type array name[20] and pointer*ptr are declared.5. User input is received to array name[] using scanfand the same is assigned to pointer

    ptr.6. Now a while loop is used to display all the datas in pointer using,while(*ptr!='\0'). This

    will make sure while loop runs until the last data in pointer \0 is arrived.

    Output :

    String Length using Pointers :-

    pointer7.c

    #include#includevoid main()

    {int i=0;char name[20],*ptr;printf("\n Name : ");scanf("%s",&name);ptr=name;printf("\n The Name you Entered = ");while(*ptr!='\0'){printf("%c",*ptr);ptr++;

    i++;}printf("\n Sring Length = %d",i);getch();}

  • 7/30/2019 1st unit c

    61/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() function is the place where C program execution begins.4. A int type variable i is declared and initialised with value of0.5. A char type array name[20] and pointer*ptr are declared.6. User input is received to array name[] using scanfand the same is assigned to pointer

    ptr.7. Now a while loop is used to display all the datas in pointer using,while(*ptr!='\0') 8. Inside the while loop variable i which had a initial value of0 is incremented on each

    cycle of loop.9. So when the loop cycle completes, I will have the count of characters and simply printing

    i will give us the string length.

    Output :

    String functions / Operations in C

    1) strlen() in C :This function is used to determine the length of a given string.

    Syntax :-

    variable=strlen(string);

    The string length will be returned to the variable.

    str_length.c

    #include#include#includevoid main(){

  • 7/30/2019 1st unit c

    62/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    char a[30];int l;printf("Enter a string : ");scanf("%s",&a);l=strlen(a);

    printf("\n Length of the Given String is : %d",l);

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strlen() comes under it.4. main() function is the place where C program execution begins.5. A char type array a[30] is declared.6. User input for array a is received using scanf.7. C in-built function strlen() is used to determine the length of the given string in array a

    and the result is stored in variable l.8. When variable l is printed the string length is displayed.

    Output :

    2) strcpy() in C :

    This function copies the string from one variable to another variable.

    Syntax :

    strcpy(source_variable, destination_variable);

  • 7/30/2019 1st unit c

    63/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    str_cpy.c

    #include#include#include

    void main(){char a[30],b[30];printf("Enter a string : ");scanf("%s",&a);strcpy(b,a);printf("Value of a : %s",a);printf("\nValue of b : %s",b);getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strcpy() comes under it.4. main() function is the place where C program execution begins.5. Two array of type chara[30] and b[30] are declared.6. User input is received and stored in the arrays a using scanf.7. C in-built function strcpy()is used to copy the datas from array a to array b.8. Now when the arrays a & b are displayed both displays identical values.

    Output :

    3) strncpy() in C :-

    This function also copies the string from one variable to another variable, but only upto thespecified length.

  • 7/30/2019 1st unit c

    64/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Syntax :

    strncpy(destination, source, length);

    strn_cpy.c

    #include#include#includevoid main(){char a[30],b[30];printf("Enter a string : ");scanf("%s",&a);

    strncpy(b,a,3);printf("Value of a : %s",a);printf("\nValue of b : %s",b);getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strncpy() comes under it.4. main() function is the place where C program execution begins.5. Two array of type char, a[30] and b[30] are declared.6. User input is received and stored in the arrays a using scanf.7. C in-built function strncpy()is used copy the datas from array a to array b upto a

    specified length. In this case it is 3.8. Now when the array a & b are displayed array b will have data identical to array a upto

    the length of3.

    Output :

  • 7/30/2019 1st unit c

    65/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    4) strcmp() in C :-

    This function is used to compare two strings. They are case sensitive.

    Syntax :

    strcmp(string1,string2);

    If both the strings are equal return value will be 0, else non_zero value will be returned.

    Sample program :

    str_cmp.c

    #include#include#include

    void main(){char a[30],b[30];int n;printf("Enter string one : ");scanf("%s",&a);printf("Enter string two : ");scanf("%s",&b);n=strcmp(a,b);if(n==0){

    printf("Both the Strings are Equal");}else{printf("Strings are not Equal");}getch();}

  • 7/30/2019 1st unit c

    66/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strcmp() comes under it.4. main() function is the place where C program execution begins.5. Two array of type char a[30] and b[30] are declared.6. User input is received and stored in the arrays a and b using scanf.7. C in-built function strcmp() is used to compare the values in a & b and the comparison

    result is returned to variable n.8. A ifcondition is used to check whether the returned value in variable n is 0.9. If it is 0 printfis used to display that both the strings are equal. If it is a non-zero value

    again printfis used to display that the given strings are not identical.

    Output :

    5) stricmp() in C :

    This function is also used to compare two strings but they are not case sensitive.

    Syntax :

    stricmp(string1,string2);

    stri_cmp.c

    #include#include#includevoid main(){char a[30],b[30];int n;printf("Enter string one : ");

  • 7/30/2019 1st unit c

    67/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    scanf("%s",&a);printf("Enter string two : ");scanf("%s",&b);n=stricmp(a,b);if(n==0)

    {printf("Both the Strings are Equal");}else{printf("Strings are not Equal");}getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function stricmp() comes under it.4. main() function is the place where C program execution begins.5. Two array of type char a[30] and b[30] are declared.6. User input is received and stored in the arrays a and b using scanf.7. C in-built function stricmp is used to compare the value in a & b without any match case

    and the comparison result is returned to variable n.

    Output :

    6) strncmp() in C :

    This function compares two strings only upto a specified length. They are case-sensitive.

    Syntax :

    strncmp(string1,string2,length);

  • 7/30/2019 1st unit c

    68/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    strn_cmp.c

    #include#include#include

    void main(){char a[30],b[30];int n;printf("Enter string one : ");scanf("%s",&a);printf("Enter string two : ");scanf("%s",&b);n=strncmp(a,b,3);if(n==0){

    printf("Both the Strings are Equal upto the first 3 characters");}else{printf("Strings are not Equal");}getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.2. #include is used because the C in-built function getch() comes under conio.h

    header files.3. string.h header file included because c in-built function strncmp() comes under it.4. main() function is the place where C program execution begins.5. Two array of type char a[30] and b[30] are declared.6. User input is received and stored in the arrays a and b using scanf.7. C in-built function strncamp() is used to compare the values ofa & b upto a specified

    length (i.e. 3) and the comparison result is returned to variable n.8. A ifcondition is used to check whether the returned value in variable n is 0.9. If it is 0, printfis used to display that both the strings are equal. If it is a non-zero valueagain printfis used to display that the given strings are not identical.

    Output :

  • 7/30/2019 1st unit c

    69/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    7) strnicmp() in C :-

    This function also compares two strings upto a specified length, but not case-sensitive.

    Syntax :

    strnicmp(string1,stringn,length);

    Sample program :

    strni_cmp.c

    #include#include#includevoid main()

    {char a[30],b[30];int n;printf("Enter string one : ");scanf("%s",&a);printf("Enter string two : ");scanf("%s",&b);n=strnicmp(a,b,3);if(n==0){printf("Both the Strings are Equal upto the first 3 characters");

    }else{printf("Strings are not Equal");}getch();}

  • 7/30/2019 1st unit c

    70/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strnicmp() comes under it.4. main() function is the place where C program execution begins.5. Two array of type char a[30] and b[30] are declared.6. User input is received and stored in the arrays a and b using scanf.7. C in-built function strnicmp() is used compare the values ofa & b upto a specified

    length without any match case and the comparison result is returned to variable n.8. A ifcondition is used to check whether the returned value in variable n is 0.9. If it is 0, printfis used to display that both the strings are equal. If it is a non-zero value

    again printfis used to display that the given strings are not identical.

    Output :

    8) strlwr() in C :-

    This function converts uppercase characters to lowercase.

    Syntax :

    strlwr(string);

    str_lwr.c

    #include#include#includevoid main(){char a[30];printf("Enter a string in uppercase : ");

  • 7/30/2019 1st unit c

    71/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    scanf("%s",&a);

    printf("RESULT : %s",strlwr(a));

    getch();

    }

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strlwr() comes under it.4. main() function is the place where C program execution begins.5. A char type array a[30] is declared.6. User input for array a is received using scanf.7. C in-built function strlwr() is used to display the given string in lower case.

    Output :

    9) strupr() in C :-

    This function converts lowercase characters to uppercase.

    Syntax :

    strupr(string);

    str_upr.c

    #include#include#includevoid main(){char a[30];printf("Enter a string in lowercase : ");

  • 7/30/2019 1st unit c

    72/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    scanf("%s",&a);

    printf("RESULT : %s",strupr(a));

    getch();

    }

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strupr() comes under it.4. main() function is the place where C program execution begins.5. A char type array a[30] is declared.6. User input for array a is received using scanf.7. C in-built function strupr() is used to display the given string in upper case.

    Output :

    10) strdup() in C :-

    This function is used to duplicate a string to a pointer variable by allocating the memory locationof the string.

    Syntax :

    pointer=strdup(string);

    str_dup.c

    #include#include#includevoid main(){

  • 7/30/2019 1st unit c

    73/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    char a[30],*b;printf("Enter a string : ");scanf("%s",&a);b=strdup(a);printf("Entered String in a : %s",a);

    printf("\nDuplicated string : %s",b);

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strdup() comes under it.4. main() function is the place where C program execution begins.5. A char type array a and char type pointer variable *b are declared.6. User Input for array a is received using scanf.7. C in-built function strdup() is used to duplicate the datas in a to b.8. Now when array and pointer variable *b are displayed, they both have identical datas.

    Output :

    11) strcat() in C :-

    This function is used to join (concatenate) two strings.

    Syntax :

    strcat(string1,string2);

    str_cat.c

  • 7/30/2019 1st unit c

    74/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    #include#include#includevoid main(){

    char a[30],b[30],c[30];printf("Enter string one : ");scanf("%s",&a);printf("Enter string two : ");scanf("%s",&b);strcat(a,b);

    printf("Concatinated String : %s",a);

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strcat() comes under it.4. main() function is the place where C program execution begins.5. Two array of type char a[30] and b[30] are declared.6. User Input is received and stored in the arrays a and b using scanf.7. C in-built function strcat() is used to join the two strings(data) from array variable a & b.8. When the array a is printed the concatenated string is displayed.

    Output :

    13) strrev() in C :-This function is sued to reverse the characters in a given string.

    Syntax :

    strrev(string);

  • 7/30/2019 1st unit c

    75/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    str_rev.c

    #include#include#include

    void main(){char a[30];printf("Enter string : ");scanf("%s",&a);strrev(a);

    printf("Reversed String : %s",a);

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strrev() comes under it.4. main() function is the place where C program execution begins.5. A char type array a[30] is declared.6. scanfis used to receive user input to array a.7. Then C in-built function strrev() is used to receive the string in array a and the same isdisplayed using printf.

    Output :

    14) strset() in C :-

    This function replaces all the characters of a string with a given symbol or character.

    Syntax :

    strset(string,symbol);

  • 7/30/2019 1st unit c

    76/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    str_set.c

    #include#include#include

    void main(){char a[30];char b;

    printf("Enter a string: ");gets(a);printf("Enter a symbol to replace the string : ");scanf("%c",&b);

    strset(a,b);

    printf("After strset : %s",a);

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strset() comes under it.4. main() function is the place where C program execution begins.5. A char type array a[30] is declared.6. A variable b of type char is declared.7. gets() is used to receive user input for array a.8. scanfis used to receive a character symbol to variable b.9. C in-built function strset() is used to replace all the characters in array a with symbol

    received in variable b.

    Output :

  • 7/30/2019 1st unit c

    77/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    15) strnset() in C :-

    This function also replaces the characters of a string with a given symbol but only to a specifiedlength.

    strnset(string,symbol,n);

    strn_set.c

    #include#include#includevoid main(){

    char a[30];char b;

    printf("Enter a string: ");gets(a);printf("Enter a symbol to replace the string : ");scanf("%c",&b);

    strnset(a,b,2);

    printf("After strset : %s",a);

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

  • 7/30/2019 1st unit c

    78/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. string.h header file included because c in-built function strnset() comes under it.4. main() function is the place where C program execution begins.5. A char type array a[30] is declared.6. A variable b of type char is declared.7. gets() is used to receive user input for array a.8. scanfis used to receive a character symbol to variable b.9. C in-built function strnset() is used to replace the character in array a with symbol

    received in variable b upto a specified length. In this case it is 2.

    Output :

    Dynamic Memory Allocations in C

    1) Malloc in C :-

    malloc() is used to allocate memory space in bytes for variables of any valid C data type.

    Syntax :

    pointer= (data_type*)malloc(user_defined_size);

    malloc.c

    #include

    #include#includevoid main(){int a,*ptr;a=10;ptr=(int*)malloc(a*sizeof(int));

  • 7/30/2019 1st unit c

    79/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    ptr=a;printf("%d",ptr);free(ptr);getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. stdlib.h is used because malloc() comes under it.4. int type variable a and pointer*ptr are declared.5. Variable a is assigned a value of10.6. malloc() is used to allocate memory to pointerptr.7. The size given through malloc() to ptr is sizeof(int).8. Now ptr is assigned the value ofa. ptr=a; so the value 10 is assigned to ptr, for which,

    we dynamically allocated memory space using malloc.9. The value in ptr is displayed using printf10.Then allocated memory is freed using the C in-built function free().

    Output :

    2) Calloc in C :-

    calloc() is sued to allocate multiple blocks of memory dynamically during the execution (run-time) of the program.

    Syntax :

    pointer=(data_type*)calloc(no of memory blocks, size of each block inbytes);

    calloc.c

    #include

  • 7/30/2019 1st unit c

    80/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    #include#includevoid main(){int *ptr,a[6]={1,2,3,4,5,6};

    int i;ptr=(int*)calloc(a[6]*sizeof(int),2);for(i=0;i

  • 7/30/2019 1st unit c

    81/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    #define in C :It is used to predefine a string for a identifier.

    Syntax :

    #define identifier string

    define.c#include#include

    #define N 10#define stop() getch()#define show printf#define getme scanfvoid main(){int a;

    show("Enter a No : ");getme("%d",&a);

    if(a>N){show("The Entered No is greater than 10..");}else{show("The No u have Entered is Less than 10..");}

    stop();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. Macro N is defined a value of10.4. stop() is defined by C in-build function getch().5. show is defined by C in-build statement printf.6. getme is defined by C in-build statement scanf.7. main () function is the place where C program execution begins.8. int type variable a is declared9. show in the printfis used to prompt the user to enter input data.10.They are received in variable a using macro getme in the place ofprintf.11.A ifcondition is used to checka>N (i.e) a>10

  • 7/30/2019 1st unit c

    82/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    12.If the entered value is greater than 10show is used to display The Entered No is greaterthan 10

    13.Else the display The No u have Entered is less than 10.14.Now Macro stop() is used in the place ofgetch() to wait for user key press.

    Output :

    header files in C :

    header files are used to include pre-built functions in our c programs. There are two types ofheader files.

    1. C in-built header files.2. C user defined header files.

    Header files like stdio.h, string.h are in-built headers in C.User defined header files are createdby the programmer itself.

    header.c

    #include#include#include "add.h"void main(){int a,b;

    printf("\n Enter 2 nos to add : ");scanf("%d%d",&a,&b);

    sum(a,b);

    getch();}

  • 7/30/2019 1st unit c

    83/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    add.h

    #includevoid sum(int x,int y){

    int z;z=x+y;printf("Sum Result : %d",z);}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. A user defined header file add.h is included.4. main() is the place where the program execution begins.5. Two int type variable a & b are declared.6. scanfis used to receive user input fora & b.7. the function call is made with user-defined function sum() with two arguments a & b.8. function sum() is pre-written in add.h header file.9. A int type variable z is declared inside function sum()10.Both the arguments are received to function sum() through the arguments x & y.11.They are added and result is stored in z.12.And displayed using printf.

    Output :

    #ifdef in C :

    #ifdef is used to check whether a identifier is assigned a value.

    Syntax :

  • 7/30/2019 1st unit c

    84/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    #ifdef identifier{statements;}#else

    {statements;}#endif

    #undef in C :Sometimes we have to restrict the defined macros to some part/module of ourprogram. #undef is used to undefined a defined macro.

    Syntax :

    #undef identifier

    ifdef_undef.c

    #include#include

    #define N 100

    #ifdef N#undef N

    #define N 10#endif

    void main(){printf("%d",N);getch();}

    Program Algorithm / Explanation :

    1.

    #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.2. #include is used because the C in-built function getch() comes under conio.h

    header files.3. Macro N is defined a value of100.4. ifdefis used to check if N is defined. #ifdef N5. If it is defined N is undefined using #undef N6. And N is again defined this time with value of10.

  • 7/30/2019 1st unit c

    85/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    7. main() is the place where the program execution starts.8. printfis sued to display N and the result is 10.

    Output :

    typedef in C :-

    We can define our own data types(user defined datatyes) from C in-built datatypes.

    Syntax :

    typedef in-built-datatype user-defined-datatype;

    typedef.c

    #include#include

    void main(){

    typedef int nos;typedef char alpha;

    nos n;n=5;alpha a[10]="hellow";printf(" %d \n %s",n,a);

    getch();}

    Program Algorithm / Explanation :

    1. #include header file is included because, the C in-built statement printfweused in this program comes under stdio.h header files.

  • 7/30/2019 1st unit c

    86/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    2. #include is used because the C in-built function getch() comes under conio.hheader files.

    3. main() is the place where the program execution begins.4. Data type int is defined to nos.5. Data type char is defined to alpha.6. Now variable n is declared of type nos and assigned a value of5.7. Also array a[0] of type alphais declared and assigned a value of hellow8. Now n & nos are displayed using printf.

    Output :

    Command Line Arguments in C :-Command line arguments are used to pass values asarguments to the main() function of a C Program from the command line itself.

    comd.c

    #include

    main(int argc,int *argv[]){int i;printf("No of arguments %d",argc);for(i=0;i

  • 7/30/2019 1st unit c

    87/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    4. argc holds the total number of arguments received from command line and argv[]holds the actual arguments itself.

    5. int type variable i is declared.6. printfis used to display argc, which returns the number of arguments received from

    command line.

    7. for loop is used to display all the arguments received in argv[].Output :

    Files in C

    Files are used to store datas in the secondary memory(eg:- hard disk, floppy, flash disketc).There are various file operations that can be done in C like Creating a file, deleting a file,renaming a file, opening a file to read/write/append datas etc.We can use FILE pointers tonavigate through various records in a file.Before doing any operations on a file, we have todeclare a file pointer first.

    Syntax for declaring a file pointer in C

    FILE *file_pointer;

    Eg :- FILE *fp;

    Where,FILE = keyword*fp = user defined file pointer variable.

    Once the file pointer is declared next step is to create/open a file.

    Creating / opening a file in C

    fopen() is used to open a specified file from disk, if it exist. If it doesnt exist a new file will becreated and opened for further file operations.

  • 7/30/2019 1st unit c

    88/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Syntax for fopen() in C

    fp=fopen(file_name with extension,mode);

    Where,fp= user defined file pointer variable.filename= name of the file with file type as extension.mode= mode in which the file is to be opened.

    Eg :-To Readr, To Write - w, To Append aTo Read & Writew+, To Read and write r+To Read Write with appenda+

    In w+ mode the contents in existing file is destroyed and then can perform read/write

    operations.In r+ mode just read and write operations can be performed.In a+ mode we canperform read and write operations with appending contents. So no existing datas in a file are

    destroyed.Example:-fp=fopen(data.txt,a+);After a file is opened, we have to perform read orwrote operations into it.

    Writing to a file in C:-

    fprintf()

    fprintf() is used to write datas to a file from memory.

    Syntax for fprintf()

    fprintf(file pointer,control string,variables);

    example:- fprintf(fp,%s,name);

    Reading from a file in C

    fscanf() is used to read data from a file to the memory.

    Syntax for fscanf()

    fscanf(file pointer,control string,variables);

    eg:- fscanf(fp,%s,name);

    Closing a file in C

  • 7/30/2019 1st unit c

    89/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    fclose() is used to close a file in C.

    Syntax for fclose()

    fclose(fp);

    Where, fp= user-defined file pointer.

    Reading and Writing to a file in C

    Sample Program :

    fprintf_fscanf.c

    #include

    #include

    void main(){FILE *fp;char c[60];int no,n;fp=fopen("data2.txt","a+");

    printf("Enter the Employee Name and No : ");scanf("%s %d",c,&no);

    fprintf(fp,"\n\n%s\n%d",c,no);

    rewind(fp);

    printf("Enter the Employee No : ");scanf("%d",&n);while(!feof (fp)){fscanf(fp,"%s %d",c,&no);if(no==n){

    printf("\n%s \n %d",c,no);}}fclose(fp);getch();}

    Output :

  • 7/30/2019 1st unit c

    90/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    Program Algorithm / Explanation

    1. #include header file is included because, the C in-built statement printf weused in this program comes understdio.h header files.

    2. #include is used because the C in-built function getch() comes underconio.hheader files.

    3. main () function is the place where C program execution begins.4. A file pointer variable *fp is declared.5. A char type array c[60] is declared along with two int type variables no & n.6. fopen()is used to open the file data2.txt in append mode along with read/write

    permissions using a+ (append mode).7. scanf() is used to receive the employee name and no to variable c & no from user input.8. Now received datas are stored in the file using fprintf().9. Now rewind(fp) is used to move the file pointer to the top of the file.10.scanf() is used to receive the employee no and a while statement is used to search for the

    corresponding employee record in the file.11.fscanf() is used to read the records from the file and they are compared with employee

    number from user input.12.If it matches, the particular employee record is displayed using printf.

    Writing Character by Character to a file in C:-

    fputc.c

    #include#include

    void main(){

    FILE *fp;char c;fp=fopen("data.txt","w");

    printf("Enter datas to save inside the file 'data.txt' and press '~' to

    stop writing \n");

    while(c!='~')

  • 7/30/2019 1st unit c

    91/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    {c=getche();fputc(c,fp);}fclose(fp);

    }

    Output :

    Program Algorithm / Explanation

    1. #include header file is included because, the C in-built statement printf weused in this program comes understdio.h header files.

    2. #include is used because the C in-built function getch() comes underconio.hheader files.

    3. main () function is the place where C program execution begins.4. A file pointer variable *fp is declared.5. A char type variable c is declared.6. fopen() is used to open the file in write mode.7. While loop is used to run until the symbol ~ is interrupted.8. Inside while loop, getche() is used to receive user input and stored in variable c.9. The character stored in variable c is written to the file using fputch().10.And fclose() is used to close the opened file.

    Reading Character by Character from a file in C:-

    getc.c

    #include#include

    void main(){FILE *fp;char c;fp=fopen("data.txt","r");

    rewind(fp);

  • 7/30/2019 1st unit c

    92/152

    206 FUNDAMENTAL OF COMPUTER PROGRAMMING

    while(!feof (fp)){printf("%c",getc(fp));}

    fclose(fp);getch();}

    Output :

    Program