Programming Final

Cards (16)

  • Reasons to learn C

    • Understand how a computer works (memory management and allocation)
    • C is the fundamental language for all other languages (Python and Java can interface with C programming. Also easier to learn other programming languages)
    • Opportunity to work on open source projects
  • How to print "Hello World" in C
    1. #include<stdio.h>
    2. int main(){
    3. printf("Hello, World!\n");
    4. return 0;
    5. }
  • How to compile a C source code
    gcc -o helloWorld helloWorld.c
  • stdio.h
    The header file in your C program. Needed to access the libraries required to run the code. Provides access to functions like printf.
  • Program to take integer input from user and print it back

    1. #include <stdio.h>
    2. int main()
    3. {
    4. int testInteger;
    5. printf("Enter an integer: ");
    6. scanf("%d",&testInteger);
    7. printf("Number = %d",testInteger);
    8. return 0;
    9. }
  • Program to take string input from user and print it back

    1. #include<stdio.h>
    2. int main()
    3. {
    4. char str[100];
    5. printf("Please type a word:\n");
    6. gets(str);
    7. puts("You entered: ");
    8. puts(str);
    9. return 0;
    10. }
  • Program to take two integers from user and print their sum

    1. #include <stdio.h>
    2. int main()
    3. {
    4. int a, b, c;
    5. printf("Enter the first value: ");
    6. scanf("%d", &a);
    7. printf("Enter the second value: ");
    8. scanf("%d",&b);
    9. c = a+b;
    10. printf("%d +%d = %d\n", a, b, c);
    11. return 0;
    12. }
  • C compilers in macOS and Windows
    • macOS: clang
    • Windows: mingw
  • Format string and &variable in scanf()
    • Format string - specifies the format of the input
    • &variable - pointer to the variable to store the input value
  • scanf("%[^\n]", str_array) and getchar()
    • %[^\n] scans for a string until a newline character
    • getchar() reads the newline character left in the buffer after scanf()
  • EOF
    End-of-file signal sent to indicate the end of a file
  • Function prototype
    Declaration of a function before its definition
  • Pointer in C
    A variable that holds the address of another variable
  • &, *

    • & gives the address of an object
    • * is the indirection/dereferencing operator to access the object a pointer points to
  • Program to add two user-given numbers using pointers
    1. #include <stdio.h>
    2. int main()
    3. {
    4. int num1, num2, sum;
    5. int *ptr1, *ptr2;
    6. ptr1 = &num1;
    7. ptr2 = &num2;
    8. printf("Enter any two numbers: ");
    9. scanf("%d%d", ptr1, ptr2);
    10. sum = *ptr1 + *ptr2;
    11. printf("Sum = %d", sum);
    12. return 0;
    13. }
  • scanf() doesn't need & on char[] (strings)