aayush@ate_
cd ../notes
languages

Introduction to C Syntax and Structure

The reason you use #include <iostream> in C++ instead of stdio.h (or "studio.h") is because they belong to different languages and serve different purposes: https://www.cse.iitd.ac.in/~saroj/IITJ/C_notes.pdf

https://cwh-full-next-space.fra1.cdn.digitaloceanspaces.com/cheatsheets/C%20Language%20CheatSheet.pdf c lang cpp https://cwh-full-next-space.fra1.cdn.digitaloceanspaces.com/cheatsheets/C%2B%2B%20Cheatsheet.pdf

(media not in this export — contact me for the full note)

(media not in this export — contact me for the full note)

Key Differences Between iostream and stdio.h

Aspectstdio.hiostream
LanguageC standard libraryC++ standard library
Input/Output StyleFunction-based (e.g., printf, scanf)Stream-based (e.g., cout, cin)
Programming ParadigmProceduralObject-oriented (uses classes and streams)
NamespaceGlobal namespaceUses std namespace
Usage in C++Allowed but considered legacy; better to use <cstdio> if neededRecommended for C++ programs
PerformanceGenerally faster for simple I/OMore flexible and type-safe, but can be slower due to abstraction
FeaturesBasic formatted input/outputSupports operator overloading, extensible for user-defined types

Why Not Use stdio.h in C++?

  • stdio.h is from C and uses functions like printf() and scanf(), which are not type-safe and less flexible.
  • iostream uses C++ streams (cout, cin) which are safer, support overloading, and fit the object-oriented design of C++.
  • Modern C++ standards (since 1998) standardized iostream as the proper way to do input/output.
  • Using iostream allows you to take advantage of namespaces (std::), classes, and other C++ features.
  • While you can include stdio.h in C++, it is discouraged because it does not integrate well with C++ features.

About iostream.h

  • iostream.h was an older, non-standard header used in early C++ compilers before standardization.
  • Modern C++ uses <iostream> without .h.
  • iostream.h does not use namespaces and is deprecated. The reason you use #include <iostream> in C++ instead of stdio.h (or "studio.h") is because they belong to different languages and serve different purposes:

conio.h

is a C header file that stands for “console input-output.” It is used primarily in MS-DOS and Windows-based compilers like Turbo C to provide functions for console input and output operations. These functions include getting characters from the keyboard without waiting for the Enter key (e.g., getch()), clearing the screen (clrscr()), moving the cursor (gotoxy()), and others like cputs(), putch(), kbhit(), textcolor(), and textbackground(). Key points about conio.h: • It is not part of the C standard library or ISO C and is mostly supported by DOS/Windows compilers, not by GCC or compilers targeting UNIX/Linux systems. • It provides useful functions for handling console I/O directly, often used in simple console applications or legacy code. • Some common functions: • getch(): Reads a character from the keyboard without echoing it. • clrscr(): Clears the console screen. • cgets(): Reads a string from the console until carriage return. • cputs(): Prints a string to the console. • gotoxy(): Moves the cursor to a specified position on the screen. Because conio.h is non-standard and compiler-dependent, programs using it may not compile on modern systems or compilers like GCC on Linux, which do not support it. Alternatives such as the curses library are used on UNIX/Linux systems for similar functionality

Summary

  • Use #include <iostream> in C++ for input/output.
  • Use #include <stdio.h> only in C programs.
  • In C++, prefer iostream because it is designed for C++'s object-oriented features.
  • stdio.h is legacy in C++ and lacks the flexibility and safety of streams.

. C

Hello World:

// hello_world.c
#include <stdio.h> // Required for printf

int main() {
    printf("Hello, World!\n"); // \n for new line
    return 0; // Indicate successful execution
}

If-Else Question Program:

// if_else_example.c
#include <stdio.h> // Required for printf and scanf

int main() {
    int number;

    // Prompt the user for input
    printf("Enter an integer: ");

    // Read an integer from the user
    // &number passes the memory address of 'number' to scanf
    if (scanf("%d", &number) != 1) { // scanf returns the number of items successfully read
        printf("Invalid input. Please enter an integer.\n");
        return 1; // Indicate error
    }

    // If-else if-else statement
    if (number > 0) {
        printf("The number %d is positive.\n", number);
    } else if (number == 0) {
        printf("The number %d is zero.\n", number);
    } else {
        printf("The number %d is negative.\n", number);
    }

    return 0; // Indicate successful execution
}

How to run C:
Save the code as a .c file. You need a C compiler (like GCC).

  1. Compile: gcc hello_world.c -o hello_world

  2. Run: ./hello_world

    For the if-else example:

  3. Compile: gcc if_else_example.c -o if_else_example

  4. Run: ./if_else_example


C++

Hello World:

// hello_world.cpp
#include <iostream> // Required for std::cout

int main() {
    std::cout << "Hello, World!" << std::endl; // std::endl for new line and flush
    return 0;
}

If-Else Question Program:

// if_else_example.cpp
#include <iostream> // Required for std::cout and std::cin
#include <limits>   // Required for std::numeric_limits

int main() {
    int number;

    // Prompt the user for input
    std::cout << "Enter an integer: ";

    // Read an integer from the user
    if (!(std::cin >> number)) { // If input fails
        std::cout << "Invalid input. Please enter an integer." << std::endl;
        // Clear error flags and ignore remaining bad input
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        return 1; // Indicate error
    }

    // If-else if-else statement
    if (number > 0) {
        std::cout << "The number " << number << " is positive." << std::endl;
    } else if (number == 0) {
        std::cout << "The number " << number << " is zero." << std::endl;
    } else {
        std::cout << "The number " << number << " is negative." << std::endl;
    }

    return 0;
}

How to run C++:
Save the code as a .cpp file. You need a C++ compiler (like G++).

  1. Compile: g++ hello_world.cpp -o hello_world

  2. Run: ./hello_world

    For the if-else example:

  3. Compile: g++ if_else_example.cpp -o if_else_example

  4. Run: ./if_else_example


Introduction to C Syntax and Structure

C is a foundational programming language that has influenced the development of many other languages, including C++, Java, and Python. Understanding C syntax and structure is crucial for grasping core programming concepts and building a solid foundation for more advanced topics. This lesson will introduce you to the basic building blocks of C programs, including the main function, header files, variables, data types, and basic input/output operations. By the end of this lesson, you'll be able to write simple C programs and understand the fundamental structure of more complex ones.

Basic Structure of a C Program

Every C program has a specific structure that must be followed for the program to compile and run correctly. The most basic structure consists of the following elements:

  1. Header Files: These files contain declarations of functions and variables that are used in the program. They are included using the #include directive.
  2. The main Function: This is the entry point of the program. Execution begins here.
  3. Variables: Variables are used to store data. They must be declared with a specific data type before they can be used.
  4. Statements: Statements are instructions that the program executes. They are terminated by a semicolon (;).

Here's a simple example of a C program:

#include <stdio.h> // Includes the standard input/output library

int main() { // The main function, where execution begins
  printf("Hello, World!\n"); // Prints "Hello, World!" to the console
  return 0; // Indicates that the program executed successfully
}

Dissecting the Code

  • #include <stdio.h>: This line includes the standard input/output library, which provides functions like printf for printing output to the console. The angle brackets <> indicate that this is a standard header file.
  • int main() { ... }: This is the main function. Every C program must have a main function. The intindicates that the function returns an integer value. The parentheses () indicate that the function takes no arguments. The curly braces {} enclose the body of the function.
  • printf("Hello, World!\n");: This line calls the printf function to print the string "Hello, World!" to the console. The \n is a newline character, which moves the cursor to the next line.
  • return 0;: This line returns the integer value 0 to the operating system. A return value of 0 typically indicates that the program executed successfully.

Header Files

Header files contain declarations of functions, variables, and other data types that are used in a C program. They allow you to use pre-written code from libraries without having to write it yourself.

Common Header Files

- ****stdio.h**: Standard input/output library. Contains functions for input and output operations, such as printfscanfgetchar, and **putchar

•	Key Functions:
•	`printf`: Prints formatted output to the console.
•	`scanf`: Reads formatted input from the user.
•	`getchar`: Reads a single character from the input.
•	`putchar`: Writes a single character to the output.

### - stdlib.h: Standard library. Contains functions for memory allocation, random number generation, and other utility functions, such as mallocfreerand, and exit.

`malloc`: Allocates a specified amount of memory dynamically.
•	`free`: Frees previously allocated memory.
•	`rand`: Generates pseudo-random numbers.
•	`exit`: Terminates the program execution immediately.

- string.h: String manipulation library. Contains functions for working with strings, such as strcpystrlen, and strcmp.

  • Key Functions: • strcpy: Copies one string to another. • strlen: Calculates the length of a string. • strcmp: Compares two strings lexicographically.

- math.h: Math library. Contains mathematical functions, such as sqrtsincos, and pow

Including Header Files

Header files are included using the #include directive. There are two ways to include header files:

  1. Standard Header Files: These are included using angle brackets <>. The compiler searches for these files in a standard system directory.

    #include <stdio.h>
    
  2. User-Defined Header Files: These are included using double quotes "". The compiler searches for these files in the current directory or a directory specified in the compiler options.

    #include "myheader.h"
    

The main Function

The main function is the entry point of every C program. It is where execution begins. The main function has the following general form:

int main() {
  // Statements
  return 0;
}

Return Type

The main function returns an integer value to the operating system. This value indicates whether the program executed successfully or encountered an error. By convention, a return value of 0 indicates success, while a non-zero value indicates an error.

Arguments

The main function can optionally take arguments from the command line. These arguments are passed as an array of strings. The main function with arguments has the following general form:

int main(int argc, char *argv[]) {
  // Statements
  return 0;
}
  • argc: This is an integer that represents the number of arguments passed to the program.
  • argv: This is an array of strings that contains the actual arguments. argv[0] is the name of the program itself, and argv[1] through argv[argc-1] are the arguments passed by the user.

Example:

#include <stdio.h>

int main(int argc, char *argv[]) {
  printf("Program name: %s\n", argv[0]); // 
Prints the name of the program

  if (argc > 1) {
    printf("Arguments:\n");
    for (int i = 1; i < argc; i++) {
      printf("argv[%d]: %s\n", i, argv[i]); // Prints each argument
    }
  } else {
    printf("No arguments provided.\n");
  }

  return 0;
}

If you compile this program and run it from the command line as myprogram arg1 arg2 arg3, the output will be:

Program name: myprogram
Arguments:
argv[1]: arg1
argv[2]: arg2
argv[3]: arg3

Variables and Data Types

Variables are used to store data in a C program. Each variable must be declared with a specific data type before it can be used. The data type determines the type of data that the variable can store and the operations that can be performed on it.

Basic Data Types

  • int: Integer. Used to store whole numbers (e.g., -10, 0, 42).
  • float: Floating-point number. Used to store numbers with decimal points (e.g., 3.14, -2.5).
  • double: Double-precision floating-point number. Used to store numbers with decimal points with higher precision than float.
  • char: Character. Used to store single characters (e.g., 'a', 'Z', '5').

Declaring Variables

Variables are declared using the following syntax:

data_type variable_name;

Examples:

int age; // Declares an integer variable named 'age'
float price; // Declares a floating-point variable named 'price'
char initial; // Declares a character variable named 'initial'

Initializing Variables

Variables can be initialized when they are declared:

int age = 30; // Declares an integer variable named 'age' and initializes it to 30
float price = 19.99; // Declares a floating-point variable named 'price' and initializes it to 19.99
char initial = 'J'; // Declares a character variable named 'initial' and initializes it to 'J'

Example: Using Variables

#include <stdio.h>

int main() {
   int quantity = 10; // Declares an integer variable and initializes it
   float unitPrice = 2.50; // Declares a float variable and initializes it
   float totalPrice = quantity * unitPrice; // Calculates the total price

  printf("Quantity: %d\n", quantity); // Prints the quantity
  printf("Unit Price: %.2f\n", unitPrice); // Prints the unit price with 2 
  
decimal places
  printf("Total Price: %.2f\n", totalPrice); // Prints the total price with 2 decimal places

  return 0;
}

Output:

Quantity: 10
Unit Price: 2.50
Total Price: 25.00

Basic Input/Output Operations

C provides functions for reading input from the user and printing output to the console. The most commonly used functions are printf and scanf, which are part of the stdio.h library.

printf Function

The printf function is used to print formatted output to the console. It takes a format string as its first argument, followed by a list of variables to be printed.

printf("format_string", variable1, variable2, ...);

Format Specifiers

Format specifiers are used to indicate the data type of the variables being printed. Some common format specifiers include:

  • %d: Integer
  • %f: Floating-point number
  • %lf: Double-precision floating-point number
  • %c: Character
  • %s: String

Example:

#include <stdio.h>

int main() {
  int age = 30;
  float height = 5.9;
  char initial = 'J';

  printf("Age: %d, Height: %.1f, Initial: %c\n", age, height, initial);

  return 0;
}

Output:

Age: 30, Height: 5.9, Initial: J

scanf Function

The scanf function is used to read formatted input from the user. It takes a format string as its first argument, followed by a list of pointers to variables where the input should be stored.

scanf("format_string", &variable1, &variable2, ...);

Important: When using scanf, you must pass the address of the variable using the & operator. This allows scanf to modify the value of the variable directly.

Example:

#include <stdio.h>

int main() {
  int age;
  float height;
  char initial;

  printf("Enter your age: ");
  scanf("%d", &age); // Reads an integer from the user and stores it in 'age'

  printf("Enter your height (in feet): ");
  scanf("%f", &height); // Reads a float from the user and stores it in 'height'

  printf("Enter your initial: ");
  scanf(" %c", &initial); // Reads a character from the user and stores it in 'initial'. Note the space before %c to consume any leftover newline characters.

  printf("Age: %d, Height: %.1f, Initial: %c\n", age, height, initial);

  return 0;
}

If the user enters 255.8, and M, the output will be:

Enter your age: 25
Enter your height (in feet): 5.8
Enter your initial: Age: 25, Height: 5.8, Initial: M

Comments in C

Comments are used to add explanatory notes to your code. They are ignored by the compiler and do not affect the execution of the program. C supports two types of comments:

  1. Single-line comments: These start with // and continue to the end of the line.
  2. Multi-line comments: These start with /* and end with */.

Example:

#include <stdio.h>

int main() {
  // This is a single-line comment
  int age = 30; /* This is an inline comment */

  /*
   This is a
   multi-line comment.
   It can span multiple lines.
  */

  printf("Age: %d\n", age); // Prints the age

  return 0;
}

To run a C program on a Mac using the Terminal, follow these simple steps:


Review of C Syntax: Variables, Data Types, Operators

Variables in C

Variables are fundamental building blocks in C programming. They are named storage locations in the computer's memory that hold data. Think of them as labeled boxes where you can store different types of information.

Declaration and Initialization

Before you can use a variable, you must declare it. Declaration involves specifying the variable's name and its data type. The data type tells the compiler what kind of data the variable will hold (e.g., integer, floating-point number, character).

int age;         // Declares an integer variable named 'age'
float salary;    // Declares a floating-point variable named 'salary'
char initial;    // Declares a character variable named 'initial'

You can also initialize a variable when you declare it, which means assigning it an initial value.

int age = 30;      // Declares 'age' and initializes it to 30
float salary = 50000.0; // Declares 'salary' and initializes it to 50000.0
char initial = 'J';    // Declares 'initial' and initializes it to 'J'

If you don't initialize a variable, it will contain a garbage value (whatever happens to be in that memory location). It's good practice to always initialize your variables to avoid unexpected behavior.

Variable Naming Rules

C has specific rules for naming variables:

  • Variable names can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
  • The first character must be a letter or an underscore.
  • Variable names are case-sensitive (e.g., age and Age are different variables).
  • You cannot use reserved keywords (e.g., intfloatchariffor) as variable names.

Here are some examples of valid and invalid variable names:

Valid NamesInvalid NamesReason
my_variable2ndVariableStarts with a digit
_agemy-variableContains a hyphen
userNameintReserved keyword
user_Ageuser AgeContains a space

Scope of Variables

The scope of a variable determines where in your program the variable can be accessed. C has different types of scope, but for now, we'll focus on local scope.

A variable declared inside a block of code (e.g., inside a function or a loop) has local scope. It can only be accessed within that block.

#include <stdio.h>

int main() {
  int x = 10; // x is declared and initialized within the main function's scope

  if (x > 5) {
    int y = 20; // y is declared and initialized within the if block's scope
    printf("x = %d, y = %d\n", x, y); // Accessing both x and y is allowed here
  }

  // printf("x = %d, y = %d\n", x, y); // This would cause an error because y is out of scope
  printf("x = %d\n", x); // This is fine, as x is still in scope

  return 0;
}

In this example, x is accessible throughout the main function, while y is only accessible within the if block. Trying to access y outside the if block will result in a compilation error.

Data Types in C

C offers a variety of data types to represent different kinds of data. Here are the most common ones:

Integer Types

Integer types are used to store whole numbers (numbers without a fractional part). C provides several integer types with different sizes and ranges:

  • int: The most common integer type. It typically occupies 4 bytes (32 bits) on most modern systems, but its size can vary depending on the compiler and architecture.
  • short: A smaller integer type, typically occupying 2 bytes (16 bits).
  • long: A larger integer type, typically occupying 4 or 8 bytes (32 or 64 bits).
  • long long: An even larger integer type, guaranteed to be at least 8 bytes (64 bits).

Each integer type can be further modified with the signed and unsigned keywords.

  • signed: Allows the integer to represent both positive and negative values. This is the default if you don't specify signed or unsigned.
  • unsigned: Allows the integer to represent only non-negative values (zero and positive). This effectively doubles the maximum positive value that can be stored.

Here's a table summarizing the common integer types, their typical sizes, and their ranges:

TypeSize (bytes)Range
signed char1-128 to 127
unsigned char10 to 255
short2-32,768 to 32,767
unsigned short20 to 65,535
int4-2,147,483,648 to 2,147,483,647
unsigned int40 to 4,294,967,295
long4 or 8-2,147,483,648 to 2,147,483,647 (if 4 bytes) OR -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (if 8 bytes)
unsigned long4 or 80 to 4,294,967,295 (if 4 bytes) OR 0 to 18,446,744,073,709,551,615 (if 8 bytes)
long long8-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned long long80 to 18,446,744,073,709,551,615

Example:

#include <stdio.h>
#include <limits.h> // Provides constants defining the limits of integer types

int main() {
  int age = 30;
  unsigned int count = 100;
  short smallNumber = 1000;
  long largeNumber = 1000000;

  printf("Age: %d\n", age);
  printf("Count: %u\n", count); // Use %u for unsigned integers
  printf("Small Number: %hd\n", smallNumber); // Use %hd for short integers
  printf("Large Number: %ld\n", largeNumber); // Use %ld for long integers

  printf("Maximum value of int: %d\n", INT_MAX);
  printf("Minimum value of int: %d\n", INT_MIN);
  printf("Maximum value of unsigned int: %u\n", UINT_MAX);

  return 0;
}

Floating-Point Types

Floating-point types are used to store numbers with a fractional part (decimal numbers). C provides three floating-point types:

  • float: A single-precision floating-point type, typically occupying 4 bytes.
  • double: A double-precision floating-point type, typically occupying 8 bytes. It offers more precision than float.
  • long double: An extended-precision floating-point type, typically occupying 10 or 16 bytes. It offers even more precision than double.

Example:

#include <stdio.h>

int main() {
  float price = 99.99;
  double pi = 3.14159265359;
  long double veryPrecisePi = 3.141592653589793238L; // The 'L' suffix indicates a long double constant

  printf("Price: %f\n", price);
  printf("Pi: %lf\n", pi); // Use %lf for double
  printf("Very Precise Pi: %Lf\n", veryPrecisePi); // Use %Lf for long double

  return 0;
}

Character Type

The char type is used to store single characters. It typically occupies 1 byte. Characters are represented using the ASCII (American Standard Code for Information Interchange) standard, which assigns a numerical value to each character.

Example:

#include <stdio.h>

int main() {
  char initial = 'A';
  char newline = '\n'; // Represents a newline character

  printf("Initial: %c\n", initial); // Use %c for characters
  printf("Newline: %c\n", newline);
  printf("ASCII value of A: %d\n", initial); // Prints the ASCII value of 'A' (65)

  return 0;
}

Void Type

The void type represents the absence of a type. It has several uses:

  • As the return type of a function that doesn't return a value.
  • As a pointer type, indicating a pointer to a memory location of unknown type (we'll cover pointers in detail in a later lesson).
  • In function arguments to indicate that the function takes no arguments.

Example:

#include <stdio.h>

void printMessage() { // Function that doesn't return a value
  printf("This function returns nothing.\n");
}

int main() {
  printMessage();
  return 0;
}

Operators in C

Operators are special symbols that perform operations on operands (variables and values). C provides a rich set of operators for various purposes.

Arithmetic Operators

Arithmetic operators perform mathematical calculations:

OperatorDescriptionExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulus (remainder)x % y
++Incrementx++ (post-increment), ++x (pre-increment)
--Decrementx-- (post-decrement), --x (pre-decrement)

Example:

#include <stdio.h>

int main() {
  int x = 10;
  int y = 3;

  printf("x + y = %d\n", x + y);   // Output: 13
  printf("x - y = %d\n", x - y);   // Output: 7
  printf("x * y = %d\n", x * y);   // Output: 30
  printf("x / y = %d\n", x / y);   // Output: 3 (integer division)
  printf("x %% y = %d\n", x % y);   // Output: 1 (remainder of 10 divided by 3)

  x++; // Post-increment: x becomes 11
  printf("x++ = %d\n", x);   // Output: 11

  y--; // Post-decrement: y becomes 2
  printf("y-- = %d\n", y);   // Output: 2

  return 0;
}

Important Note on Integer Division: When dividing two integers, C performs integer division, which truncates the decimal part of the result. For example, 10 / 3 results in 3, not 3.333.... To get a floating-point result, at least one of the operands must be a floating-point number.

#include <stdio.h>

int main() {
  int x = 10;
  int y = 3;

  float result = (float)x / y; // Cast x to float to perform floating-point division
  printf("x / y = %f\n", result); // Output: 3.333333

  return 0;
}

Relational Operators

Relational operators compare two operands and return a boolean value (true or false). In C, 0 represents false, and any non-zero value (typically 1) represents true.

OperatorDescriptionExample
**Equal tox ** y
!=Not equal tox != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Example:

#include <stdio.h>
#include <stdbool.h> // Include this header for using bool type

int main() {
  int x = 10;
  int y = 5;

  bool isEqual = (x == y);
  bool isGreater = (x > y);

  printf("x == y: %s\n", isEqual ? "true" : "false");   // Output: false
  printf("x > y: %s\n", isGreater ? "true" : "false"); // Output: true

  return 0;
}

Logical Operators

Logical operators combine two or more boolean expressions:

OperatorDescriptionExample
&&Logical ANDx && y
``
!Logical NOT!x

Example:

#include <stdio.h>
#include <stdbool.h>

int main() {
  int age = 25;
  bool hasLicense = true;

  bool canDrive = (age >= 18) && hasLicense; // Must be 18 or older AND have a license
  bool isTeenager = (age >= 13) && (age <= 19); // Check if age is between 13 and 19

  printf("Can drive: %s\n", canDrive ? "true" : "false");     // Output: true
  printf("Is teenager: %s\n", isTeenager ? "true" : "false"); // Output: false

  return 0;
}

Assignment Operators

Assignment operators assign a value to a variable. The most basic assignment operator is =, but C also provides compound assignment operators that combine an assignment with an arithmetic operation.

OperatorDescriptionExampleEquivalent to
=Assignmentx = y
+=Add and assignx += yx = x + y
-=Subtract and assignx -= yx = x - y
*=Multiply and assignx *= yx = x * y
/=Divide and assignx /= yx = x / y
%=Modulus and assignx %= yx = x % y

Example:

#include <stdio.h>

int main() {
  int x = 10;

  x += 5; // x = x + 5;  x becomes 15
  printf("x += 5: %d\n", x); // Output: 15

  x *= 2; // x = x * 2;  x becomes 30
  printf("x *= 2: %d\n", x); // Output: 30

  return 0;
}

Bitwise Operators

Bitwise operators perform operations on individual bits of integer values. These are particularly useful in low-level programming and embedded systems.

OperatorDescriptionExample
&Bitwise ANDx & y
|Bitwise ORx | y
^Bitwise XORx ^ y
~Bitwise NOT~x
<<Left shiftx << n
>>Right shiftx >> n

Example:

#include <stdio.h>

int main() {
  unsigned char x = 5;  // 00000101 in binary
  unsigned char y = 3;  // 00000011 in binary

  printf("x & y = %d\n", x & y); // Output: 1 (00000001)
  printf("x | y = %d\n", x | y); // Output: 7 (00000111)
  printf("x ^ y = %d\n", x ^ y); // Output: 6 (00000110)
  printf("~x = %d\n", ~x);   // Output: -6 (11111010 - two's complement)
  printf("x << 1 = %d\n", x << 1); // Output: 10 (00001010)
  printf("x >> 1 = %d\n", x >> 1); // Output: 2 (00000010)

  return 0;
}

Conditional Operator (Ternary Operator)

The conditional operator (also known as the ternary operator) is a shorthand way of writing a simple if-elsestatement.

condition ? expression1 : expression2;

If condition is true (non-zero), expression1 is evaluated and its value is returned. Otherwise, expression2 is evaluated and its value is returned.

Example:

#include <stdio.h>

int main() {
  int age = 20;
  const char *status = (age >= 18) ? "Adult" : "Minor"; // Assign "Adult" if age >= 18, otherwise "Minor"

  printf("Status: %s\n", status); // Output: Adult

  return 0;
}

Operator Precedence and Associativity

Operators have precedence and associativity rules that determine the order in which they are evaluated in an expression.

  • Precedence: Operators with higher precedence are evaluated before operators with lower precedence. For example, multiplication and division have higher precedence than addition and subtraction.
  • Associativity: When operators have the same precedence, associativity determines the order of evaluation. Associativity can be either left-to-right or right-to-left. For example, addition and subtraction have left-to-right associativity, while assignment operators have right-to-left associativity.

Here's a table summarizing the precedence and associativity of common C operators (from highest to lowest precedence):

| Precedence | Operator(s)

It's always a good idea to use parentheses to make your code more readable and avoid ambiguity, even if the precedence is clear.

Example:

#include <stdio.h>

int main() {
  int a = 10, b = 5, c = 2;

  int result1 = a + b * c;       // Multiplication has higher precedence than addition
  int result2 = (a + b) * c;     // Parentheses force addition to be performed first

  printf("result1 = %d\n", result1); // Output: 20 (10 + (5 * 2))
  printf("result2 = %d\n", result2); // Output: 30 ((10 + 5) * 2)

  return 0;
}

Practice Activities

  1. Variable Declaration and Initialization:

    • Declare an int variable named studentAge and initialize it with your age.
    • Declare a float variable named examScore and initialize it with a value between 0.0 and 100.0.
    • Declare a char variable named grade and initialize it with a letter grade ('A', 'B', 'C', etc.).
    • Print the values of all three variables using printf.
  2. Arithmetic Operators:

    • Write a program that takes two integer inputs from the user.
    • Calculate the sum, difference, product, quotient, and remainder of the two numbers.
    • Print the results of each calculation.
  3. Relational and Logical Operators:

    • Write a program that takes an integer input from the user representing their age.
    • Use relational operators to check if the age is:
      • Less than 18 (print "Minor")
      • Between 18 and 65 (print "Adult")
      • Greater than 65 (print "Senior")
    • Use logical operators to combine conditions if needed.
  4. Assignment Operators:

    • Declare an integer variable counter and initialize it to 0.
    • Use the += operator to increment the counter by 1 in a loop that runs 10 times.
    • Print the final value of the counter.
    • Then, use the -= operator to decrement the counter by 2 in a loop that runs 5 times.
    • Print the final value of the counter.
  5. Bitwise Operators:

    • Write a program that takes two integer inputs from the user.
    • Perform bitwise AND, OR, XOR, and NOT operations on the two numbers.
    • Print the results of each operation in both decimal and binary format. (Hint: You may need to write a function to convert a decimal number to binary).

Summary

In this lesson, we reviewed the fundamental concepts of C syntax, including variables, data types, and operators. We covered how to declare and initialize variables, the different data types available in C, and the various operators used to perform operations on data. Understanding these concepts is crucial for building more complex C programs.

1. Install Command Line Tools (if not already installed)

  • Open Terminal (search "Terminal" via Spotlight or find it in Applications > Utilities).
  • Install Apple's command line developer tools by running:
xcode-select --install

This installs clang (the default C compiler on macOS) and other necessary tools.


2. Write Your C Program

Use any text editor (like nano, vim, or VS Code) to write your C program.

  • Save it with a .c extension, for example, program.c.

Example minimal program (program.c):

#include <stdio.h>

int main() {
    printf("Hello, world!\n");
    return 0;
}

3. Navigate to Your Program's Directory

In Terminal, use cd to go to the folder containing your C file:

cd path/to/your/program

Use ls to list files and confirm your .c file is there.


4. Compile the C Program

Use clang or gcc to compile your program. For example:

clang program.c -o program

or

gcc program.c -o program
  • This compiles program.c into an executable named program.
  • If you omit -o program, the default executable will be a.out.

5. Run the Executable

Run your compiled program by typing:

./program

You should see the output, e.g.:

Hello, world!


Additional Tips

  • To stop a running program in Terminal (e.g., if stuck in an infinite loop), press Control + C.
  • Use nano program.c or vim program.c to edit files directly in Terminal.
  • You can also use VS Code or other editors and then compile/run from Terminal.

These steps are standard for macOS and work well for C programming in the Terminal environment[1][2][3][5][6].

Sources [1] How do I run my C program in Mac Terminal? https://www.reddit.com/r/learnprogramming/comments/1hfbkp/how_do_i_run_my_c_program_in_mac_terminal/ [2] How can I run a C program on Mac OS X using Terminal? https://stackoverflow.com/questions/32337643/how-can-i-run-a-c-program-on-mac-os-x-using-terminal [3] Developing C programs on Mac OS https://www.cs.auckland.ac.nz/~paul/C/Mac/ [4] MacOS - Compiling C Code on the Command Line https://www.youtube.com/watch?v=qOchFxcstXU [5] Similar Posts https://commandhunt.com/run-c-program-on-mac/ [6] How to run C program on Mac OS X using Terminal? - Config Router https://www.configrouter.com/how-to-run-c-program-on-mac-os-x-using-terminal-26261/ [7] Execute commands and run tools in Terminal on Mac https://support.apple.com/en-ca/guide/terminal/apdb66b5242-0d18-49fc-9c47-a2498b7c91d5/mac [8] 20 Mac Terminal Commands Every User Should Know https://www.techrepublic.com/article/16-terminal-commands-every-user-should-know/

Practice Activities

  1. Simple Calculator: Write a C program that takes two numbers as input from the user and prints their sum, difference, product, and quotient.
  2. Area of a Circle: Write a C program that takes the radius of a circle as input from the user and prints its area. (Area = pi * radius^2. Use 3.14159 for pi).
  3. Temperature Conversion: Write a C program that converts a temperature from Celsius to Fahrenheit. The formula is: Fahrenheit = (Celsius * 9/5) + 32.
  4. Command Line Arguments: Modify the command line arguments example to print the arguments in reverse order.

Here's a line-by-line explanation of a C program conversion of word or a sentence :

#include <stdio.h>
#include <string.h>
  • These lines include standard input/output and string manipulation libraries.
  • <stdio.h> is for functions like printf.
  • <string.h> is for string functions like strtok.
int main() {
  • The main function where the program execution starts.
    char sentence[] = "Hi myself Aayush here to check this sentence";
  • Declares and initializes a modifiable character array sentence with the given string.
  • This array holds the sentence you want to split into words.
  • Important: sentence is an array, not a string literal pointer, so it can be modified by strtok.
    char *words[20];  // Array to hold pointers to words
  • Declares an array of 20 pointers to char.
  • Each element will point to the start of a word (token) inside the sentence array.
  • This is how you store the split words without copying them.
    int count = 0;
  • Initializes a counter variable count to zero.
  • It keeps track of how many words have been found and stored.
    // Tokenize the sentence by space
    char *token = strtok(sentence, " ");
  • Calls strtok to tokenize the string sentence.
  • The delimiter is a space " ", so it splits the sentence into words separated by spaces.
  • strtok returns a pointer to the first token (word).
  • This pointer is stored in token.
    while (token != NULL) {
  • Starts a loop that continues as long as token is not NULL.
  • strtok returns NULL when no more tokens are found.
        words[count++] = token;
  • Stores the current token pointer into the words array at index count.
  • Then increments count by 1.
  • This keeps track of all tokens found.
        token = strtok(NULL, " []");
  • Calls strtok again with NULL as the first argument to continue tokenizing the same string.
  • The delimiters now are " []" — meaning space, left square bracket [, and right square bracket ].
  • This means the next tokens will be split by any of these characters.
  • Note: This is inconsistent with the first call where only space " " was used. Usually, the delimiters should be the same in all calls.
  • In your example sentence, no [ or ] characters exist, so effectively it still splits by space.
    }
  • Ends the while loop.
    // Print all words
    printf("Words in the sentence:\n");
  • Prints a header before listing the words.
    for (int i = 0; i < count; i++) {
  • Starts a for loop to iterate over all stored words from index 0 to count - 1.
        printf("[%s]\t", words[i]);
  • Prints each word surrounded by square brackets [word] followed by a tab \t.
  • This visually separates the words in the output.
    }
  • Ends the for loop.
    return 0;
}
  • Returns 0 to indicate successful program termination.
  • Ends the main function.

Summary of what the program does:

  • It takes a fixed sentence "Hi myself Aayush here to check this sentence".
  • Splits it into words using space (and also brackets as delimiters in subsequent calls).
  • Stores pointers to each word in an array.
  • Prints each word inside square brackets separated by tabs.

Important note about your delimiters in strtok calls:

  • The first call uses " " (space) as delimiter.
  • The second call uses " []" (space, left bracket, right bracket).

This inconsistency is unusual and can cause unexpected behavior if your sentence contains brackets. Usually, you want to use the same delimiter string in all calls, e.g.:

or

token = strtok(NULL, " []");

both times.

Certainly! Here's a line-by-line explanation of your C program that splits a sentence into words, then prints each word along with its letters:

#include <stdio.h>
#include <string.h>
  • Includes standard input/output and string handling libraries.
  • stdio.h is for functions like printf.
  • string.h is for string functions like strtok and strlen.
int main() {
  • Starts the main function where the program execution begins.
    char sentence[] = "I want to make a sentence into list of array using C";
  • Declares a modifiable character array initialized with the sentence.
  • This array will be tokenized into words.
    char *words[20];
  • Declares an array of 20 pointers to char.
  • Each pointer will point to the start of a word token inside sentence.
    int count = 0;
  • Initializes a counter to keep track of the number of words found.
    char *token = strtok(sentence, " ");
  • Calls strtok to tokenize the sentence using space " " as the delimiter.
  • Returns a pointer to the first word token.
    while (token != NULL) {
  • Starts a loop that continues until no more tokens are found (token == NULL).
        words[count++] = token;
  • Stores the pointer to the current token in words array.
  • Increments count to keep track of total words.
        token = strtok(NULL, " ");
  • Continues tokenizing the same string by passing NULL as the first argument.
  • Uses space " " as delimiter again.
  • Returns pointer to the next token or NULL if none left.
    }
  • Ends the while loop.
    // Print Letter of each word
    for (int i = 0; i < count; i++) {
  • Starts a for loop to iterate over all stored words.
        printf("Word %d: [%s\nLetters:] ", i+1, words[i]);
  • Prints the word number and the word itself inside square brackets.
  • Prints "Letters:" label to start printing letters of the word.
  • Note: There is a small formatting issue here — the \n inside the square brackets will cause a newline immediately after printing the word. You might want to move it outside or adjust.
        for (int j = 0; j < strlen(words[i]); j++) {
  • Starts a nested loop to iterate over each character of the current word.
            printf("[%c ]", words[i][j]);
  • Prints each letter of the word inside square brackets followed by a space.
        }
  • Ends the inner for loop over letters.
        printf("[\n]");//word in next line 
  • Prints a newline enclosed in square brackets (which is a bit unusual).
  • This moves output to the next line before printing the next word.
    }
  • Ends the outer for loop over words.
    return 0;
}
  • Returns 0 indicating successful program termination.
  • Ends the main function.

Suggested improvements for clearer output:

You can improve the formatting a bit for readability:

#include <stdio.h>
#include <string.h>

int main() {
    char sentence[] = "I want to make a sentence into list of array using C";
    char *words[20];
    int count = 0;

    char *token = strtok(sentence, " ");
    while (token != NULL) {
        words[count++] = token;
        token = strtok(NULL, " ");
    }

    // Print each word and its letters
    for (int i = 0; i < count; i++) {
        printf("Word %d: [%s]\nLetters: ", i + 1, words[i]);
        for (int j = 0; j < strlen(words[i]); j++) {
            printf("[%c] ", words[i][j]);
        }
        printf("\n\n"); // Blank line after each word
    }

    return 0;
}

Sample output:

Word 1: [I]
Letters: [I] 

Word 2: [want]
Letters: [w] [a] [n] [t] 

Word 3: [to]
Letters: [t] [o] 

Word 4: [make]
Letters: [m] [a] [k] [e] 

Word 5: [a]
Letters: [a] 

Word 6: [sentence]
Letters: [s] [e] [n] [t] [e] [n] [c] [e] 

Word 7: [into]
Letters: [i] [n] [t] [o] 

Word 8: [list]
Letters: [l] [i] [s] [t] 

Word 9: [of]
Letters: [o] [f] 

Word 10: [array]
Letters: [a] [r] [r] [a] [y] 

Word 11: [using]
Letters: [u] [s] [i] [n] [g] 

Word 12: [C]
Letters: [C] 

/\////////////////////////////////\/ c++ language logic question

1. Write a program to find the sum of digits of a given number.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0, digit;
    cout << "Enter a number: ";
    cin >> n;
    while (n > 0) {
        digit = n % 10;
        sum += digit;
        n /= 10;
    }
    cout << "Sum of digits: " << sum << endl;
    return 0;
}

2. Write a program to check if a number is palindrome.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int n, num, digit, rev = 0;
    cout << "Enter a number: ";
    cin >> n;
    num = n;
    while (num > 0) {
        digit = num % 10;
        rev = rev * 10 + digit;
        num /= 10;
    }
    if (n == rev)
        cout << n << " is a palindrome." << endl;
    else
        cout << n << " is not a palindrome." << endl;
    return 0;
}

3. Write a program to find the factorial of a number.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int n, fact = 1;
    cout << "Enter a number: ";
    cin >> n;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    cout << "Factorial: " << fact << endl;
    return 0;
}

4. Write a program to find the GCD of two numbers using Euclidean algorithm.

Code:

C++

#include <iostream>
using namespace std;

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main() {
    int a, b;
    cout << "Enter two numbers: ";
    cin >> a >> b;
    cout << "GCD: " << gcd(a, b) << endl;
    return 0;
}

5. Write a program to reverse an array.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int start = 0, end = 4;
    while (start < end) {
        swap(arr[start], arr[end]);
        start++;
        end--;
    }
    cout << "Reversed array: ";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

6. Write a program to find the largest element in an array.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 5, 20, 8, 15};
    int max = arr[0];
    for (int i = 1; i < 5; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    cout << "Largest element: " << max << endl;
    return 0;
}

7. Write a program to check if an array is sorted.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 5, 4}; // Change to {1, 2, 3, 4, 5} for sorted
    bool isSorted = true;
    for (int i = 0; i < 4; i++) {
        if (arr[i] > arr[i + 1]) {
            isSorted = false;
            break;
        }
    }
    if (isSorted)
        cout << "Array is sorted." << endl;
    else
        cout << "Array is not sorted." << endl;
    return 0;
}

8. Write a program to merge two sorted arrays.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int arr1[] = {1, 3, 5};
    int arr2[] = {2, 4, 6};
    int merged[6];
    int i = 0, j = 0, k = 0;
    while (i < 3 && j < 3) {
        if (arr1[i] < arr2[j])
            merged[k++] = arr1[i++];
        else
            merged[k++] = arr2[j++];
    }
    while (i < 3)
        merged[k++] = arr1[i++];
    while (j < 3)
        merged[k++] = arr2[j++];
    cout << "Merged array: ";
    for (int i = 0; i < 6; i++) {
        cout << merged[i] << " ";
    }
    return 0;
}

9. Write a program to find the second largest element in an array.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 4, 7, 5};
    int first = -1, second = -1;
    for (int i = 0; i < 5; i++) {
        if (arr[i] > first) {
            second = first;
            first = arr[i];
        } else if (arr[i] > second && arr[i] != first) {
            second = arr[i];
        }
    }
    cout << "Second largest element: " << second << endl;
    return 0;
}

10. Write a program to rotate an array by one position to the right.

Code:

C++

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int last = arr[4];
    for (int i = 4; i > 0; i--) {
        arr[i] = arr[i - 1];
    }
    arr[0] = last;
    cout << "Rotated array: ";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

obsidian source → .md

download