C Programming

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What character (operator) and keyword is used to identify a preprocessing directive?

#include

PREPROCESSING DIRECTIVES

#include <stdio.h> -An instruction to your compiler to do something before compiling code -The #symbol indicates a preprocessing directive -The stdio.h header file is provided by the standard C library, and is required in order to use the --- -printf()function

What is the format to output only two decimal places of a float variable type?

%.2f

What is the syntax for explicit type conversion of an integer variable called "number" to a float?

%d

The ________ conversion character represents an integer data type, and the ________ conversion character represents a float data type

%d %f

How are float data types different from integer data types?

(float) number casting

What are the basic arithmetic operators in order of precedence?

* / % + -

Pre

++number; --number;

FUNCTIONS

-A named block of code between braces { } that carries out a specific set of operations -Used to break up a program into segments -Arguments are data passed to the function between the () -A function can take zero or more arguments -All C programs contain one or more functions -Every C program must contain a function called main() -Execution always begins with the main()function

VARIABLES - WHAT IS A STRING?

-A string constant is a sequence of characters or symbols between a pair of double-quote characters -Anything between a pair of double quotes is interpreted by the compiler as a string printf("This is a string."); -When referring to single literal character -Enclose in single quote 'b'for bor'\0'forNULL.

What is an integer?

-An integer is any whole number without a decimal point * Incode, commas are not used

CODE COMMENTS

-Anything between /*and */is treated as a comment -Ignored by compiler -May be used over multiple lines -Use // for single line comments -Useful to explain sections of code

VARIABLES IMPLICIT CONVERSION

-Arithmetic operations only execute correctly when both operands are the same type -When operands are different types, the compiler arranges for the value of the data type with a more limited range to be converted to the data type of the other -Those operands are implicitly converted to the least restrictive type of those used in the operation

PROGRAMMING FUNDAMENTALS PSEUDOCODE

-Artificial and informal language -Helps programmers to plan an algorithm -Similar to everyday English -Not an actual programming language

VARIABLES STRING HANDLING METHODS

-C has no specific provision within its syntax for variables that store strings -To store a string, you must declare a char array char name[20] -The variable name can accommodate a string that has up to 19 characters -One element is reserved for the termination character NULL, written as \0 -There are two ways to initialize during declaration char name[] = "Harry"; char name[6]={'H','a','r','r','y','\0'}; -The compiler will automatically fill the last character with a NULL character

PROGRAMMING FUNDAMENTALS - LINK/BUILD

-Combines modules generated by a compiler -Adds required code modules from program libraries -Links libraries to object file -Detects and reports errors -Missing or nonexistent library component is referenced -Libraries contain routines that support operations -Function definitions -Input, output, comparing strings, etc -Many IDEs have a "Build" option, which compiles and links in one step -Creates an executable file

A compiler...

-Converts source code into machine language -Detects and reports errors -Variable Declaration and Type Enforcement -Results in the creation of an object file -Can be done via command line or IDE interface

What flowchart symbol is used for decisions? For input/output?

-Diamond [Decision / Condition Operators] - Parallelogram [Input/Output]

Pseudocode Advantages

-Easily Modified -Done easily in a text editor

Stages of Creation

-Editing -Compiling -Linking -Execute

What are the four fundamental stages of program creation?

-Editing -Compiling -Linking -Execute

VARIABLES - DEFINED

-Every variable has a name -Refers to that place in memory -retrieve/store data -Only begin with a lower or uppercase letter or an underscore -May contain uppercase or lowercase letters, numbers, or underscores -no other special characters -Number of variables used in a program virtually unlimited -Value not fixed -may be changed as needed w/an exception -Constants (#define preprocessor or constkeyword) #define NEWLINE '\n' Const char NEWLINE = '\n'; -When a variable is declared, the computer allocates a space in memory big enough to store it -Variable type dictates amount of memory to allocate -Different variable types require different amounts of memory

VARIABLES EXPLICIT TYPE CONVERSION

-Explicit type conversion -a type of conversion which is explicitly defined within a program -Commonly used for comparing integer with floating-point values when the fraction of the calculation needs to be retained -Accomplished via a cast operator (type) variablename

Flowchart Disadvantages

-Hard to modify -Special software required

Define requirements

-Identify the problem (need) -Identify the user (and expected output) -Determine target computer or device -Determine programming skill

What is a major limitation of scripting?

-Not designed for large application -The larger it gets the slower it runs -Borrows resource management -Not as close to the processor -Cannot specify how memory is managed -NOt as efficient of resources aka being slow

Pseudocode Disadvantages

-Not visual -No accepted standard

What capabilities do scripting languages offer?

-Portability -OS Interaction -Regular Expression -One-liners -Interactive Script Execution

PROGRAMMING FUNDAMENTALS - EXECUTE

-Process of running a program -All previous steps must have been accomplished successfully -No errors -To execute via command line input ./c_pass or ./a.out

Flowchart Advantages

-Standardized -Visual

DEBUGGING

-The compiler will present you with a list of these mistakes in your code -To correct these mistakes, return to the editing stage, find the problem, then fix it

VARIABLES STRING LIBRARY FUNCTIONS

-The header file <string.h> contains multiple string oriented functions -Contained within are functions for copying, concatenating, comparing, and searching through strings

FLOW CONTROL BOOLEAN LOGIC OPERATORS:

-Used to compare true/false values to compute a new true/false value -Three Boolean logic operators are (assume X is 1 and Y is 0):

Types of text editor or an IDE (Integrated Development Environment)

-VI, Notepad (recommend Notepad++) -Microsoft Visual Studio

COMPILE -GCC

-gcc <sourcefile.c> -o <outputfile> -The -o option designates the output file -Otherwise a.out is used by default -gcc c_pass.c-o c_pass

VARIABLES PRINTF() FUNCTION REVISITED

-printf can also be used to print values of variables based upon their data type -Conversion characters used to represent data types (%d, %f, %c, %p, %s) -Each conversion character represents an argument of the same type

FUNCTIONS -PRINTF()

-printf("Hello World"); -Function is contained within stdio.h -Takes at least one argument, can be formatted strings and escape sequences -\n= newline character -\t= tab character -printf("\t\tHello\nWorld");

What is a string constant?

-sequence of characters or symbols between a pair of double-quote characters

What is a variable?

-specific piece of memory in the computer that consist of one or more contiguous byte -every variable has a name

What symbols (operator) are used to create a multiline comment in C?

/ * */

Three additional operators are:

<=, >=, !=

VARIABLES ADDRESSES AND VARIABLES

A byte of memory is labeled as an address

PROGRAM STRUCTURE PERSONAL HEADER FILES

A header file contains function declarations and definitions to be shared between source files

FLOW CONTROL CODE BLOCK

A segment of code surrounded by { and } Define blocks of code Function definition Statements in an evaluated expression Allows multiple instructions to the computer within the block of code Rule of thumb: indent block of code

FLOW CONTROL"DO...WHILE" LOOP

A variation of the while loop do {repeat this block of code} while(expression == true); Tests the expression at the end of the loop body Repeats the block of code as long as the expression at the end is true

FLOW CONTROL "IF...ELSE" STATEMENT

An else added to an if statement gives you more flexibility Creates an either-or situation if condition == true, execute 1st statement if condition == false, skip 1st and execute 2nd One way of dealing with multiple-choice situations Evaluate multiple conditions

VARIABLES INTEGERS

An integer is any whole number without a decimal point 1 2,147,483,647 In code, commas are not used: 2147483647

SCRIPTING USES

Automate repetitive tasks Log/file Analysis: Search for keywords Resetting permissions, equipment / VMs Scraping a website Scanning a network Brute forcing a password Creating user accounts Overlaying another application Extend or modify functionality New or enhanced features Macros in MS Office

PROGRAM STRUCTURE BASIC STRUCTURE

Basic structure in order of appearance in program Link - preprocessing directives Declaration Global variable declaration(s) User-defined function declaration(s) Main function - main() User-defined function definition(s) Optional but recommended Documentation section Author, date w/revision dates, etc. Recommended throughout the program

VARIABLES CASTING

Casting -method to convert a variable from one type to another

What converts source code into machine language?

Compilier

What kind of errors are reported by the compiler at the compiling stage? At the linking stage?

Compiling statge:detect variable declaration, type enforcement, structure, syntax errors, flow control Linking stage - missing or non ex.teal library component

Circle

Connectors

________ is the process of correcting mistakes in source code identified by the compiler.

Debugging

FLOW CONTROL - DECISION MAKING

Decision Making Evaluating a condition True or False True - non-zero and non-null value False - zero and null value Statements: if, if...else, and switch

Diamond

Decision/condition operators

VARIABLES DECLARATION AND ASSIGNMENT

Declare a variable type variablename; int a;

VARIABLES CHARACTER VARIABLES

Designated in C as char Uses the least amount of memory of all the data types 1 byte Holds a single ASCII character

PROGRAM STRUCTURE FUNCTION DEFINITION

Determine the type of actions performed on the values passed to the function Syntax for a function definition is the same as the declaration Minus the semi-colon Followed by opening and closing curly brackets { and } Code to execute is within the braces Contains the return keyword to return to point in program function was called

Nested Statements

Each if can be anything as long as the result is true or false If all the if conditions are false, the final else will be executed (final else optional)

What is the process of creating and modifying C source code?

Editing

FLOW CONTROL SWITCH STATEMENTS

Enables you to choose one course of action from a set of possible actions Such as a menu Not as flexible as if statements Based on the result of an integer expression Requires a break statement to terminate a statement If break is missing, will continue processing the next case until a break is reached The (optional) default case which appears at the end does not require a break

2 types of conversion:

Explicit type conversion Implicit type conversion

Scripting

Faster to modify Slower at runtime (requires interpreter) Repetitive tasks Small applications Multi-platform/systems

PROGRAM STRUCTURE VARIABLE SCOPE - Two Types

Global Local

VARIABLES FLOATING-POINT VARIABLES

Hold values with a decimal point 1.6 0.00008 7655.899

PROGRAM STRUCTURE FUNCTION DECLARATION/PROTOTYPE

Identifies the characteristics of the function Return type, name of function, parameter list Ends with a semi-colon Syntax: returnType functionName(parameter list);

What section of a program will you find function prototypes? And what section do they appear before?

In the declaration section of the program before the main( ) section.

FLOW CONTROL LOOP CONTROL (INCREMENT/DECREMENT)

Increment or decrement variable by 1 number = number + 1; number = number - 1;

Parallelogram

Input/Output

What combines various modules generated by the compiler from source code files?

Linker

When do variables cease to exist?

Local variables cease to exist at the closing curly brace for the block

FLOW CONTROL FUNDAMENTAL RELATIONAL OPERATORS

Mechanism for comparing Decision based on comparison (true or false) Three fundamental relational operators are: < , ==, >

What character will automatically fill the last index of a string?

Null character (\0)

What are function parameters?

Place holds for the arguments which need to specified when a function is called

What is meant by parameter list in a function prototype? And what are they enclosed in?

Placeholder for arguments, parathesis is in parathesis & includes a list of all parameters separated by commas & their respective data types the function will accepts as arguments

FLOW CONTROL NESTED LOOPS

Placing one loop inside the body of another Can go as many levels deep as required

SCRIPTING CAPABILITIES

Portability OS Interaction Special syntax and/or modules (functions) Regular Expressions One-liners

SCRIPTING LIMITATIONS

Processor Abstraction Not designed for large applications The larger it gets the slower it runs Borrows resource management Not as close to the processor Cannot specify how memory is managed Not as efficient in use of resources

Line

Program Flow

SCRIPTING VS. COMPILED WHAT IS SCRIPTING?

Programming language that avoids explicit program compilations Also known as an interpreted language

FLOW CONTROL SCANF() FUNCTION

Reads input from STDIN (aka keyboard) Stops reading when encounters a space Takes at least two arguments Formatted string with conversion character %d - signed integer %f - signed float

lvalue

Refers to an object that persists beyond an expression All variables are lvalues May be on either left or right side of assignment operator

Loop

Repeat a block of code several times Types: while , do...while, and for

SCRIPTING VS. COMPILED COMPARISON

Scripting Converted to binary at runtime by an interpreter Portable Compiled Compiled and linked into an executable prior to runtime Platform specific

PROGRAM STRUCTURE FUNCTIONS

Series of statements in a block of code written to perform a task Purpose: separate parts of the program for repeated use Input/Output Mathematical operations (formulas) Not limited to functions in standard library Write your own Must declare/define before used

FLOW CONTROL LOOPS

Series of statements which execute repeatedly a given number of times Useful to apply the same calculation to different sets of data values Without loops you would need to write out the instructions the number of times there were sets of data values to be processed.

What does the line of code "EXP1 ? EXP2 : EXP3" implement?

Short hand way to implement an if else conditional statement

FLOW CONTROL"FOR" LOOP

Similar to the while loop for(init; expression == true; increment) {repeat this block of code} Abbreviates the code to manage the loop Loop repeats the block of code as long as the expression is true The increment (or decrement) occurs only after the block of code has been executed

Compiled

Slower to modify (requires compiling/linking) Faster at runtime Large scale complex applications Operating systems Word/image manipulation

The process of creating and modifying

Source code

There are two types of header files

Standard library - discussed in Objective 1a Personal - ones you create and share (use quotes instead of angled braces) #include "myfile.h"

Rectangle (rounded)

Start/End of program

Rectangle

Static actions

. A ________ is a set of smaller goals written in plain language; whereas, _______ is an artificial and informal language used to help programmers plan an algorithm

Tasklist Pseudocode

rvalue

Temporary value that does not persist beyond the expression Appears on the right side of assignment operator only

Assign a value

The assignment operator= (to be discussed shortly) Everything to the right (rvalue or lvalue) of = gets assigned to variable on the left (lvalue) int a = 1; int b = 2, c = 3; int d = a + b + c;

PROGRAM STRUCTURE VARIABLE SCOPE

The extent within the program code where a variable is visible and can be referenced

FLOW CONTROL "WHILE" LOOPS

The most basic loop while(expression == true) {repeat this block of code} Continues to repeat the block of code as long as the expression is true May be a single statement or multiple statements in the block of code { }

FLOW CONTROL "IF" STATEMENT

The simplest statement to determine whether code is executed based on a condition -Always evaluates to true or false if condition == true, execute the statement if condition == false, skip the statement

Variable pointer is used tell the computer what to store

Variable name preceded by & Examples: scanf("%d", &myInt); scanf("%d %f", &myInt, &myFloat);

PROGRAM STRUCTURE FUNCTION OPERATION

When a function is called Zero or more arguments are passed Block of code for function is executed Control returns to the point at which it was called when keyword return is encountered The return keyword provides the means for exiting from a function Functions which return no value (type void) do not require a return keyword and will still return to the point it is called

What is the name of the file created if you do not specify an output file when compiling at the command line using the gcc command?

a.out

What does the if...else statement create?

added flexibility to write separate blocks of code for both a true or false evalution. It creates an either -or situation

What symbol precedes an escape sequence in the printf function?

backslash (\)

A/An ________ is defined as a segment of code surrounded by curly braces that define functions or statements in an evaluated expression

blocking code

What keyword terminates a case in switch statement, and what happens if it is not included in the case?

break statement flow of control will continue to the next case until a break is encountered or the swith statement ends

What is defined as the method uses to convert a variable from one data type to another?

casting

The ________ data type holds a single ASCII character.

char

What are the five signed and unsigned integer variable types?

char, short int, int, long int, long long int

How do you declare a string?

character array, such as char name[ ]

What happens when a function is called?

code within the body of the function is executed A call is made using the function name followed by opening & closing parenthesis

The ________ case in a switch statement is not required but is often used to execute a block of code when none of the other cases are true.

default

What loop will always execute at least once?

do...while loop

The ________ section is optional but recommended and includes such information as author, date, etc.

documentation

Global variables

exist throughout a program Declared before main() function

Local variables

exist within the block of code they are defined

What is the correct syntax to prototype a function named "myfunction" which returns a float data type and has two float parameters, in order, named "x" and "y."

float myfunction(float x, float y);

What benefit does compiling a large program have over the same program as a script?

for large scale applications such as word processing Power to run complex applications like operating systems. speed

A named block of code that contains curly braces and carries out some specific set of operations is a ________.

function

The ________ statement is the simplest way to alter the order your code is executed based on a condition.

if

What rule of thumb should be followed in your code to identify the statements belonging to a conditional or loop statement?

indented block of code

Declare multiple variables at same time

int a, b, c, d;

. What are the three fundamental relational operators?

is less than < is equal to = = is greater than >

What function must all C programs have?

main ( )

What is the syntax to call the function in question 9 with two variables, in order, called a and b?

myfunction (a, b);

A true evaluation is any ________ and ________ value, and a false evaluation is any ________ and ________ value.

non zero and non null zero and null

What is the shorthand notation for incrementing or decrementing a number by one?

number +1 = number++ number -1 = number--

Post ( number+=2;to increment by 2)

number++; number--;

What is a nested loop?

placing one loop inside the body of another can go as many levels deep as required

What is a scripting language?

programming language that does not require the code to be converted into machine code, aka binary, prior to execution uses an interpreter

Control is returned to the point at which a function is called when the keyword ________ is encountered.

return

PROGRAM STRUCTURE FUNCTION DECLARATION/PROTOTYPE

returnType functionName(parameter list); Parameter List Placeholder for arguments passed to it Declare type of arguments required for the function Enclosed in parenthesis after function name Separate multiple arguments with comma Example (area of circle PIr2): float circleArea(int radius);

You edit a/an ________ file, compile it into a/an ________ file, and link/build it into a/an ________ file.

source object executable

What does a for loop abbreviate, and when does the increment/decrement occur?

step break down abbreviate the code to manage this loop occurs all on one line versus multiple lines

The ________ string function adds one string to the end of another, and the ________ string function returns a pointer.

strcat strstr

Concatenate str2 onto the end of str1

strcat(str1, str2);

Compare str1 to str2, returns -1, 0, or 1

strcmp(str1, str2);

Copy the contents of str2 into str1

strcpy(str1, str2);

What is the name of the preprocessing directive (header file) which contains string oriented functions?

string.h

Return the length of str1

strlen(str1);

Search str1 for str2, returns a pointer

strstr(str1, str2);

When will a loop exit?

until the condition is evaluated as false

The most basic loop is the _____________ loop.

while

Where do variables exist in relation to scope?

within the block in which they are defined


Ensembles d'études connexes

Lesson 2.5 Solving Equations with Absolute Value

View Set

C++ interview questions and answers

View Set

Chapter 12: Water and Electrolytes

View Set