The document provides an overview of the basic structure and components of a C program. It discusses that every C program has the following general structure: comments, preprocessing commands, global declarations, the main function, local declarations within main, executable statements, and user-defined functions. It also summarizes some key elements of C including data types, variables, constants, operators, and tokens.
C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup
at AT and T Bell Laboratories USA, in the early 1980’s. Stroustrup, an admirer of
Simula67 and a strong supporter of C wanted to combine the best of both the languages
and create a more powerful language that could support object-oriented programming
features and still retain the power and elegance of C. The result was C++
The document provides information about C programming language and its features. It discusses the basic structure of a C program which includes documentation, link, definition, global declaration, main function, and sub-program sections. It also describes the four steps to execute a C program: create, compile, link, and execute. Different forms of the main statement in C are discussed including main(), main(void), int main(), void main(), void main(void), and int main(void).
The document discusses the two-pass approach for compiler construction. The first pass analyzes the source code and generates an intermediate representation (IR) including symbol tables. The second pass analyzes the IR to perform code synthesis for the target program. The front end performs lexical, syntax and semantic analysis to build the IR. The back end performs memory allocation and code generation based on the target architecture.
The document provides an introduction to the C programming language. It discusses the structure of a C program including character set, tokens, identifiers, reserved words, comments, data types, constants, variables, operators, expressions, statements, functions, and how to convert an algorithm into a C program. It then discusses why C is commonly used, its features such as being robust, portable, supporting dynamic memory allocation, and being efficient and fast. The document outlines the advantages and disadvantages of C and valid steps in a C program. Finally, it provides details on the typical structure of a C program which includes documentation, linking, definitions, global declarations, the main function, and subprograms.
C# (pronounced “see sharp” or “C Sharp”) is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002
This document discusses nested macros in system programming. It defines a macro as a unit of program specification that allows code expansion. A macro can contain a call to another macro, known as a nested macro call. Nested macro calls are expanded following the LIFO (last-in-first-out) rule, where the innermost macro call is expanded first. The document provides an example of a nested macro call in C code and how the macros would expand to generate the final code.
This document summarizes key concepts from an introduction to C++ programming chapter, including:
- The main parts of a C++ program are comments, preprocessor directives, the main() function, and statements.
- Variables are used to store and manipulate data in a program. Variables are declared with a name and type before use.
- Arithmetic operators allow performing calculations in C++ programs. Expressions follow order of operations rules.
- Input and output streams allow getting user input and displaying output to the screen.
The document provides information about C language and its features. It discusses that C was developed by Dennis Ritchie in 1972 and is a general purpose programming language well suited for business and scientific applications. It also summarizes the basic structure of a C program and describes various C language components like data types, operators, and conditional statements.
C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup
at AT and T Bell Laboratories USA, in the early 1980’s. Stroustrup, an admirer of
Simula67 and a strong supporter of C wanted to combine the best of both the languages
and create a more powerful language that could support object-oriented programming
features and still retain the power and elegance of C. The result was C++
The document provides information about C programming language and its features. It discusses the basic structure of a C program which includes documentation, link, definition, global declaration, main function, and sub-program sections. It also describes the four steps to execute a C program: create, compile, link, and execute. Different forms of the main statement in C are discussed including main(), main(void), int main(), void main(), void main(void), and int main(void).
The document discusses the two-pass approach for compiler construction. The first pass analyzes the source code and generates an intermediate representation (IR) including symbol tables. The second pass analyzes the IR to perform code synthesis for the target program. The front end performs lexical, syntax and semantic analysis to build the IR. The back end performs memory allocation and code generation based on the target architecture.
The document provides an introduction to the C programming language. It discusses the structure of a C program including character set, tokens, identifiers, reserved words, comments, data types, constants, variables, operators, expressions, statements, functions, and how to convert an algorithm into a C program. It then discusses why C is commonly used, its features such as being robust, portable, supporting dynamic memory allocation, and being efficient and fast. The document outlines the advantages and disadvantages of C and valid steps in a C program. Finally, it provides details on the typical structure of a C program which includes documentation, linking, definitions, global declarations, the main function, and subprograms.
C# (pronounced “see sharp” or “C Sharp”) is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002
This document discusses nested macros in system programming. It defines a macro as a unit of program specification that allows code expansion. A macro can contain a call to another macro, known as a nested macro call. Nested macro calls are expanded following the LIFO (last-in-first-out) rule, where the innermost macro call is expanded first. The document provides an example of a nested macro call in C code and how the macros would expand to generate the final code.
This document summarizes key concepts from an introduction to C++ programming chapter, including:
- The main parts of a C++ program are comments, preprocessor directives, the main() function, and statements.
- Variables are used to store and manipulate data in a program. Variables are declared with a name and type before use.
- Arithmetic operators allow performing calculations in C++ programs. Expressions follow order of operations rules.
- Input and output streams allow getting user input and displaying output to the screen.
The document provides information about C language and its features. It discusses that C was developed by Dennis Ritchie in 1972 and is a general purpose programming language well suited for business and scientific applications. It also summarizes the basic structure of a C program and describes various C language components like data types, operators, and conditional statements.
The document discusses the evolution of programming languages from machine languages to higher-level languages. It begins with an overview of the three main categories: machine languages, assembly languages, and higher-level languages. It then provides more details on each category, explaining that machine languages use binary, assembly languages use cryptic phrases, and higher-level languages use more English-like syntax. It specifically discusses third-generation languages as the first to use true English phrases.
The document discusses the design and implementation of the second pass of a two-pass assembler. It explains that a two-pass assembler handles forward references easily by building a symbol table in the first pass and then using it to synthesize the target program in the second pass. The first pass constructs an intermediate representation using the symbol table, which the second pass then processes to generate the target code. The algorithm for the second pass is described, which involves processing the intermediate representation and writing the target code to an output file.
The document discusses language processor development tools (LPDTs) like LEX and YACC that are used to generate the analysis phase of a compiler. LEX is a lexical analyzer generator that takes a specification of lexical units and actions to produce a scanner. YACC is a parser generator that takes a grammar specification and actions to produce a parser. These tools generate C programs for scanning and parsing along with semantic actions. An example LEX program is provided to recognize keywords, identifiers, numbers and operators in an input stream.
This document introduces key concepts in Java programming including data types, identifiers, variable declarations, constants, comments, arithmetic operations, input/output, and the Scanner and JOptionPane classes. It defines identifiers as names for classes, methods, and variables that must start with a letter or underscore. It describes primitive and non-primitive data types. It explains that variables store values in memory locations and are declared with a type and name. Constants are variables that cannot change value once assigned. Comments are used to explain code. The Scanner class reads input and JOptionPane displays dialog boxes.
This document discusses macros in system programming. It defines a macro as a unit of specification for program generation through expansion. A macro definition consists of a macro prototype statement, model statements, and preprocessor statements. A macro is called by writing its name in an assembly statement's mnemonic field along with actual parameters. During macro expansion, the macro call statement is replaced by a sequence of assembly code generated from the model statements with formal parameters replaced by actual parameters. There are two types of expansions - lexical expansion replaces character strings, while semantic expansion can generate different code depending on parameter usage. An example demonstrates defining, calling, and expanding a simple macro in C.
The document discusses the basic elements of a Java program, including methods, identifiers, data types, expressions, input/output statements, and packages. It covers primitive data types like int and float, arithmetic operators, strings, variables, and how to write a simple Java application program. The chapter objectives are to familiarize readers with these core programming concepts in Java.
C is a general purpose programming language developed in the 1970s. It has features like control structures, looping statements, and arrays that make it well-suited for business and scientific applications. A C program executes in four steps - creating the program, compiling it, linking it to libraries, and executing the final executable file. C has keywords, variables, data types, operators, and conditional statements that allow for structured programming and control flow.
C is a general-purpose programming language developed in the early 1970s. It was designed to be compiled using a minimal compiler for portability. C is still widely used today due to its speed, flexibility and ability to access low-level hardware which makes it suitable for system programming tasks like operating systems, language compilers, databases etc. The document provides an overview of the history and evolution of C, why it is still useful, basic C programming concepts like variables, data types, expressions and operators.
This document provides 50 interview questions on C programming language organized into 5 chapters: Variables & Control Flow, Operators, Constants & Structures, Functions, Pointers, and Programs. It aims to help both freshers and experienced programmers quickly brush up on basic C concepts commonly asked during job interviews at top companies. Each question is accompanied by a detailed answer along with code examples where applicable. Feedback is welcomed to be sent to the publisher.
C programming Training in Ambala ! Batra Computer Centrejatin batra
Batra Computer Centre is An ISO certified 9001:2008 training Centre in Ambala.
We Provide C Programming Training in Ambala. BATRA COMPUTER CENTRE provides best training in C, C++, S.E.O, Web Designing, Web Development and So many other courses are available.
The document discusses the C programming language and data structures. It covers the basic structure of C programs, data types, operators, control flow statements, arrays, strings, functions, pointers, structures, unions and file I/O. The chapters are outlined and key concepts like algorithms, flowcharts and program development steps are explained in detail. The history and evolution of C language is presented along with its features, applications and importance. A simple C program example is also provided and analyzed.
This document provides an overview of the C programming language, including its history, features, data types, control characters, input/output functions, and examples. It discusses how C was created at Bell Labs as a portable, general-purpose language suitable for system programming. The document also covers C keywords, character sets, compiling and executing C programs, functions, libraries, and standardization.
The document discusses the steps involved in executing a program written in language L. These steps include translation, linking, relocation, and loading. The translator outputs an object module, which contains program code, relocation tables, and linking tables. The linker processes multiple object modules, relocating addresses and resolving external references to produce an executable binary program. It builds a name table containing symbols and their loaded addresses. This allows the linker to modify address operands to point to the correct memory locations for program execution.
The document describes the unique features of the C++ and PHP programming languages. It discusses the history of C++, which was created by Bjarne Stroustrup in 1979 by adding object-oriented programming capabilities to the C language. Some key features of C++ include performance, low-level hardware interaction capabilities, powerful abstractions like generic code, and support for multiple programming paradigms like object-oriented, imperative, functional and logic programming. The document also provides examples of code written in C++ to illustrate various programming concepts.
The document provides an introduction to the C programming language including:
- The C development environment and how a program is compiled from source code to executable code
- A simple "Hello World" example program
- Key elements of a C program like comments, preprocessor directives, data types, and basic functions like printf()
- Details on tokens, variables, statements, and basic data types and functions in C
The document provides an overview of the basic structure and syntax of C# programs. It discusses that a C# program consists of namespaces, classes, methods, attributes, and other elements. It then presents a simple "Hello World" program as an example to demonstrate these core components. The document also introduces some basic C# syntax like data types, identifiers, and keywords. It provides examples of defining a class with attributes and methods to illustrate how objects are represented in C#.
The document discusses the role of CLR (Common Language Runtime) in .NET framework. It explains that CLR converts programs to native code, handles exceptions, provides type safety, memory management, security, improved performance and is language and platform independent. It also discusses garbage collection and language features supported by CLR. The main components of CLR are CTS (Common Type System), JIT (Just-In-Time) compiler and CLS (Common Language Specification). CTS defines value and reference types while JIT compiles CIL to machine code. CLS provides language interoperability.
This document provides an introduction to the C programming language. It discusses that C was created to develop the UNIX operating system and is widely used for systems programming. The document then covers C program structure, tokens, basic syntax, identifiers, keywords, whitespace, data types including integer and floating point types, variables, and variable scope and storage duration. It provides examples of declaring, defining, initializing and using different variables in a sample C program.
The document provides information about C programming language. It was prepared by Chetan Thapa Magar of Brightland Higher Secondary College. C was created by Dennis Ritchie in 1972 and draws concepts from earlier languages like BCPL and B. C is portable, efficient, structured, and a middle-level language well-suited for system and application programming. The document discusses C's history, elements, data types, operators, control structures like loops and decisions, and provides some example programs.
This document provides an overview of C programming basics and features. It discusses problem solving techniques like algorithms, flowcharts, and pseudo codes. It then introduces C programming, highlighting its features like portability and support for data types. It describes the typical structure of a C program including preprocessor directives, global declarations, the main function, and subprograms. It also covers the compilation and linking process. Finally, it discusses key concepts like variables, identifiers, keywords, and integer, floating point, character, and string constants.
C programming language tutorial for beginers.pdfComedyTechnology
This document provides an introduction and overview of the basics of C programming language. It discusses the following key topics in 3 or less sentences each:
- Introduction to programming and computer languages.
- Introduction to C programming, its history, uses, and why it is widely used.
- Program structure in C, including main functions, printf statements, comments, and return values.
- Basic syntax rules in C including semicolons, comments, identifiers, and whitespace.
- Common data types in C like char, int, float, and double and their purposes.
- How variables are named, defined through data type declaration, and initialized in C code.
- Common operators in
The document discusses the evolution of programming languages from machine languages to higher-level languages. It begins with an overview of the three main categories: machine languages, assembly languages, and higher-level languages. It then provides more details on each category, explaining that machine languages use binary, assembly languages use cryptic phrases, and higher-level languages use more English-like syntax. It specifically discusses third-generation languages as the first to use true English phrases.
The document discusses the design and implementation of the second pass of a two-pass assembler. It explains that a two-pass assembler handles forward references easily by building a symbol table in the first pass and then using it to synthesize the target program in the second pass. The first pass constructs an intermediate representation using the symbol table, which the second pass then processes to generate the target code. The algorithm for the second pass is described, which involves processing the intermediate representation and writing the target code to an output file.
The document discusses language processor development tools (LPDTs) like LEX and YACC that are used to generate the analysis phase of a compiler. LEX is a lexical analyzer generator that takes a specification of lexical units and actions to produce a scanner. YACC is a parser generator that takes a grammar specification and actions to produce a parser. These tools generate C programs for scanning and parsing along with semantic actions. An example LEX program is provided to recognize keywords, identifiers, numbers and operators in an input stream.
This document introduces key concepts in Java programming including data types, identifiers, variable declarations, constants, comments, arithmetic operations, input/output, and the Scanner and JOptionPane classes. It defines identifiers as names for classes, methods, and variables that must start with a letter or underscore. It describes primitive and non-primitive data types. It explains that variables store values in memory locations and are declared with a type and name. Constants are variables that cannot change value once assigned. Comments are used to explain code. The Scanner class reads input and JOptionPane displays dialog boxes.
This document discusses macros in system programming. It defines a macro as a unit of specification for program generation through expansion. A macro definition consists of a macro prototype statement, model statements, and preprocessor statements. A macro is called by writing its name in an assembly statement's mnemonic field along with actual parameters. During macro expansion, the macro call statement is replaced by a sequence of assembly code generated from the model statements with formal parameters replaced by actual parameters. There are two types of expansions - lexical expansion replaces character strings, while semantic expansion can generate different code depending on parameter usage. An example demonstrates defining, calling, and expanding a simple macro in C.
The document discusses the basic elements of a Java program, including methods, identifiers, data types, expressions, input/output statements, and packages. It covers primitive data types like int and float, arithmetic operators, strings, variables, and how to write a simple Java application program. The chapter objectives are to familiarize readers with these core programming concepts in Java.
C is a general purpose programming language developed in the 1970s. It has features like control structures, looping statements, and arrays that make it well-suited for business and scientific applications. A C program executes in four steps - creating the program, compiling it, linking it to libraries, and executing the final executable file. C has keywords, variables, data types, operators, and conditional statements that allow for structured programming and control flow.
C is a general-purpose programming language developed in the early 1970s. It was designed to be compiled using a minimal compiler for portability. C is still widely used today due to its speed, flexibility and ability to access low-level hardware which makes it suitable for system programming tasks like operating systems, language compilers, databases etc. The document provides an overview of the history and evolution of C, why it is still useful, basic C programming concepts like variables, data types, expressions and operators.
This document provides 50 interview questions on C programming language organized into 5 chapters: Variables & Control Flow, Operators, Constants & Structures, Functions, Pointers, and Programs. It aims to help both freshers and experienced programmers quickly brush up on basic C concepts commonly asked during job interviews at top companies. Each question is accompanied by a detailed answer along with code examples where applicable. Feedback is welcomed to be sent to the publisher.
C programming Training in Ambala ! Batra Computer Centrejatin batra
Batra Computer Centre is An ISO certified 9001:2008 training Centre in Ambala.
We Provide C Programming Training in Ambala. BATRA COMPUTER CENTRE provides best training in C, C++, S.E.O, Web Designing, Web Development and So many other courses are available.
The document discusses the C programming language and data structures. It covers the basic structure of C programs, data types, operators, control flow statements, arrays, strings, functions, pointers, structures, unions and file I/O. The chapters are outlined and key concepts like algorithms, flowcharts and program development steps are explained in detail. The history and evolution of C language is presented along with its features, applications and importance. A simple C program example is also provided and analyzed.
This document provides an overview of the C programming language, including its history, features, data types, control characters, input/output functions, and examples. It discusses how C was created at Bell Labs as a portable, general-purpose language suitable for system programming. The document also covers C keywords, character sets, compiling and executing C programs, functions, libraries, and standardization.
The document discusses the steps involved in executing a program written in language L. These steps include translation, linking, relocation, and loading. The translator outputs an object module, which contains program code, relocation tables, and linking tables. The linker processes multiple object modules, relocating addresses and resolving external references to produce an executable binary program. It builds a name table containing symbols and their loaded addresses. This allows the linker to modify address operands to point to the correct memory locations for program execution.
The document describes the unique features of the C++ and PHP programming languages. It discusses the history of C++, which was created by Bjarne Stroustrup in 1979 by adding object-oriented programming capabilities to the C language. Some key features of C++ include performance, low-level hardware interaction capabilities, powerful abstractions like generic code, and support for multiple programming paradigms like object-oriented, imperative, functional and logic programming. The document also provides examples of code written in C++ to illustrate various programming concepts.
The document provides an introduction to the C programming language including:
- The C development environment and how a program is compiled from source code to executable code
- A simple "Hello World" example program
- Key elements of a C program like comments, preprocessor directives, data types, and basic functions like printf()
- Details on tokens, variables, statements, and basic data types and functions in C
The document provides an overview of the basic structure and syntax of C# programs. It discusses that a C# program consists of namespaces, classes, methods, attributes, and other elements. It then presents a simple "Hello World" program as an example to demonstrate these core components. The document also introduces some basic C# syntax like data types, identifiers, and keywords. It provides examples of defining a class with attributes and methods to illustrate how objects are represented in C#.
The document discusses the role of CLR (Common Language Runtime) in .NET framework. It explains that CLR converts programs to native code, handles exceptions, provides type safety, memory management, security, improved performance and is language and platform independent. It also discusses garbage collection and language features supported by CLR. The main components of CLR are CTS (Common Type System), JIT (Just-In-Time) compiler and CLS (Common Language Specification). CTS defines value and reference types while JIT compiles CIL to machine code. CLS provides language interoperability.
This document provides an introduction to the C programming language. It discusses that C was created to develop the UNIX operating system and is widely used for systems programming. The document then covers C program structure, tokens, basic syntax, identifiers, keywords, whitespace, data types including integer and floating point types, variables, and variable scope and storage duration. It provides examples of declaring, defining, initializing and using different variables in a sample C program.
The document provides information about C programming language. It was prepared by Chetan Thapa Magar of Brightland Higher Secondary College. C was created by Dennis Ritchie in 1972 and draws concepts from earlier languages like BCPL and B. C is portable, efficient, structured, and a middle-level language well-suited for system and application programming. The document discusses C's history, elements, data types, operators, control structures like loops and decisions, and provides some example programs.
This document provides an overview of C programming basics and features. It discusses problem solving techniques like algorithms, flowcharts, and pseudo codes. It then introduces C programming, highlighting its features like portability and support for data types. It describes the typical structure of a C program including preprocessor directives, global declarations, the main function, and subprograms. It also covers the compilation and linking process. Finally, it discusses key concepts like variables, identifiers, keywords, and integer, floating point, character, and string constants.
C programming language tutorial for beginers.pdfComedyTechnology
This document provides an introduction and overview of the basics of C programming language. It discusses the following key topics in 3 or less sentences each:
- Introduction to programming and computer languages.
- Introduction to C programming, its history, uses, and why it is widely used.
- Program structure in C, including main functions, printf statements, comments, and return values.
- Basic syntax rules in C including semicolons, comments, identifiers, and whitespace.
- Common data types in C like char, int, float, and double and their purposes.
- How variables are named, defined through data type declaration, and initialized in C code.
- Common operators in
The document provides an introduction to the C programming language. It discusses the structure of a C program including documentation, preprocessor directives, header files, and function definitions. It also describes various math and trigonometric functions available in the standard library like sqrt, pow, sin, cos, and log. The rest of the document outlines the steps to compile and execute a C program and defines key concepts like variables, constants, and data types in C.
Unit-2_Getting Started With ‘C’ Language (3).pptxSanketShah544615
The document provides information about getting started with the C programming language. It discusses the key features of C including that it is a general-purpose, procedural language developed in the 1970s as a successor to B. The document then outlines the typical structure of a C program including documentation, definitions, global declarations, the main function, and subprograms. It also discusses how a C program executes through compilation, linking, and loading. Finally, it covers C language fundamentals like tokens, keywords, identifiers, and data types.
unit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshuGauravRawat830030
Computer systems consist of hardware and software. System software manages hardware components and includes device drivers, operating systems, servers, and utilities. Programming software provides tools to assist programmers. Application software aids tasks through business, design, databases, and other programs. There are low-level languages close to machine code like machine language and assembly language and high-level languages like C that are closer to English. Creating and running a C program involves writing code, compiling it, linking, loading, and executing the program.
C is a general-purpose programming language developed at Bell Labs in the 1970s. It discusses the basics of C programming, including its history, structure, keywords, variables, data types, and provides an example "Hello World" program. The document provides an overview of the key elements of C for a beginner programmer to understand how to get started with C.
The document provides an introduction to algorithms and key concepts related to algorithms such as definition, features, examples, flowcharts, pseudocode. It also discusses different types of programming languages from first to fifth generation. Key points of structured programming approach and introduction to C programming language are explained including data types, variables, constants, input/output functions, operators, type conversion etc.
The document provides information on the C programming language, including its history, structure, and key concepts. It discusses how C was developed at Bell Labs in the 1970s and influenced by other languages. It also describes the basic structure of C programs, which typically include header files, main functions, and statements organized into functions. The document also covers important C concepts like data types, variables, constants, and tokens.
C programming is a general-purpose language developed in the 1970s to write operating systems like UNIX. It is one of the most widely used languages, particularly for systems programming. Some key facts: C was created to develop UNIX and is still widely used for operating systems, compilers, databases and other modern programs. It has various data types like integers, floats, characters, arrays and structures. Variables are defined with a data type and can be initialized. C code is written in files with a .c extension and preprocessed before compilation.
C language was developed at Bell Laboratories in 1972 by Dennis Ritchie. It was created for implementing the UNIX operating system. Key standards that were developed for C include C89, C99, C11. C is a structured, general-purpose programming language that is reliable, simple, portable and widely used for system programming like operating systems and application development. The basic structure of a C program includes preprocessor directives, global declarations, the main function, and optional user-defined functions.
The document provides an overview of the C programming language, including its history, characteristics, environment, structure, data types, variables, decision making, looping, libraries, and uses. It describes how C was developed at Bell Labs in the early 1970s and later standardized. The summary highlights C's small fixed set of keywords, static typing, use of headers and functions, and popularity for systems programming and performance-critical applications due to its efficiency and ability to access hardware.
C programming is a general-purpose language developed in the 1970s to write operating systems like UNIX. It is one of the most widely used languages, particularly for systems programming. Some key facts: C was created to develop UNIX and is highly optimized for systems programming tasks. It produces very efficient code but with less abstraction than newer languages. Common applications of C include operating systems, language compilers, databases, and network drivers.
This document provides an overview of C programming and data structures. It begins with an introduction to C language concepts like data types, variables, constants, I/O functions, operators, and control statements. It then discusses the history and evolution of C from earlier languages like ALGOL and BCPL. The document outlines characteristics of C and its applications. It also covers topics like keywords, identifiers, data type sizes, variable naming rules, and comment syntax. Library functions for input/output like scanf and printf are explained. The different types of constants in C like integer, real, character, and string constants are defined along with their syntax rules.
The document provides an introduction to the C programming language including its history, importance, basic structure, and key concepts. It was developed in 1972 by Dennis Ritchie at Bell Labs. C is a high-level language well-suited for system programming like operating systems and compilers. The basic structure of C programs includes sections for documentation, headers, preprocessor directives, global declarations, the main function, and subprograms. The document also discusses C tokens, variables, data types, input/output functions, and assignment statements.
Full description about the c programming language . It will helpful to learn the c language easily with this notes and it will helpful in the building of coding and to get jobs in required companies
C is a general-purpose, procedural computer programming language that was developed in the 1970s. Some key points about C include:
1) C is considered the mother language of most modern programming languages as many compilers, kernels, and other core systems are written in C. It introduced fundamental concepts like arrays, strings, functions, and file handling that are used in languages like C++, Java, and C#.
2) C is a procedural language as it breaks programs into functions and data structures. It is also structured as it supports breaking programs into logical blocks.
3) C is a mid-level language as it has features of both low-level languages like pointer arithmetic but is also machine independent like
The document discusses the C programming language. It states that C was created by Dennis Ritchie at Bell Labs in 1972 to develop the UNIX operating system. It became more widely used after Brian Kernighan and Dennis Ritchie published the first description of C in 1978. C is a general-purpose, high-level language that produces efficient, low-level code and can be compiled on many platforms. It is widely used to develop operating systems, compilers, databases and other systems programs.
The document discusses header files and C preprocessors. It defines header files as files containing C declarations and macro definitions that can be shared between source files by including them using the #include directive. Common header files like stdio.h, conio.h, and math.h are given as examples. Preprocessors are described as a macro processor that transforms the program before compilation by handling preprocessor directives like #define. It allows defining macros which are abbreviations for longer code constructs. The document also provides examples of preprocessor directives like #include and #define.
This document provides an introduction to the C programming language. It discusses that C is a procedural language initially developed by Dennis Ritchie in 1972 primarily for system programming like operating system development. It describes the main features of C like low-level access to memory and simple keywords. Many other languages like Java and JavaScript have borrowed syntax from C. The document then discusses the history of C's development at Bell Labs and its general program structure. It provides an example C program to calculate the area of a circle and explains each section of the code. Finally, it covers various C programming concepts like header files, character set, tokens, constants, variables and data types.
Unit 5 discusses file handling in C programming. It defines a file as a collection of bytes stored on disk where related data is stored. There are two main types of file accessing: sequential and random. Sequential files are processed line-by-line while random accessing allows accessing any point in the file. Common file handling functions in C include fopen(), fclose(), fread(), fwrite(), fseek(), ftell() among others. Files are needed to permanently store data for programs to access even after terminating. Reading from files uses functions like fscanf() while writing uses fprintf(). The key aspects of files, records and fields are also discussed along with examples of reading and writing to files in C.
The document discusses functions in C programming. It defines functions and explains their various parts like declaration, definition, and invocation. It also differentiates between function declaration and definition. Various types of functions are classified based on their inputs and outputs. The key differences between call by value and call by reference are explained with examples. Advantages of pass by reference are also mentioned.
A C program is provided to reorder a one-dimensional array of numbers in descending order. The program declares an integer array, prompts the user to enter the number of elements, reads the elements into the array, then uses nested for loops and a temporary variable to reorder the elements from highest to lowest value by swapping elements. The reordered array is then printed to display the output.
The document discusses various topics related to programming in C including data types, constants, expressions, decision making statements, and a sample C program structure. It provides 20 questions with explanations on these topics. It also includes a sample C program to calculate the sum of 10 non-negative numbers entered by the user, illustrating the use of various data types in C programming.
The document discusses various C preprocessor directives and storage classes in C.
1. It defines storage class specifier and mentions the different types of storage classes - auto, extern, static, and register. It distinguishes between auto and register storage classes.
2. It explains what extern storage class means and provides an example. It identifies the storage class of a variable defined within a code block.
3. It discusses various preprocessor directives like #define, #undef, #if, #else, #include and explains their usage with examples.
The document discusses various C preprocessor directives and storage classes. It defines storage class specifier as used to define storage location, scope, lifetime and default value of a variable. The main storage classes are auto, extern, static, and register. It also discusses preprocessor directives like #define, #include, #if etc and provides examples of conditional compilation using #if,#else,#elif. Macro is defined as a way to create symbols or functions that are substituted before compilation. Advantages of macro over functions are also mentioned.
This document contains a summary of structures in C programming language. It defines what a structure is, how to declare and define a structure with members, and how to access structure members using the dot operator. It also discusses nested structures, arrays of structures, and provides an example of a program that uses a structure to prepare student mark statements. Key points covered include declaring and defining structures, accessing structure members, nested structures, arrays of structures, and an example program to print student marks statements using a structure.
This document provides an overview of string handling functions in C programming. It discusses how to declare strings, compare strings, concatenate strings, copy strings, and manipulate strings using pre-defined functions from the string.h header file. Examples are given for common string functions like strlen(), strcmp(), strcpy(), strcat(), etc. to illustrate how each function works and what it returns.
Arrays in C allow storing multiple values of the same data type in contiguous memory locations. An array is declared with a data type, array name, and size. Individual elements are accessed using the array name and index. Arrays are useful for storing lists of values, performing matrix operations, implementing algorithms like search and sort, and more. Strings in C are implemented as arrays of characters that are null-terminated. Functions like strcpy(), strcat(), strcmp() allow manipulating strings.
The document contains C program code snippets for solving various math and logic problems. These include programs to find roots of a quadratic equation, generate the Fibonacci series, find Armstrong numbers between intervals, check if a number is prime, and convert between binary, decimal and other number bases. It also includes programs to check for palindromes, calculate power of a number using a while loop, and convert decimal numbers to hexadecimal representation.
Comparative analysis between traditional aquaponics and reconstructed aquapon...bijceesjournal
The aquaponic system of planting is a method that does not require soil usage. It is a method that only needs water, fish, lava rocks (a substitute for soil), and plants. Aquaponic systems are sustainable and environmentally friendly. Its use not only helps to plant in small spaces but also helps reduce artificial chemical use and minimizes excess water use, as aquaponics consumes 90% less water than soil-based gardening. The study applied a descriptive and experimental design to assess and compare conventional and reconstructed aquaponic methods for reproducing tomatoes. The researchers created an observation checklist to determine the significant factors of the study. The study aims to determine the significant difference between traditional aquaponics and reconstructed aquaponics systems propagating tomatoes in terms of height, weight, girth, and number of fruits. The reconstructed aquaponics system’s higher growth yield results in a much more nourished crop than the traditional aquaponics system. It is superior in its number of fruits, height, weight, and girth measurement. Moreover, the reconstructed aquaponics system is proven to eliminate all the hindrances present in the traditional aquaponics system, which are overcrowding of fish, algae growth, pest problems, contaminated water, and dead fish.
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
Embedded machine learning-based road conditions and driving behavior monitoringIJECEIAES
Car accident rates have increased in recent years, resulting in losses in human lives, properties, and other financial costs. An embedded machine learning-based system is developed to address this critical issue. The system can monitor road conditions, detect driving patterns, and identify aggressive driving behaviors. The system is based on neural networks trained on a comprehensive dataset of driving events, driving styles, and road conditions. The system effectively detects potential risks and helps mitigate the frequency and impact of accidents. The primary goal is to ensure the safety of drivers and vehicles. Collecting data involved gathering information on three key road events: normal street and normal drive, speed bumps, circular yellow speed bumps, and three aggressive driving actions: sudden start, sudden stop, and sudden entry. The gathered data is processed and analyzed using a machine learning system designed for limited power and memory devices. The developed system resulted in 91.9% accuracy, 93.6% precision, and 92% recall. The achieved inference time on an Arduino Nano 33 BLE Sense with a 32-bit CPU running at 64 MHz is 34 ms and requires 2.6 kB peak RAM and 139.9 kB program flash memory, making it suitable for resource-constrained embedded systems.
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMHODECEDSIET
Time Division Multiplexing (TDM) is a method of transmitting multiple signals over a single communication channel by dividing the signal into many segments, each having a very short duration of time. These time slots are then allocated to different data streams, allowing multiple signals to share the same transmission medium efficiently. TDM is widely used in telecommunications and data communication systems.
### How TDM Works
1. **Time Slots Allocation**: The core principle of TDM is to assign distinct time slots to each signal. During each time slot, the respective signal is transmitted, and then the process repeats cyclically. For example, if there are four signals to be transmitted, the TDM cycle will divide time into four slots, each assigned to one signal.
2. **Synchronization**: Synchronization is crucial in TDM systems to ensure that the signals are correctly aligned with their respective time slots. Both the transmitter and receiver must be synchronized to avoid any overlap or loss of data. This synchronization is typically maintained by a clock signal that ensures time slots are accurately aligned.
3. **Frame Structure**: TDM data is organized into frames, where each frame consists of a set of time slots. Each frame is repeated at regular intervals, ensuring continuous transmission of data streams. The frame structure helps in managing the data streams and maintaining the synchronization between the transmitter and receiver.
4. **Multiplexer and Demultiplexer**: At the transmitting end, a multiplexer combines multiple input signals into a single composite signal by assigning each signal to a specific time slot. At the receiving end, a demultiplexer separates the composite signal back into individual signals based on their respective time slots.
### Types of TDM
1. **Synchronous TDM**: In synchronous TDM, time slots are pre-assigned to each signal, regardless of whether the signal has data to transmit or not. This can lead to inefficiencies if some time slots remain empty due to the absence of data.
2. **Asynchronous TDM (or Statistical TDM)**: Asynchronous TDM addresses the inefficiencies of synchronous TDM by allocating time slots dynamically based on the presence of data. Time slots are assigned only when there is data to transmit, which optimizes the use of the communication channel.
### Applications of TDM
- **Telecommunications**: TDM is extensively used in telecommunication systems, such as in T1 and E1 lines, where multiple telephone calls are transmitted over a single line by assigning each call to a specific time slot.
- **Digital Audio and Video Broadcasting**: TDM is used in broadcasting systems to transmit multiple audio or video streams over a single channel, ensuring efficient use of bandwidth.
- **Computer Networks**: TDM is used in network protocols and systems to manage the transmission of data from multiple sources over a single network medium.
### Advantages of TDM
- **Efficient Use of Bandwidth**: TDM all
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Sinan KOZAK
Sinan from the Delivery Hero mobile infrastructure engineering team shares a deep dive into performance acceleration with Gradle build cache optimizations. Sinan shares their journey into solving complex build-cache problems that affect Gradle builds. By understanding the challenges and solutions found in our journey, we aim to demonstrate the possibilities for faster builds. The case study reveals how overlapping outputs and cache misconfigurations led to significant increases in build times, especially as the project scaled up with numerous modules using Paparazzi tests. The journey from diagnosing to defeating cache issues offers invaluable lessons on maintaining cache integrity without sacrificing functionality.
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSIJNSA Journal
The smart irrigation system represents an innovative approach to optimize water usage in agricultural and landscaping practices. The integration of cutting-edge technologies, including sensors, actuators, and data analysis, empowers this system to provide accurate monitoring and control of irrigation processes by leveraging real-time environmental conditions. The main objective of a smart irrigation system is to optimize water efficiency, minimize expenses, and foster the adoption of sustainable water management methods. This paper conducts a systematic risk assessment by exploring the key components/assets and their functionalities in the smart irrigation system. The crucial role of sensors in gathering data on soil moisture, weather patterns, and plant well-being is emphasized in this system. These sensors enable intelligent decision-making in irrigation scheduling and water distribution, leading to enhanced water efficiency and sustainable water management practices. Actuators enable automated control of irrigation devices, ensuring precise and targeted water delivery to plants. Additionally, the paper addresses the potential threat and vulnerabilities associated with smart irrigation systems. It discusses limitations of the system, such as power constraints and computational capabilities, and calculates the potential security risks. The paper suggests possible risk treatment methods for effective secure system operation. In conclusion, the paper emphasizes the significant benefits of implementing smart irrigation systems, including improved water conservation, increased crop yield, and reduced environmental impact. Additionally, based on the security analysis conducted, the paper recommends the implementation of countermeasures and security approaches to address vulnerabilities and ensure the integrity and reliability of the system. By incorporating these measures, smart irrigation technology can revolutionize water management practices in agriculture, promoting sustainability, resource efficiency, and safeguarding against potential security threats.
1. 1
C Program Basics
C is a structured programming language. Every c program and its statements must be in a
particular structure. Every c program has the following general structure...
Line 1: Comments - They are ignored by the compiler
This section is used to provide a small description of the program. The comment lines are simply
ignored by the compiler, that means they are not executed. In C, there are two types of comments.
1. Single Line Comments: Single line comment begins with // symbol. We can write any
number of single line comments.
2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with
*/. We can write any number of multiple lines comments in a program.
In a C program, the comment lines are optional. Based on the requirement, we write comments.
All the comment lines in a C program just provide the guidelines to understand the program and
its code.
Line 2: Preprocessing Commands
Preprocessing commands are used to include header files and to define constants. We use
the #include statement to include the header file into our program. We use a #define statement
2. 2
to define a constant. The preprocessing statements are used according to the requirements. If we
don'tneed any header file, then no need to write #include statement. If we don'tneed any constant,
then no need to write a #define statement.
Line 3: Global Declaration
The global declaration isused to define the global variables,which are common for all the functions
after its declaration. We also use the globaldeclaration to declare functions. Thisglobal declaration
is used based on the requirement.
Line 4: int main()
Every C program must write this statement. This statement (main) specifies the starting point of
the C program execution. Here, main is a user-defined method which tells the compiler that this is
the starting point of the programexecution. Here, int is a data type of a value thatis going to return
to the Operating System after completing the main method execution. If we don't want to return
any value, we can use it as void.
Line 5: Open Brace ( { )
The open brace indicates the beginning of the block which belongs to the main method. In C
program, every block begins with a '{' symbol.
Line 6: Local Declaration
In this section, we declare the variables and functionsthat are local to the function or block in which
they are declared. The variables which are declared in this section are valid only within the function
or block in which they are declared.
Line 7: Executable statements
In this section, we write the statements which perform tasks like reading data, displaying the result,
calculations, etc., All the statements in this section are written according to the requirements.
Line 9: Closing Brace ( } )
3. 3
The close brace indicates the end of the block which belongs to the main method. In C program
every block ends with a '}' symbol.
Line 10, 11, 12, ...: User-defined function()
This is the place where we implement the user-defined functions. The user-defined function
implementation can also be performed before the main method. In this case, the user-defined
function need not be declared. Directly it can be implemented, but it must be before the main
method. In a program, we can define as many user-defined functions as we want. Every user-
defined function needs a function call to execute its statements.
General rules for any C program
1. Every executable statement must end with a semicolon symbol (;).
2. Every C program must contain exactly one main method (Starting point of the program
execution).
3. All the system-defined words (keywords) must be used in lowercase letters.
4. Keywords can not be used as user-defined names(identifiers).
5. For every open brace ({), there must be respective closing brace (}).
6. Every variable must be declared before it is used.
C Character Set
As every language contains a set of characters used to construct words, statements, etc., C
language also has a set of characters which include alphabets, digits, and special symbols. C
language supports a total of 256 characters.
Every C program contains statements. These statements are constructed using words and these
words are constructed using characters from C character set. C language character set contains
the following set of characters...
1. Alphabets
4. 4
2. Digits
3. Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters
together support 52 alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < | tab newline space NULL
bell backspace verticaltab etc.,
C Tokens
Every C program is a collection of instructions and every instruction is a collection of some
individual units. Every smallest individual unit of a c program is called token. Every instruction in a
c program is a collection of tokens. Tokens are used to construct c programs and they are said to
the basic building blocks of a c program.
In a c program tokens may contain the following...
1. Keywords
2. Identifiers
5. 5
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values
C Keywords
As every language has words to construct statements, C programming also has words with a
specific meaning which are used to construct c program instructions. In the C programming
language, keywords are special words with predefined meaning. Keywords are also known as
reserved words in C programming language.
In the C programming language, there are 32 keywords. All the 32 keywords have their meaning
which is already known to the compiler.
Properties of Keywords
1. All the keywords in C programming language are defined as lowercase lettersso they must
be used only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user-defined nameslike variable,functions,arrays,pointers,
etc...
4. Every keyword in C programming language represents something or specifies some kind
of action to be performed by the compiler.
The following table specifies all the 32 keywords with their meaning...
6. 6
C Identifiers
In C programming language, programmers can specify their name to a variable, array, pointer,
function,etc... An identifier is a collection of characterswhich actsas the name ofvariable,function,
7. 7
array,pointer, structure, etc... In other words, an identifier can be defined as the user-defined name
to identify an entity uniquely in the c programming language that name may be of the variable
name, function name, array name, pointer name, structure name or a label.
The identifier is a user-defined name of an entity to identify it uniquely during the program
execution
Example
int marks;
char studentName[30];
Here, marks and studentName are identifiers.
Rules for Creating Identifiers
1. An identifier can contain letters (UPPERCASE and
lowercase), numerics & underscore symbol only.
2. An identifier should not start with a numerical value. It can start with a letter or an
underscore.
3. We should not use any special symbols in between the identifier even whitespace.
However, the only underscore symbol is allowed.
4. Keywords should not be used as identifiers.
5. There is no limit for the length of an identifier. However, the compiler considers the first 31
characters only.
6. An identifier must be unique in its scope.
C data types
Data used in c program is classified into different types based on its properties. In the C
programming language, a data type can be defined as a set of values with similar characteristics.
All the values in a data type have the same properties.
Data types in the c programming language are used to specify what kind of value can be stored in
a variable. The memory size and type of the value of a variable are determined by the variable
8. 8
data type. In a c program, each variable or constant or array must have a data type and this data
type specifies how much memory is to be allocated and what type of values are to be stored in that
variable or constant or array. The formal definition of a data type is as follows...
In the c programming language, data types are classified as follows...
1. Primary data types (Basic data types OR Predefined data types)
2. Derived data types (Secondary data types OR User-defined data types)
3. Enumeration data types
4. Void data type
Primary data types
The primary data types in the C programming language are the basic data types. All the primary
data types are already defined in the system. Primary data types are also called as Built-In data
types. The following are the primary data types in c programming language...
1. Integer data type
2. Floating Point data type
3. Double data type
4. Character data type
9. 9
Integer Data type
The integer data type is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer data type in c. We use the keyword int to
declare the variables and to specify the return type of a function. The integer data type is used with
different type modifiers like short, long, signed and unsigned. The following table provides
complete details about the integer data type.
Floating Point data types
Floating-point data types are a set of numbers with the decimal value. Every floating-point value
must contain the decimal value. The floating-point data type has two variants...
10. 10
float
double
We use the keyword "float" to represent floating-point data type and "double" to represent double
data type in c. Both float and double are similar but they differ in the number of decimal places.
The float value contains 6 decimal places whereas double value contains 15 or 19 decimal places.
The following table provides complete details about floating-point data types.
Character data type
The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.
The following table provides complete information about all the data types in c programming
language...
11. 11
void data type
The void data type means nothing or no value. Generally, the void is used to specify a function
which does not return any value. We also use the void data type to specify empty parameters of a
function.
Enumerated data type
An enumerated data type is a user-defined data type that consists of integer constants and each
integer constant is given a name. The keyword "enum" is used to define the enumerated data
type.
Derived data types
Derived data types are user-defined data types. The derived data types are also called as user-
defined data types or secondary data types. In the c programming language, the derived data
types are created using the following concepts...
Arrays
Structures
Unions
Enumeration
C Variables
Variables in a c programming language are the named memory locations where the user can store
different values of the same datatype during the program execution. That means a variable is a
name given to a memory location in which we can store different values of the same data type. In
12. 12
other words, a variable can be defined as a storage container to hold values of the same datatype
during the program execution. The formal definition of a data type is as follows...
Variable is a name given to a memory location where we can store different values of the
same datatype during the program execution.
Every variable in c programming language must be declared in the declaration section before it is
used. Every variable must have a datatype that determines the range and type of values be stored
and the size of the memory to be allocated.
A variable name may contain letters, digits and underscore symbol. The following are the rules to
specify a variable name...
1. Variable name should not start with a digit.
2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore(_).
4. A variable name can be of any length but compiler considers only the first 31 characters of
the variable name.
Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified datatype values into that memory location. In C
programming language, the declaration can be performed either before the function as global
variables or inside any block or function. But it must be at the beginning of block or function.
Declaration Syntax:
datatype variableName;
Example
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.
C Constants
In C programming language, a constant is similar to the variable but the constant hold only one
value during the program execution. That means, once a value is assigned to the constant, that
value can't be changed during the program execution. Once the value is assigned to the constant,
it is fixed throughout the program. A constant can be defined as follows...
13. 13
A constant is a named memory location which holds only one value throughout the
program execution.
In C programming language, a constant can be of any data type like integer, floating-point,
character, string and double, etc.,
Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal
integer value is specified as direct integer value whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer constant.
Unsigned integer constant value is suffixed with 'u' and long integer constant value is suffixed with
'l' whereas unsigned long integer constant value is suffixed with 'ul'.
Example
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant
Floating Point constants
A floating-point constant must contain both integer and decimal parts. Some times it may also
contain the exponent part. When a floating-point constant is represented in exponent form, the
value must be suffixed with 'e' or 'E'.
Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.
Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a
maximum length of one character.
Example
'A'
'2'
'+'
In the C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape sequence
is prefixed with '' symbol. These escape sequences are used in output function called 'printf()'.
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that
are enclosed in double quotations.
14. 14
We define string constant in a single line as follows...
"Thisisbtechsmartclass"
We can definestring constant using multiple lines as follows...
" This
is
btechsmartclass "
We can also define string constant by separating it with white space as follows...
"This" "is" "btechsmartclass"
C Operators
An operator is a symbol used to perform arithmetic and logical operations in a program. That
means an operator is a special symbol that tells the compiler to perform mathematical or logical
operations.C programming language supportsa rich set of operatorsthatare classified as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
Arithmetic Operators (+, -, *, /, %)
The arithmetic operators are the symbols that are used to perform basic mathematical operations
like addition, subtraction, multiplication, division and percentage modulo. The following table
provides information about arithmetic operators.
15. 15
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5 % 2 = 1
⇒ The addition operator can be used with numerical data types and character data type. When it
is used with numerical values, it performs mathematical addition and when it is used with character
data type values, it performs concatination (appending).
⇒ The remainder of the division operator is used with integer data type only.
Relational Operators (<, >, <=, >=, ==, !=)
The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two results TRUE or FALSE. In simple words, the relational operators are used to
define conditions in a program. The following table providesinformation about relationaloperators.
Operator Meaning Example
< Returns TRUE if the first value is smaller than second
value otherwise returns FALSE
10 < 5 is
FALSE
16. 16
Operator Meaning Example
> Returns TRUE if the first value is larger than second value
otherwise returns FALSE
10 > 5 is
TRUE
<= Returns TRUE if the first value is smaller than or equal to
second value otherwise returns FALSE
10 <= 5
is
FALSE
>= Returns TRUE if the first value is larger than or equal to
second value otherwise returns FALSE
10 >= 5
is TRUE
== Returns TRUE if both values are equal otherwise returns
FALSE
10 == 5
is
FALSE
!= Returns TRUE if both values are not equal otherwise
returns FALSE
10 != 5 is
TRUE
Logical Operators (&&, ||, !)
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
Operator Meaning Example
&& Logical AND - Returns TRUE if all conditions are
TRUE otherwise returns FALSE
10 < 5 && 12 >
10 is FALSE
|| Logical OR - Returns FALSE if all conditions are
FALSE otherwise returns TRUE
10 < 5 || 12 > 10
is TRUE
17. 17
Operator Meaning Example
! Logical NOT - Returns TRUE if condition is FLASE
and returns FALSE if it is TRUE
!(10 < 5 && 12 >
10) is TRUE
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE
then complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
then complete condition becomes TRUE.
Increment & Decrement Operators (++ & --)
The increment and decrement operators are called unary operators because both need only one
operand.The increment operatorsaddsone to the existing value ofthe operand and the decrement
operator subtracts one from the existing value of the operand. The following table provides
information about increment and decrement operators.
Operator Meaning Example
++ Increment - Adds one to existing value int a = 5;
a++; ⇒ a = 6
-- Decrement - Subtracts one from existing value int a = 5;
a--; ⇒ a = 4
The increment and decrement operatorsare used infrontof the operand (++a) or after the operand
(a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is
used after the operand, we call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the
18. 18
expression evaluation. That means, when we use pre-increment or pre-decrement, first the value
of the variable is incremented or decremented by one, then the modified value is used in the
expression evaluation.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j = %d",i,j);
}
Output:
Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value of the variable is incremented or
decremented by one.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
19. 19
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);
}
Output:
Assignment Operators (=, +=, -=, *=, /=, %=)
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the C programming
language.
Operator Meaning Example
= Assign the right-hand side value to left-hand side variable A = 15
+= Add both left and right-hand side values and store the
result into left-hand side variable
A += 10
⇒ A =
A+10
-= Subtract right-hand side value from left-hand side
variable value and store the result
into left-hand side variable
A -= B
⇒ A = A-B
20. 20
Operator Meaning Example
*= Multiply right-hand side value with left-hand side variable
value and store the result
into left-hand side variable
A *= B
⇒ A = A*B
/= Divide left-hand side variable value with right-hand side
variable value and store the result
into the left-hand side variable
A /= B
⇒ A = A/B
%= Divide left-hand side variable value with right-hand side
variable value and store the remainder
into the left-hand side variable
A %= B
⇒ A =
A%B
Bitwise Operators (&, |, ^, ~, >>, <<)
The bitwise operators are used to perform bit-level operations in the c programming language.
When we use the bitwise operators, the operationsare performed based on the binaryvalues. The
following table describes all the bitwise operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example
& the result of Bitwise AND is 1 if all the bits are 1
otherwise it is 0
A & B
⇒ 16 (10000)
| the result of Bitwise OR is 0 if all the bits are 0
otherwise it is 1
A | B
⇒ 29 (11101)
^ the result of Bitwise XOR is 0 if all the bits are same
otherwise it is 1
A ^ B
⇒ 13 (01101)
21. 21
Operator Meaning Example
~ the result of Bitwise once complement is negation of
the bit (Flipping)
~A
⇒ 6 (00110)
<< the Bitwise left shift operator shifts all the bits to the
left by the specified number of positions
A << 2
⇒ 100
(1100100)
>> the Bitwise right shift operator shifts all the bits to the
right by the specified number of positions
A >> 2
⇒ 6 (00110)
Conditional Operator (?:)
The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the condition is
TRUE the first option is performed, if the condition is FALSE the second option is performed. The
conditional operator is used with the following syntax.
Condition ? TRUE Part : FALSE Part;
Example
A = (10<15)?100:200; ⇒A value is 100
Special Operators (sizeof, pointer, comma, dot, etc.)
The following are the special operators in c programming language.
sizeof operator
22. 22
This operator isused to find the size of the memory (in bytes) allocated for a variable.This operator
is used with the following syntax.
sizeof(variableName);
Example
sizeof(A); ⇒the result is 2 if A is an integer
Pointer operator (*)
This operator is used to define pointer variables in c programming language.
Comma operator (,)
This operator is used to separate variables while they are declaring, separate the expressions in
function calls, etc.
Dot operator (.)
This operator is used to access members of structure or union.
What is Operator Precedence?
Operator precedence is used to determine the order of operators evaluated in an expression. In c
programming language every operator has precedence (priority). When there is more than one
operator in an expression the operator with higher precedence is evaluated first and the operator
with the least precedence is evaluated last.
What is Operator Associativity?
Operator associativityis used to determine the order ofoperatorswith equalprecedence evaluated
in an expression. In the c programming language, when an expression contains multiple operators
with equal precedence, we use associativity to determine the order of evaluation of those
operators.
In c programming language the operator precedence and associativity are as shown in the
following table.
Precedence Operator Operator Meaning Associativity
1 ()
[]
function call
array reference
Left to Right
23. 23
Precedence Operator Operator Meaning Associativity
->
.
structure member access
structure member access
2 !
~
+
-
++
--
&
*
sizeof
(type)
negation
1's complement
Unary plus
Unary minus
increment operator
decrement operator
address of operator
pointer
returns size of a variable
type conversion
Right to Left
3 *
/
%
multiplication
division
remainder
Left to Right
4 +
-
addition
subtraction
Left to Right
5 <<
>>
left shift
right shift
Left to Right
6 <
<=
>
>=
less than
less than or equal to
greater than
greater than or equal to
Left to Right
7 ==
!=
equal to
not equal to
Left to Right
8 & bitwise AND Left to Right
9 ^ bitwise EXCLUSIVE OR Left to Right
24. 24
Precedence Operator Operator Meaning Associativity
10 | bitwise OR Left to Right
11 && logical AND Left to Right
12 || logical OR Left to Right
13 ?: conditional operator Left to Right
14 =
*=
/=
%=
+=
-=
&=
^=
|=
<<=
>>=
assignment
assign multiplication
assign division
assign remainder
assign addition
assign subtraction
assign bitwise AND
assign bitwise XOR
assign bitwise OR
assign left shift
assign right shift
Right to Left
15 , separator Left to Right
In the above table, the operator precedence decreases from top to bottom and increases from
bottom to top.
'if' Statement in C
What is Decision Making Statement?
In the C programming language, the program execution flowis line by line from top to bottom. That
means the c program is executed line by line from the main method. But this type of execution flow
may not be suitable for all the program solutions. Sometimes, we make some decisions or we may
skip the execution of one or more lines of code. Consider a situation, where we write a program to
check whether a student has passed or failed in a particular subject. Here, we need to check
whether the marks are greater than the pass marks or not. If marks are greater, then we decide
25. 25
that the student has passed otherwise failed. To solve such kind of problems in c we use the
statements called decision making statements.
Decision-making statements are the statements that are used to verify a given condition
and decide whether a block of statements gets executed or not based on the condition
result.
In the c programming language, there are two decision-making statements they are as follows.
1. if statement
2. switch statement
if statement in c
In c, if statement is used to make decisions based on a condition. The if statement verifies the
given condition and decides whether a block of statements are executed or not based on the
condition result. In c, if statement is classified into four types as follows...
1. Simple if statement
2. if-else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)
Simple if statement
Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. The simple if statement evaluates specified condition. If it is TRUE,
it executes the next statement or block of statements. If the condition is FALSE, it skips the
execution of the next statement or block of statements. The general syntax and execution flow of
the simple if statement is as follows.
Simple if statement is used when we have only one option that is executed or skipped based on a
condition.
26. 26
Example Program | Test whether given number is divisible by
5.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5n") ;
printf("statement does not belong to if!!!") ;
}
Output 1:
Output 2:
if-else statement
The if-else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is FALSE, it
executes another block of statements (False block). The general syntax and execution flow of the
if-else statement is as follows.
27. 27
The if-else statement is used when we have two options and only one option has to be executed
based on a condition result (TRUE or FALSE).
Example Program | Test whether given number is even or odd.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVENn") ;
else
printf("Given number is ODDn") ;
}
Output 1:
Output 2:
28. 28
Nested if statement
Writing a if statement inside another if statement is called nested if statement. The general syntax
of the nested if statement is as follows...
The nested if statement can be defined using any combination of simple if & if-else statements.
Example Program | Test whether given number is even or odd
if it is below 100.
#include<stdio.h>
#include<conio.h>
void main(){
29. 29
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 1:
Output 2:
if-else-if statement (if-else ladder)
Writing a if statement inside else of an if statement is called if-else-if statement.The generalsyntax
of the if-else-if statement is as follows...
30. 30
The if-else-if statement can be defined using any combination of simple if & if-else statements.
Example Program | Find the largest of three numbers.
#include<stdio.h>
#include<conio.h>
void main(){
int a, b, c ;
clrscr() ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
31. 31
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}
Output:
'switch' statement in C
Consider a situation in which we have many optionsout of which we need to select only one option
that is to be executed. Such kind of problems can be solved using nested if statement. But as the
number of options increases, the complexity of the program also gets increased. This type of
problem can be solved very easily using a switch statement. Using the switch statement, one can
select onlyone option from more number of optionsvery easily. In the switch statement,we provide
a value that is to be compared with a value associated with each option. Whenever the given value
matches the value associated with an option, the execution starts from that option. In the switch
statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
32. 32
The switch statement contains one or more cases and each case has a value associated with it.
At first switch statement compares the first case value with the switchValue, if it gets matched the
execution starts from the first case. If it doesn't match the switch statement compares the second
case value with the switchValue and if it is matched the execution starts from the second case.
This process continues until it finds a match. If no case value matches with the switchValue
specified in the switch statement, then a special case called default is executed.
When a case value matches with the switchValue, the execution starts from that particular case.
This execution flow continueswith the next case statements also. To avoid this,we use the "break"
statement at the end of each case. That means the break statementis used to terminate the switch
statement. However, it is optional.
Example Program | Display pressed digit in words.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any digit: ") ;
scanf("%d", &n) ;
switch( n )
{
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
33. 33
break ;
case 5: printf("FIVE") ;
break ;
case 6: printf("SIX") ;
break ;
case 7: printf("SEVEN") ;
break ;
case 8: printf("EIGHT") ;
break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
getch() ;
}
Output 1:
Output 2:
'do-while' statement in C
The do-while statement is used to execute a single statement or block of statements repeatedly
as long as given the condition is TRUE. The do-while statement is also known as the Exit control
looping statement. The do-while statement has the following syntax...
35. 35
At first, the single statement or block of statements which are defined in do block are executed.
After the execution of the do block, the given condition gets evaluated. If the condition is evaluated
to TRUE, the single statement or block of statements of do block are executed again. Once the
execution gets completed again the condition is evaluated. If it is TRUE, again the same
statements are executed. The same process is repeated until the condition is evaluated to FALSE.
Whenever the condition is evaluated to FALSE, the execution control moves out of the while block.
Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>
36. 36
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10n");
do
{
if( n%2 == 0)
printf("%dt", n) ;
n++ ;
}while( n <= 10 ) ;
getch() ;
}
Output:
'for' statement in C
The for statement is used to execute a single statement or a block of statements repeatedly as
long as the given condition is TRUE. The for statement has the following syntax and execution flow
diagram...
37. 37
At first, the for statement executes initialization followed by condition evaluation. If the condition
is evaluated to TRUE, the single statement or block of statements of for statement are executed.
Once the execution gets completed, the modification statement is executed and again the
condition is evaluated. If it is TRUE, again the same statements are executed. The same process
is repeated until the condition is evaluated to FALSE. Whenever the condition is evaluated to
FALSE, the execution control moves out of the for block.
Example Program | Program to display even numbers upto 10.
38. 38
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)
printf("%dt", n) ;
}
getch() ;
}
Output:
Type Casting and Conversion in C
In a programming language, the expression contains data values of the same datatype or
different data types. When the expression contains similar datatype values then it is evaluated
without any problem. But if the expression contains two or more different datatype values
then they must be converted to the single datatype of destination datatype. Here, the
destination is the location where the final result of that expression is stored. For example, the
multiplication of an integer data value with the float data value and storing the result into a
float variable. In this case, the integer value must be converted to float value so that the final
result is a float datatype value.
In a c programming language, the data conversion is performed in two different methods as
follows...
1. Type Conversion
2. Type Casting
Type Conversion
39. 39
The type conversion is the process of converting a data value from one data type to another
data type automatically by the compiler. Sometimes type conversion is also called implicit
type conversion. The implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a float variable
the integer value automatically gets converted to float value by adding decimal value 0. And
when a float value is assigned to an integer variable the float value automatically gets
converted to an integer value by removing the decimal value. To understand more about type
conversion observe the following...
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i
x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; =======> Here the ASCII value of A (65) is assigned to i
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;
i = x ;
printf("i value is %dn",i);
x = i ;
printf("x value is %fn",x);
i = ch ;
printf("i value is %dn",i);
}
OUTPUt
I value is90
X value is90.000000
I value is65
In the above program,we assign i = x, i.e.,floatvariable valueisassignedtothe integervariable.
Here,the compilerautomaticallyconvertsthe floatvalue (90.99) intointegervalue (90) byremoving
the decimal partof the floatvalue (90.99) and thenitis assignedtovariable i.Similarly,whenwe
assignx = i, the integervalue (90) getsconvertedtofloatvalue (90.000000) by addingzeroas the
decimal part.
Example
40. 40
#include <stdio.h>
main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %fn", sum );
}
Value of sum : 116.000000
Here,itis simple tounderstandthatfirstc gets convertedtointeger,butasthe final value isdouble,
usual arithmeticconversionappliesandthe compilerconvertsi andc into'float' and addsthem
yieldinga'float'result.
Typecasting
Typecasting is also called an explicit type conversion. Compiler converts data from one data
type to another data type implicitly. When compiler converts implicitly, there may be a data
loss. In such a case, we convert the data from one data type to another data type using explicit
type conversion. To perform this we use the unary cast operator. To convert data from one
type to another type we specify the target data type in parenthesis as a prefix to the data value
that has to be converted. The general syntax of typecasting is as follows.
(TargetDatatype) DataValue
Example
int totalMarks = 450, maxMarks = 600 ;
float average ;
average = (float) totalMarks / maxMarks * 100 ;
In the above example code, both totalMarks and maxMarks are integer data values. When we
perform totalMarks / maxMarks the result is a float value, but the destination (average)
datatype is a float. So we use type casting to convert totalMarks and maxMarks into float data
type.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int a, b, c ;
float avg ;
Printf( "Enter any three integer values : ");
Printf(“%d%d%d”,a,b,c);
41. 41
avg = (a + b + c) / 3 ;
printf("avg before casting = %d", avg );
avg = (float)(a + b + c) / 3 ;
printf( "avg after casting = %d",avg);
return 0;
}
OUTPUT
Enter anythree integervalue:10 20 30
Avgbefore casting= 20.000000
Avgaftercasting = 20.000000
Break, continue and goto in C
In c, there are control statements that do not need any condition to control the program
execution flow. These control statements are called as unconditional control statements. C
programming language provides the following unconditional control statements...
break
continue
goto
The above three statements do not need any condition to control the program execution flow.
break statement
In C, the break statement is used to perform the following two things...
1. break statement is used to terminate the switch case statement
2. break statement is also used to terminate looping statements like while,
do-while and for.
When a break statement is encountered inside the switch case statement, the execution
control moves out of the switch statement directly. For example, consider the following
program.
Example Program to perform all arithmetic operations using switch statement
#include<stdio.h>
#include<conio.h>
void main(){
int number1, number2, result ;
42. 42
char operator;
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator: ");
operator = getchar();
switch(operator)
{
case '+': result = number1 + number2 ;
printf("Addition = %d", result) ;
break;
case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d", result) ;
break;
case '/': result = number1 / number2 ;
printf("Division = %d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder = %d", result) ;
break;
default: printf("nWrong selection!!!") ;
}
getch() ;
}
Output:
Enter anytwo integervalue:1020
Please enterenyarithmeticoperator:Multiplication200
When the break statement is encountered inside the looping statement, the execution control
moves out of the looping statements. The break statement execution is as shown in the
following figure.
For example, consider the following example program...
43. 43
Example Program for break statement.
#include<stdio.h>
#include<conio.h>
void main(){
char ch ;
clrscr() ;
do
{
printf("Enter Y / N : ") ;
scanf("%c", &ch) ;
if(ch == 'Y')
{
printf("Okay!!! Repeat again !!!n") ;
}
else
{
printf("Okay !!! Breaking the loop !!!") ;
break ;
}
} while( 1 ) ;
getch() ;
}
OUTPUT:
Do you want to repeat –
Enter Y / N: Y
Okay!!! Repeat again
Enter Y / N: Y
continue statement
The continue statement is used to move the program execution control to the beginning of
the looping statement. When the continue statement is encountered in a looping statement,
the execution control skips the rest of the statements in the looping block and directly jumps
to the beginning of the loop. The continue statement can be used with looping statements like
while, do-while and for.
When we use continue statement with while and do-while statements the execution control
directly jumps to the condition. When we use continue statement with for statement the
execution control directly jumps to the modification portion (increment/decrement/any
modification) of the for loop. The continue statement execution is as shown in the following
figure.
44. 44
Example Program Program to illustrate continue statement.
#include<stdio.h>
#include<conio.h>
void main(){
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
printf("Entered number is EVEN!!! Try another number!!!n") ;
continue ;
}
else
{
printf("You have entered ODD number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
}
OUTPUT
Enter any integer number: 10
Entered number is EVEN!!! Try another number!!!
Enter any integer number: 30
Entered number is EVEN!!! Try another number!!!
Enter any integer number: 55
45. 45
You have entered ODD number!!! Bye!!!
goto statement
The goto statement is used to jump from one line to another line in the program. Using goto
statement we can jump from top to bottom or bottom to top. To jump from one line to another
line, the goto statement requires a label. Label is a name given to the instruction or line in the
program. When we use a goto statement in the program, the execution control directly jumps
to the line with the specified label.
Example Program for goto statement.
#include<stdio.h>
#include<conio.h>
void main(){
clrscr() ;
printf("We are at first printf statement!!!n") ;
goto last ;
printf("We are at second printf statement!!!n") ;
printf("We are at third printf statement!!!n") ;
last: printf("We are at last printf statement!!!n") ;
getch() ;
}
OUTPUT
We are at first printf statement!!!
We are at last printf statement!!!
Most important points
The break is a keyword so it must be used only in lower case letters.
The break statement can not be used with if statement.
The break statement can be used only in switch case and looping statements.
The break statement can be used with if statement, only if that if statement is written
inside the switch case or looping statements.
The continue is a keyword so it must be used only in lower case letters.
The continue statement is used only within looping statements.
The continue statement can be used with if statement, only if that if statement is written
inside the looping statements.
The goto is a keyword so it must be used only in lower case letters.
The goto statement must require a label.
46. 46
The goto statement can be used with any statement like if, switch, while, do-while, and for,
etc.
C Input Functions
C programming language provides built-in functions to perform input operations. The input
operations are used to read user values (input) from the keyboard. The c programming
language provides the following built-in input functions.
1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()
scanf() function
The scanf() function is used to read multiple data values of different data types from the
keyboard. The scanf() function is built-in function defined in a header file called "stdio.h".
When we want to use scanf() function in our program, we need to include the respective
header file (stdio.h) using #include statement. The scanf() function has the following
syntax...
Syntax:
scanf("format strings",&variableNames);
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
printf("nEnter any integer value: ");
scanf("%d",&i);
printf("nYou have entered %d number",i);
}
Output:
Enter any integer value: 10
You have entered %d number 10
47. 47
The scanf() functionreturnsanintegervalue equal tothe total numberof input valuesreadusing
scanf function.
Example program
#include<stdio.h>
#include<conio.h>
void main(){
int i,a,b;
float x;
printf("nEnter two integers and one float : ");
i = scanf("%d%d%f",&a, &b, &x);
printf("nTotal inputs read : %d",i);
}
OUTPUT
Enter two integers and one float : 10 20 3.5
Total inputs read =3
getchar() function
The getchar() function is used to read a character from the keyboard and return it to the
program. This function is used to read a single character. To read multiple characters we need
to write multiple times or use a looping statement. Consider the following example program..
Example program
#include<stdio.h>
#include<conio.h>
void main(){
char ch;
printf("nEnter any character : ");
ch = getchar();
printf("nYou have entered : %cn",ch);
}
Enter any character : V
You have entered : V
getch() function
The getch() function is similar to getchar function. The getch() function is used to read a
character from the keyboard and return it to the program. This function is used to read a
48. 48
single character. To read multiple characters we need to write multiple times or use a looping
statement. Consider the following example program..
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char ch;
printf("nEnter any character : ");
ch = getch();
printf("nYou have entered : %c",ch);
}
Enter any character :
You have entered : V
gets() function
The gets() function is used to read a line of string and stores it into a character array. The
gets() function reads a line of string or sequence of characters till a newline symbol enters.
Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char name[30];
printf("nEnter your favourite website: ");
gets(name);
printf("%s",name);
}
Output:
Enter your favourite website: SRMvalliammai
SRMvalliammai
fscanf() function
The fscanf() function is used with the concept of files. The fscanf() function is used to read
data values from a file. When you want to use fscanf() function the file must be opened in
reading mode.
C Output Functions
49. 49
C programming language provides built-in functions to perform output operation. The output
operations are used to display data on user screen (output screen) or printer or any file. The c
programming language provides the following built-in output functions...
1. printf()
2. putchar()
3. puts()
4. fprintf()
printf() function
The printf() function is used to print string or data values or a combination of string and data
values on the output screen (User screen). The printf() function is built-in function defined in
a header file called "stdio.h". When we want to use printf() function in our program we need
to include the respective header file (stdio.h) using the #include statement. The printf()
function has the following syntax...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Hello! Welcome to btechsmartclass!!!");
}
Output
Hello! Welcome to btechsmartclass!!!"
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 10;
float x = 5.5;
printf("%d %f",i, x);
}
Output
10 5.50000
Syntax:
50. 50
printf("String format string",variableName);
Formatted printf() function
Generally, when we write multiple printf() statements the result is displayed in a single line
because the printf() function displays the output in a single line.
o display the output in different lines or as we wish, we use some special characters called
escape sequences. Escape sequences are special characters with special functionality used in
printf() function to format the output according to the user requirement. In the C
programming language, we have the following escape sequences...
Escape sequence Meaning
n Moves the cursor to New Line
t Inserts Horizontal Tab (5 characters space)
v Inserts Vertical Tab (5 lines space)
a Beep sound
b Backspace (removes the previous character from its current position)
Inserts Backward slash symbol
? Inserts Question mark symbol
' Inserts Single quotation mark symbol
" Inserts Double quotation mark symbol
Example program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Welcome ton");
printf("smartclassn");
printf("the perfect website for learning");
}
OUTPUT
Welcome to
Smartclass
the perfect website for learning
putchar() function
The putchar() function is used to display a single character on the output screen. The
putchar() functions prints the character which is passed as a parameter to it and returns the
same character as a return value. This function is used to print only a single character. To
print multiple characters we need to write multiple times or use a looping statement. Consider
the following example program..
51. 51
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char ch = 'A';
putchar(ch);
}
Output
A
Puts() function
The puts() function is used to display a string on the output screen. The puts() functions prints
a string or sequence of characters till the newline. Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char name[30];
printf("nEnter your favourite website: ");
gets(name);
puts(name);
}
OUTPUT
Enter your favourite website: SRMvalliammai
fprintf() function
The fprintf() function is used with the concept of files. The fprintf() function is used to print a
line into the file. When you want to use fprintf() function the file must be opened in writting
mode.
56. 56
Program to Find Roots of a Quadratic Equation
#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart,imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a,&b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart,imagPart, realPart,imagPart);
}
return 0;
}
Fibonacci Series up to n terms
57. 57
#include <stdio.h>
int main() {
int i, n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Armstrong Numbers Between Two Integers
#include <math.h>
#include <stdio.h>
int main() {
int low, high, i, temp1, temp2, rem, n = 0;
float result = 0.0;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Armstrong numbers between %d and %d are: ", low, high);
for (i = low + 1; i < high; ++i) {
temp2 = i;
temp1 = i;
// number of digits calculation
while (temp1 != 0) {
temp1 /= 10;
++n;
}
// result contains sum of nth power of its digits
while (temp2 != 0) {
rem = temp2 % 10;
result += pow(rem, n);
temp2 /= 10;
}
// check if i is equal to the sum of nth power of its digits
if ((int)result == i) {
printf("%d ", i);
}
// resetting the values
n = 0;
result = 0;
}
58. 58
return 0;
}
Program to Check Prime Number
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i) {
// condition for non-prime
if (n % i == 0) {
flag = 1;
break;
}
}
if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}
Display Prime Numbers Between two Intervals
#include <stdio.h>
int main() {
int low, high, i, flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Prime numbers between %d and %d are: ", low, high);
while (low < high) {
flag = 0;
// if low is a non-prime number, flag will be 1
for (i = 2; i <= low / 2; ++i) {
if (low % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
printf("%d ", low);
59. 59
++low;
}
return 0;
}
Program to convert binary to decimal
#include <math.h>
#include <stdio.h>
int convert(long long n);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n != 0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
#include <math.h>
#include <stdio.h>
int convert(long long n);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n != 0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
Output
Enter a binary number: 110110111
110110111 in binary = 439
60. 60
Program to convert decimal to binary
#include <math.h>
#include <stdio.h>
long long convert(int n);
int main() {
int n;
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("%d in decimal = %lld in binary", n, convert(n));
return 0;
}
long long convert(int n) {
long long bin = 0;
int rem, i = 1, step = 1;
while (n != 0) {
rem = n % 2;
printf("Step %d: %d/2, Remainder = %d, Quotient = %dn", step++, n, rem, n / 2);
n /= 2;
bin += rem * i;
i *= 10;
}
return bin;
}
Output
Enter a decimal number: 19
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary
For example we want to convert decimal number 525 in the octal.
Step 1: 525 / 8 Remainder : 5 , Quotient : 65
Step 2: 65 / 8 Remainder : 1 , Quotient : 8
Step 3: 8 / 8 Remainder : 0 , Quotient : 1
Step 4: 1 / 8 Remainder : 1 , Quotient : 0
So equivalent octal number is: 1015
That is (525)10 = (1015)8
Example 1: Program to Convert Decimal to Octal
#include <stdio.h>
#include <math.h>
int convertDecimalToOctal(int decimalNumber);
int main()
{
int decimalNumber;
61. 61
printf("Enter a decimal number: ");
scanf("%d", &decimalNumber);
printf("%d in decimal = %d in octal", decimalNumber, convertDecimalToOctal(decimalNumber));
return 0;
}
int convertDecimalToOctal(int decimalNumber)
{
int octalNumber = 0, i = 1;
while (decimalNumber != 0)
{
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
Output
Enter a decimal number: 78
78 in decimal = 116 in octal
Example 2: Program to Convert Octal to Decimal
#include <stdio.h>
#include <math.h>
long long convertOctalToDecimal(int octalNumber);
int main()
{
int octalNumber;
printf("Enter an octal number: ");
scanf("%d", &octalNumber);
printf("%d in octal = %lld in decimal", octalNumber, convertOctalToDecimal(octalNumber));
return 0;
}
long long convertOctalToDecimal(int octalNumber)
{
int decimalNumber = 0, i = 0;
while(octalNumber != 0)
{
decimalNumber += (octalNumber%10) * pow(8,i);
++i;
octalNumber/=10;
}
62. 62
i = 1;
return decimalNumber;
}
Output
Enter an octal number: 116
116 in octal = 78 in decimal
Hexadecimal number system: It is base 16 number system which uses the digits from 0 to 9 and
A, B, C, D, E, F.
Decimal number system:
It is base 10 number system which uses the digits from 0 to 9
Decimal to hexadecimal conversion method:
Following steps describe how to convert decimal to hexadecimal
Step 1: Divide the original decimal number by 16
Step 2: Divide the quotient by 16
Step 3: Repeat the step 2 until we get quotient equal to zero.
Equivalent binary number would be remainders of each step in the reverse order.
Decimal to hexadecimal conversion example:
For example we want to convert decimal number 900 in the hexadecimal.
Step 1: 900 / 16 Remainder : 4 , Quotient : 56
Step 2: 56 / 16 Remainder : 8 , Quotient : 3
Step 3: 3 / 16 Remainder : 3 , Quotient : 0
So equivalent hexadecimal number is: 384
That is (900)10 = (384)16
C Program
1. #include<stdio.h>
2. int main() {
3. long int decimalNumber,remainder,quotient;
4. int i=1,j,temp;
5. char hexadecimalNumber[100];
6. printf("Enter any decimal number: ");
7. scanf("%ld",&decimalNumber);
8. quotient = decimalNumber;
9. while(quotient!=0) {
10. temp = quotient % 16;
63. 63
11. //To convert integer into character
12. if( temp < 10)
13. temp =temp + 48; else
14. temp = temp + 55;
15. hexadecimalNumber[i++]= temp;
16. quotient = quotient / 16;
17. }
18. printf("Equivalent hexadecimal value of decimal number %d: ",decimalNu
mber);
19. for (j = i -1 ;j> 0;j--)
20. printf("%c",hexadecimalNumber[j]);
21. return 0;
22.}
Output
1. Enter any decimal number: 45
2. Equivalent hexadecimal value of decimal number 45: 2D
Program to Check Palindrome
#include <stdio.h>
int main() {
int n, reversedN = 0, remainder, originalN;
printf("Enter an integer: ");
scanf("%d", &n);
originalN = n;
// reversed integer is stored in reversedN
while (n != 0) {
remainder = n % 10;
reversedN = reversedN * 10 + remainder;
n /= 10;
}
// palindrome if orignalN and reversedN are equal
if (originalN == reversedN)
printf("%d is a palindrome.", originalN);
else
printf("%d is not a palindrome.", originalN);
return 0;
}
Power ofa Number Using the while Loop
#include <stdio.h>
int main() {
int base,exp;
64. 64
long long result = 1;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &exp);
while (exp != 0) {
result *= base;
--exp;
}
printf("Answer = %lld", result);
return 0;
}
Output
Enter a base number: 3
Enter an exponent: 4
Answer = 81