The preprocessor directive #include inserts the contents of header files into the source code. Common header files include stdio.h, stdlib.h, and math.h. The #define directive defines macros that are replaced before compilation. Functions in math.h perform mathematical operations on double values. Functions in stdlib.h provide common utilities like converting strings to integers with atoi() and generating random numbers with rand() and srand().
1. The document discusses user-defined and standard functions in C programming. It provides examples of function prototypes, definitions, and calls.
2. Key points covered include function return types, parameters, local variable declarations, and scope. Header files and standard library functions are also mentioned.
3. Examples show how to define, declare, and call functions of different types (void, non-void) with and without parameters in C code.
4 operators, expressions & statementsMomenMostafa
?
This document discusses various C programming language concepts including operators, expressions, statements, data types, and type conversions. It provides examples of using unary and binary operators, increment/decrement operators, and the modulus operator. It also discusses operator precedence, expressions, statements, and how C handles type conversions between integers, floats, and characters both automatically and through explicit casting. Loops and conditional statements are demonstrated in examples converting seconds to minutes and counting down bottles of water.
This document contains information about arrays and pointers in C programming. It includes code examples demonstrating how to declare and initialize arrays, access array elements using indexes and pointers, pass arrays to functions, and perform operations on arrays such as summing elements. Multidimensional arrays and pointer arithmetic are also discussed. The examples output the results of operations on sample data arrays.
The document describes debugging a C program with GDB that is causing a segmentation fault. The key steps are:
1. Running the program in GDB shows a segmentation fault occurring in the libc library function atoi().
2. Backtracing reveals the fault occurs when trying to assign an integer to a pointer variable in main().
3. Adding debugging symbols and setting a breakpoint allows inspecting that argv[1] is a null pointer.
4. Passing an argument fixes that fault but causes a new one in the print function when dereferencing the pointer.
5. Further debugging with breakpoints, examining variables and instructions reveals the pointer is being assigned an integer instead of a memory address.
9 character string & string libraryMomenMostafa
?
This document discusses various string handling functions in C including gets(), puts(), fgets(), fputs(), scanf(), strlen(), strcat(), strncat(), strcmp(), strncmp(), strcpy(), and strncpy(). It provides examples of how each function works and the differences between similar functions. Key points covered include how gets() and fgets() read input, how puts() and fputs() output strings, and what string manipulation functions like strlen(), strcat(), etc. are used for.
The document discusses C++ and its history and features. It describes C++ as an extension of C with object-oriented features like classes. It provides information on the creator of C++, Bjarne Stroustrup, and the evolution of C++ since its introduction as a way to add object-oriented programming to C. It also includes sample C++ code demonstrating the use of arrays and includes from the Boost library.
6 c control statements branching & jumpingMomenMostafa
?
This document discusses various C programming concepts including control statements, functions like getchar() and putchar(), character testing and mapping functions from ctype.h, nested if/else statements, the conditional operator, continue and break statements. It provides examples of using these concepts to analyze user input, manipulate characters, calculate electricity bills with rate tiers, check for prime numbers, and calculate statistics from scored entered by the user.
Boost.Python allows extending C++ code with Python by exposing C++ functions, classes, and objects to Python. It provides a simpler approach than other tools by using only C++. Boost.Python handles interfacing C++ and Python types and memory management. The document discusses exposing C++ code like functions, classes with inheritance and special methods, constants, and enums. It also covers passing objects between C++ and Python like lists and custom types. While Boost.Python enables seamless integration, there are still challenges around complex C++ features and performance. The document ends by demonstrating embedding Python in C++.
The document discusses properties in Python classes. Properties allow accessing attributes through normal attribute syntax, while allowing custom behavior through getter and setter methods. This avoids directly accessing attributes and allows for validation in setters. Properties are defined using the @property and @setter decorators, providing a cleaner syntax than regular getter/setter methods. They behave like regular attributes but allow underlying method calls.
The document provides an overview of how a simple C "Hello World" program works, from writing the code to executing the compiled binary. It includes explanations of key concepts like #include, main(), printf(), compiling with gcc, the a.out executable, and how the operating system loads and runs the program. The summary explores the high-level process of taking C code and turning it into a running program.
This document discusses monadic programming (MP) in Clojure. It begins with introductions to monads and monadic programming in Haskell. It then discusses reasons for using MP in Clojure despite it not having static typing or being purely functional. It explains two libraries for MP in Clojure - clojure.algo.monads and funcool/cats - and how they implement monads using macros and protocols. Examples are given of using monads for error handling in a reverse Polish notation calculator and for representing probability distributions.
The document discusses arrays, strings, and functions in C programming. It begins by explaining how to initialize and access 2D arrays, including examples to take input from the user and store it in a 2D array. It then discusses initializing and accessing multidimensional arrays. Next, it covers array contiguous memory and the advantages and limitations of arrays. Finally, it discusses common programming errors related to array construction for real-time applications.
The document discusses Python functions. Some key points covered include:
- Functions are reusable blocks of code defined using the def keyword that can accept parameters and return values.
- To execute a function, it must be called by name with appropriate arguments.
- Functions can call themselves, which is known as recursion.
- Functions can have default, variable, and keyword parameters to provide flexibility in how they are called.
1. Free monads allow defining monadic interpreters for domain-specific languages (DSLs) by representing the DSL's abstract syntax tree as a recursive data type and making it an instance of the Functor typeclass.
2. The document provides an example of defining a DSL for reverse polish notation (RPN) expressions using a Free monad. This includes defining the RPNExpr data type, making it a Functor, lifting it into a Free monad, and writing functions for evaluation, parsing, and pretty-printing RPN expressions.
3. By defining the interpreter as a monad, the RPN expressions can be combined in a composable manner while retaining the ability to run,
This document discusses various Python functions concepts including defining simple functions, functions with arguments, default arguments, lambda functions, generators, and decorators. It provides examples of defining functions that take positional and keyword arguments, using lambda functions, creating generators using yield, and applying decorators to functions. Various introspection methods like type(), dir(), and callable() are also covered.
The document provides an introduction to C++ programming. It outlines topics that will be covered, including basic syntax, compiling programs, passing arguments, dynamic memory allocation, and object-oriented programming. It recommends several useful books and web resources for learning C++ and offers a live coding demonstration of a simple image class to illustrate C++ concepts. The overall tone is informative but acknowledges that C++ is complex and learning requires practice.
1. The document discusses various input/output functions in C including printf(), scanf(), putchar(), gets(), and puts(). It provides examples of using format specifiers like %d, %f, %c with printf and scanf.
2. Functions like putchar() and gets() are used to output/input single characters and strings. Examples demonstrate using gets() to accept user input and puts() to output strings.
3. The last section provides more complex examples combining multiple functions like printf(), scanf(), gets() to perform input/output operations and manipulate strings.
The document provides an introduction to C++ programming. It outlines topics that will be covered such as basic syntax, compiling programs, argument passing, dynamic memory, and object-oriented programming. It recommends some useful books and websites for learning C++ and notes that the tutorial will demonstrate features of the language through examples while emphasizing learning through practice.
02 of 03 parts
Get Part 1 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 3 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-3
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
1. The document discusses various input/output functions in C including printf(), scanf(), putchar(), getchar(), gets(), and puts(). It provides examples of using format specifiers like %d, %c, %s in printf and scanf.
2. Function prototypes and uses of various I/O functions are demonstrated through simple code snippets. Examples show declaring and initializing variables, performing arithmetic operations, character manipulation, string input/output and formatted output.
3. Comments explain the purpose and usage of standard input/output header file stdio.h and each I/O function discussed. Formatted output using field widths and justifications is also demonstrated.
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
?
The document discusses different parameter passing techniques in programming languages, including pass by value, pass by reference, and pass by result/value-result. It provides examples in languages like C, C++, Java, C#, Pascal, Ada to illustrate how each technique works and the differences between them. It also covers topics like parameter modes (in, out, in-out), parameter arrays, and variable arguments.
Implementing Software Machines in C and GoEleanor McHugh
?
The next iteration of the talk I gave at Progscon, this introduces examples of Map implementation (useful for caches etc.) and outlines for addition of processor core code in a later talk.
Learn c++ (functions) with nauman ur rehmanNauman Rehman
?
The document discusses functions in C++. It defines a function as a group of statements that perform a task and can take input arguments and return an output value. Functions make the code more organized and reusable. The document covers function prototypes, definitions, calls, passing arguments by value and by reference, pointer functions, and array functions. It provides examples of different types of functions.
03 of 03 parts
Get Part 1 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 2 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-2
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
Diving into byte code optimization in python Chetan Giridhar
?
The document discusses byte-code optimization in Python. It begins by explaining that Python source code is compiled into byte code, which is then executed by the CPython interpreter. It describes some of the key steps in the compilation process, including parsing the source code and generating an abstract syntax tree (AST) before compiling to bytecodes. The document then discusses some approaches for optimizing Python code at the byte-code level, including using tools like Pyrex, Psyco and the Python bytecode manipulation library BytePlay. It recommends always profiling applications to identify optimization opportunities and considering writing performance-critical portions as C extensions.
Implementing Software Machines in Go and CEleanor McHugh
?
Early draft of a tutorial on techniques for implementing virtual machines and language interpreters. Contains example programs for functional stacks and despatch loops.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, comments, preprocessor directives, libraries and headers. It also covers pointers, arrays, passing command line arguments and standard header files in C. Examples of simple C programs are provided to illustrate various concepts.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, libraries, headers, and compilers. It also covers pointers, arrays, preprocessor directives, and macros. Examples are provided to illustrate basic C programs and common programming constructs in C.
6 c control statements branching & jumpingMomenMostafa
?
This document discusses various C programming concepts including control statements, functions like getchar() and putchar(), character testing and mapping functions from ctype.h, nested if/else statements, the conditional operator, continue and break statements. It provides examples of using these concepts to analyze user input, manipulate characters, calculate electricity bills with rate tiers, check for prime numbers, and calculate statistics from scored entered by the user.
Boost.Python allows extending C++ code with Python by exposing C++ functions, classes, and objects to Python. It provides a simpler approach than other tools by using only C++. Boost.Python handles interfacing C++ and Python types and memory management. The document discusses exposing C++ code like functions, classes with inheritance and special methods, constants, and enums. It also covers passing objects between C++ and Python like lists and custom types. While Boost.Python enables seamless integration, there are still challenges around complex C++ features and performance. The document ends by demonstrating embedding Python in C++.
The document discusses properties in Python classes. Properties allow accessing attributes through normal attribute syntax, while allowing custom behavior through getter and setter methods. This avoids directly accessing attributes and allows for validation in setters. Properties are defined using the @property and @setter decorators, providing a cleaner syntax than regular getter/setter methods. They behave like regular attributes but allow underlying method calls.
The document provides an overview of how a simple C "Hello World" program works, from writing the code to executing the compiled binary. It includes explanations of key concepts like #include, main(), printf(), compiling with gcc, the a.out executable, and how the operating system loads and runs the program. The summary explores the high-level process of taking C code and turning it into a running program.
This document discusses monadic programming (MP) in Clojure. It begins with introductions to monads and monadic programming in Haskell. It then discusses reasons for using MP in Clojure despite it not having static typing or being purely functional. It explains two libraries for MP in Clojure - clojure.algo.monads and funcool/cats - and how they implement monads using macros and protocols. Examples are given of using monads for error handling in a reverse Polish notation calculator and for representing probability distributions.
The document discusses arrays, strings, and functions in C programming. It begins by explaining how to initialize and access 2D arrays, including examples to take input from the user and store it in a 2D array. It then discusses initializing and accessing multidimensional arrays. Next, it covers array contiguous memory and the advantages and limitations of arrays. Finally, it discusses common programming errors related to array construction for real-time applications.
The document discusses Python functions. Some key points covered include:
- Functions are reusable blocks of code defined using the def keyword that can accept parameters and return values.
- To execute a function, it must be called by name with appropriate arguments.
- Functions can call themselves, which is known as recursion.
- Functions can have default, variable, and keyword parameters to provide flexibility in how they are called.
1. Free monads allow defining monadic interpreters for domain-specific languages (DSLs) by representing the DSL's abstract syntax tree as a recursive data type and making it an instance of the Functor typeclass.
2. The document provides an example of defining a DSL for reverse polish notation (RPN) expressions using a Free monad. This includes defining the RPNExpr data type, making it a Functor, lifting it into a Free monad, and writing functions for evaluation, parsing, and pretty-printing RPN expressions.
3. By defining the interpreter as a monad, the RPN expressions can be combined in a composable manner while retaining the ability to run,
This document discusses various Python functions concepts including defining simple functions, functions with arguments, default arguments, lambda functions, generators, and decorators. It provides examples of defining functions that take positional and keyword arguments, using lambda functions, creating generators using yield, and applying decorators to functions. Various introspection methods like type(), dir(), and callable() are also covered.
The document provides an introduction to C++ programming. It outlines topics that will be covered, including basic syntax, compiling programs, passing arguments, dynamic memory allocation, and object-oriented programming. It recommends several useful books and web resources for learning C++ and offers a live coding demonstration of a simple image class to illustrate C++ concepts. The overall tone is informative but acknowledges that C++ is complex and learning requires practice.
1. The document discusses various input/output functions in C including printf(), scanf(), putchar(), gets(), and puts(). It provides examples of using format specifiers like %d, %f, %c with printf and scanf.
2. Functions like putchar() and gets() are used to output/input single characters and strings. Examples demonstrate using gets() to accept user input and puts() to output strings.
3. The last section provides more complex examples combining multiple functions like printf(), scanf(), gets() to perform input/output operations and manipulate strings.
The document provides an introduction to C++ programming. It outlines topics that will be covered such as basic syntax, compiling programs, argument passing, dynamic memory, and object-oriented programming. It recommends some useful books and websites for learning C++ and notes that the tutorial will demonstrate features of the language through examples while emphasizing learning through practice.
02 of 03 parts
Get Part 1 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 3 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-3
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
1. The document discusses various input/output functions in C including printf(), scanf(), putchar(), getchar(), gets(), and puts(). It provides examples of using format specifiers like %d, %c, %s in printf and scanf.
2. Function prototypes and uses of various I/O functions are demonstrated through simple code snippets. Examples show declaring and initializing variables, performing arithmetic operations, character manipulation, string input/output and formatted output.
3. Comments explain the purpose and usage of standard input/output header file stdio.h and each I/O function discussed. Formatted output using field widths and justifications is also demonstrated.
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
?
The document discusses different parameter passing techniques in programming languages, including pass by value, pass by reference, and pass by result/value-result. It provides examples in languages like C, C++, Java, C#, Pascal, Ada to illustrate how each technique works and the differences between them. It also covers topics like parameter modes (in, out, in-out), parameter arrays, and variable arguments.
Implementing Software Machines in C and GoEleanor McHugh
?
The next iteration of the talk I gave at Progscon, this introduces examples of Map implementation (useful for caches etc.) and outlines for addition of processor core code in a later talk.
Learn c++ (functions) with nauman ur rehmanNauman Rehman
?
The document discusses functions in C++. It defines a function as a group of statements that perform a task and can take input arguments and return an output value. Functions make the code more organized and reusable. The document covers function prototypes, definitions, calls, passing arguments by value and by reference, pointer functions, and array functions. It provides examples of different types of functions.
03 of 03 parts
Get Part 1 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 2 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-2
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
Diving into byte code optimization in python Chetan Giridhar
?
The document discusses byte-code optimization in Python. It begins by explaining that Python source code is compiled into byte code, which is then executed by the CPython interpreter. It describes some of the key steps in the compilation process, including parsing the source code and generating an abstract syntax tree (AST) before compiling to bytecodes. The document then discusses some approaches for optimizing Python code at the byte-code level, including using tools like Pyrex, Psyco and the Python bytecode manipulation library BytePlay. It recommends always profiling applications to identify optimization opportunities and considering writing performance-critical portions as C extensions.
Implementing Software Machines in Go and CEleanor McHugh
?
Early draft of a tutorial on techniques for implementing virtual machines and language interpreters. Contains example programs for functional stacks and despatch loops.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, comments, preprocessor directives, libraries and headers. It also covers pointers, arrays, passing command line arguments and standard header files in C. Examples of simple C programs are provided to illustrate various concepts.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, libraries, headers, and compilers. It also covers pointers, arrays, preprocessor directives, and macros. Examples are provided to illustrate basic C programs and common programming constructs in C.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like main functions, libraries, headers, source/header files. It also covers basic C concepts like data types, variables, operators, functions, pointers, arrays, comments and preprocessor directives. Examples of simple C programs are provided to illustrate these concepts.
Contains C programming tutorial for beginners with lot of examples explained. This tutorial contains each and every feature of C programming that will help you. C programming tutorial covering basic C Programming examples, data types, functions, loops, arrays, pointers, etc.
The document discusses functions in C programming. It provides examples of defining functions with parameters and return types, calling functions by passing arguments, using header files to declare functions, and recursion. It shows functions being defined and called to perform tasks like calculating factorials, displaying prices based on hotel rates and nights, and converting numbers to binary. Functions allow breaking programs into smaller, reusable components.
The document discusses various C/C++ programs that demonstrate APIs for files, directories, and devices in Unix-like systems. The programs show how to use APIs such as open, read, write, close, fcntl, lseek, link, unlink, stat, chmod, chown, utime, access, opendir, readdir, closedir, and ioctl. They illustrate functions for file handling, file metadata operations, directory operations, and device I/O. The programs output details like file contents, attributes and permissions to confirm the correct behavior of the various file system and device APIs.
The document discusses debugging techniques for finding and removing logical errors from programs. It describes common debugging techniques like print statements, core dump analysis, and execution monitoring. It then demonstrates how to use a debugger called DDD with a sample C program, including how to set breakpoints and conditional breakpoints to pause execution under certain conditions. The document stresses that prevention through writing clear, simple code is better than debugging, and provides some tips to aim for simplicity.
The document discusses functions in C programming. It begins by explaining what functions are and why they are useful. Functions help modularize programs, avoid code repetition, and allow for software reusability. Key benefits of using functions include divide and conquer programming and abstraction. The document then provides examples of function definitions, prototypes, parameters, return values, and scope. It also discusses calling functions, libraries, recursion, and other concepts related to functions in C.
Python is a versatile, object-oriented programming language that can be used for web development, data analysis, and more. It has a simple syntax and is easy to read and learn. Key features include being interpreted, dynamically typed, supporting functional and object-oriented programming. Common data types include numbers, strings, lists, dictionaries, tuples, and files. Functions and classes can be defined to organize and reuse code. Regular expressions provide powerful string manipulation. Python has a large standard library and is used widely in areas like GUIs, web scripting, AI, and scientific computing.
This document discusses functions in C programming. It covers key concepts about functions including:
- Functions allow programmers to break programs into modular, reusable components.
- Functions are defined with a return type, name, and parameters. They can contain local variable declarations.
- Functions are called by name and passing arguments. They can return values.
- Function prototypes declare the name, parameters, and return type before the function is used.
- The document provides examples of defining, calling, and prototyping functions. It also covers scope, storage classes, and other aspects of working with functions in C.
Functions allow programmers to organize and reuse code. There are three types of functions: built-in functions, modules, and user-defined functions. User-defined functions are created using the def keyword and can take parameters and arguments. Functions can return values and have different scopes depending on if a variable is local or global. Recursion is when a function calls itself, and is useful for breaking down complex problems into simpler sub-problems. Common recursive functions calculate factorials, Fibonacci numbers, and generate the Pascal's triangle.
Here are the values of some pointer expressions:
40, 50, 60};
char *p = a;
*p = 10
*(p+1) = 20
*(p+2) = 30
*(p+3) = 40
*(p+4) = 50
*(p+5) = 60
p+1 points to the element after *p
p+2 points to the second element after *p
&p points to the address of p
1. Header files contain function declarations and macro definitions that can be shared between multiple C source files. System header files are provided by the compiler while user header files are written by the programmer.
2. The math.h header file contains common mathematical functions like sqrt, exp, log, pow, etc. The ctype.h header file contains functions for character classification and conversion like isalpha, isdigit, toupper, tolower.
3. Important functions in stdio.h include printf, scanf for input/output, and fopen, fclose for file handling. Functions in stdlib.h include malloc and free for memory management.
1) Functions allow breaking down programs into smaller, self-contained blocks of code that perform specific tasks. Functions make code more organized and reusable.
2) There are two types of functions in C: library functions that are predefined in header files, and user-defined functions that are defined by the user.
3) Functions make code more modular and reusable by allowing the same block of code to be easily called multiple times by name rather than having to rewrite the block.
The document provides code snippets for creating programs in C to:
1. Restrict mouse pointer movement and display pointer position by accessing the interrupt table and using functions like int86().
2. Create simple viruses by writing programs that shutdown the system, open internet explorer infinitely, or delete IE files.
3. Create DOS commands by writing C programs that can be executed from the command line to list files or directories.
4. Switch to 256 color graphics mode and create directories by calling int86() and writing to registers.
5. Develop a basic paint brush program using graphics functions to draw shapes determined by brush properties when the mouse is clicked.
This document summarizes key aspects of iteration in Python based on the provided document:
1. Python supports multiple ways of iteration including for loops and generators. For loops are preferred for iteration over finite collections while generators enable infinite iteration.
2. Common iteration patterns include iterating over elements, indices, or both using enumerate(). Numerical iteration can be done with for loops or while loops.
3. Functions are first-class objects in Python and can be passed as arguments or returned as values, enabling functional programming patterns like mapping and filtering.
The main function serves as the starting point for program execution. It controls program flow by calling other functions. A program typically ends at the end of main. All C programs must have a main function which takes no arguments and returns an int. Main contains the core logic that runs the program. Preprocessor directives like #include add functionality by including header files. Macros defined with #define are text replacements that occur before compilation. Conditional compilation with #ifdef/#ifndef includes or excludes blocks of code based on symbol definitions.
This document provides an introduction to the C programming language. It discusses key concepts like functions, variables, data types, memory, scopes, expressions, operators, control flow with if/else statements and loops. It also explains how passing arguments by value means functions cannot directly modify their parameters, but passing addresses allows modifying variables in the calling scope. Overall it serves as a helpful primer on basic C syntax and programming concepts for newcomers to the language.
The document discusses functions in C programming. It defines functions as self-contained blocks of code that perform a specific task. Functions make a program modular and easier to debug. There are four main types of functions: functions with no arguments and no return value, functions with no arguments but a return value, functions with arguments but no return value, and functions with both arguments and a return value. Functions are called by their name and can pass data between the calling and called functions using arguments.
Team Emertxe's document provides an overview of functions in C, including:
1. Functions allow code reuse, modularity, and abstraction. They define an activity with inputs, operations, and outputs.
2. Functions are defined with a return type, name, and parameters. They are called by name with arguments. Functions can return values or ignore returned values.
3. Parameters can be passed by value or by reference. Pass by reference allows changing the original argument. Arrays can be passed to functions.
4. Recursive functions call themselves to break down problems. Function pointers allow functions to be called indirectly. Variadic functions accept variable arguments.
5. Common pitfalls include
This document discusses structures in C programming. It explains that structures can contain elements of different data types, accessed by name, unlike arrays where all elements must be of the same type and accessed by index. It provides examples of declaring a structure type with members, defining structure variables, accessing members using the dot operator, passing structures to functions, and initializing an array of structures.
The document discusses call-by-value in function invocation in C. When a function is called, only the values of the arguments are passed to the function, not the variables themselves. So any changes made to the parameters inside the function are not reflected in the calling function. This causes an issue when trying to swap variables by passing them to a Swap function.
2. Preprocessor
? Preprocessor
¨C Permits to define simple macros that are evaluated and
expanded prior to compilation.
¨C Commands begin with a ¡®#¡¯.
¨C #define : defines a macro [Ex] #include <stdio.h>
¨C #undef : removes a macro definition #define PI 3.14159
¨C #include : insert text from file
¨C #if : conditional based on value of expression
¨C #ifdef : conditional based on whether macro defined
¨C #ifndef : conditional based on whether macro is not defined
¨C #else : alternative
¨C #elif : conditional alternative
¨C defined() : preprocessor function: 1 if name defined, else 0
#if defined(__NetBSD__)
2
3. Preprocessor
? #include <filename> or #include ¡°filename¡±
¨C Include contents of filename in this position (not modify your
source file, but make a new temporary file just before compile)
¨C <> is used if filename is in the system default directory
(Most of the standard header files are in the default directory)
¨C ¡°¡± is used if filename is not in the default directory
(Write the path to filename if it is not in the current directory)
[Ex]
Include stdio.h which is in the default
#include <stdio.h>
directory
#include ¡°./test/file.h¡±
Include file.h in test directory.
3
4. Preprocessor
? Header file
¨C Header files with the extension ¡°.h¡± are included by #include
? Contents of Header file
¨C Prototype of Function
¨C ¡®extern¡¯ global variables Refer to Modulization
¨C type definition, etc.
? Typical header files
¨C stdio.h, stdlib.h, math.h, etc.
4
5. Preprocessor
? #define [identifier] [replacement]
¨C replaces any occurrence of identifier in the rest of the code by
replacement.
¨C replacement can be an expression, a statement, a block or simply
anything.
[Ex]
#define LIMIT 100 Preprocessor regards LIMIT as 100,
#define PI 3.14159 PI as 3.141592.
5
6. Preprocessor
? #define
#include <stdio.h>
#define LIMIT 100
#define PI 3.14159
void main(void)
{
printf( ¡°%d, %fn¡±, LIMIT, PI ) ;
}
Preprocessor makes a temporary file.
¡
After that, compile the temporary file.
void main(void)
{
printf( ¡°%d, %fn¡±, 100, 3.14159 ) ;
}
6
7. Preprocessor
? Example
#include <stdio.h> void main(void)
{
#define YELLOW 0 int color ;
#define RED 1
#define BLUE 2 for( color = YELLOW ; color <= BLUE ; color++ ) {
switch( color ) {
case YELLOW : printf( ¡°Yellown¡± ) ; break ;
case RED : printf( ¡°Redn¡± ) ; break ;
case BLUE : printf( ¡°Bluen¡± ) ; break ;
}
}
}
7
8. Preprocessor
? Macro function: Declare a function by using #define
#define multiply(a,b) ((a)*(b))
void main() {
int c = multiply(3,2) ;
}
¨C Compiled after the code modified by preprocessor as follows.
void main() {
int c = ((3)*(2)) ;
}
8
9. Preprocessor
? Macro function: Be careful! Simple replacement!!
¨C what will happen?
#define multiply(a,b) a*b
void main() {
int c = multiply(3+1,2+2) ;
}
¨C Compiled after the code modified by preprocessor as follows.
void main() {
int c = 3+1*2+2 ;
}
¨C Use ¡®()¡¯ for safety.
9
11. Mathematical Functions
? Mathematical Functions
¨C sqrt(), pow(), exp(), log(), sin(), cos(), tan(), etc.
¨C Include the Header file <math.h>
¨C All the math functions have argument with double type and
return value with double type.
[Ex] double sin(double); /* argument is the angle in radians */
double pow(double, double);
¨C Give ¡°-lm¡± flag when you compile this with Unix(gcc).
[Ex] gcc filename.c -lm
11
12. Mathematical Functions
[Ex] #include <stdio.h>
#include <math.h>
#define PI 3.1415926
int main() {
double r = PI / (2*90); /* 180 radian = 1 degree */
int i;
for(i=0; i<=90; i+=5) {
printf("cos(%d) = %ft", i, cos(r*i));
printf("sin(%d) = %ft", i, sin(r*i));
printf("tan(%d) = %fn", i, tan(r*i));
} cos(0) = 1.000000 sin(0) = 0.000000 tan(0) = 0.000000
} ¡
cos(45) = 0.707107 sin(45) = 0.707107 tan(45) = 1.000000
¡
cos(90) = 0.000000 sin(90) = 1.000000 tan(90) = 37320539.634355
12
14. Miscellaneous functions
? Standard Headers you should know about:
¨C stdio.h: file and console (also a file) IO
? perror, printf, open, close, read, write, scanf, etc.
¨C stdlib.h: common utility functions
? malloc, calloc, strtol, atoi, etc
¨C string.h: string and byte manipulation
? strlen, strcpy, strcat, memcpy, memset, etc.
¨C math.h: math functions
? ceil, exp, floor, sqrt, etc.
14
15. Miscellaneous functions
? Standard Headers you should know about:
¨C ctype.h: character types
? isalnum, isprint, isupport, tolower, etc.
¨C errno.h: defines errno used for reporting system errors
¨C signal.h: signal handling facility
? raise, signal, etc
¨C stdint.h: standard integer
? intN_t, uintN_t, etc
¨C time.h: time related facility
? asctime, clock, time_t, etc.
15
16. Miscellaneous functions
? Miscellaneous Functions
¨C atoi(), rand(), srand()
¨C <stdlib.h>: Common Utility Functions
¨C atoi(¡°String¡±): Convert string to integer
int a = atoi( ¡°1234¡± ) ;
¨C rand() : Generate random number
int a = rand() ;
¨C srand( Initial Value ) : Initialize random number generator
srand( 3 ) ;
16
17. Miscellaneous functions
? Ex.: Print 10 random numbers
#include <stdio.h>
#include <stdlib.h>
int main() {
Run this Program twice
for(i=0; i<10; i++)
printf(¡°%dn¡±, rand() ) ;
}
? Print different random number in every execution
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand( (int)time(NULL) ) ;
for(i=0; i<10; i++)
printf(¡°%dn¡±, rand() ) ;
}
17