This commit is contained in:
Joaquin Gottlebe
2025-07-30 15:57:48 +02:00
parent e49fcfac46
commit a639c34cee
273 changed files with 20151 additions and 0 deletions
@@ -0,0 +1,50 @@
import java.util.HashSet;
public class BaumHashSet {
public static void main(String[] args) {
int n = 17;
HashSet<Integer> baumSet = new HashSet<>();
for (int i = 0; i < n; i++) {
baumSet.add(i * 2);
}
for (Integer value : baumSet) {
System.out.println(value);
}
Integer smallestGreater = null;
for (Integer value : baumSet) {
if (value > n) {
if (smallestGreater == null || value < smallestGreater) {
smallestGreater = value;
}
}
}
if (smallestGreater != null) {
System.out.println("Smallest element > " + n + ": " + smallestGreater);
} else {
System.out.println("No element greater than " + n);
}
Integer smallest = null;
for (Integer value : baumSet) {
if (smallest == null || value < smallest) {
smallest = value;
}
}
if (smallest != null) {
System.out.println("Smallest element: " + smallest);
baumSet.remove(smallest); // Remove it
} else {
System.out.println("Set is empty");
}
System.out.println("Set after removal: " + baumSet);
}
}
@@ -0,0 +1,32 @@
import java.util.TreeMap;
public class BaumMap {
public static void main(String[] args) {
int n = 17;
TreeMap<Integer, Integer> baumMap = new TreeMap<>();
for (int i = 0; i < n; i++) {
baumMap.put(i, i * 2);
}
for (Integer value : baumMap.values()) {
System.out.println(value);
}
Integer c = null;
for (Integer value : baumMap.values()) {
if (value > n) {
c = value;
System.out.println(c);
break;
}
}
var d = baumMap.pollFirstEntry();
System.out.println(d.getValue());
}
}
@@ -0,0 +1,26 @@
import java.util.TreeSet;
public class BaumSet {
public static void main(String[] args) {
int n = 17;
TreeSet<Integer> baumSet = new TreeSet<>();
for (int i = 0; i < n; i++) {
baumSet.add(i * 2);
}
for (Integer baum : baumSet) {
System.out.println(baum);
}
int c = baumSet.higher(n);
System.out.println(c);
int d = baumSet.pollFirst();
System.out.println(d);
}
}
@@ -0,0 +1,30 @@
/** Bindung.java
*
* Eine Klasse, die am Beispiel des figure-Pakets
* statische und dynamische Typen ausprobiert
*/
import figure.*;
class Bindung {
public static void main(String[] args) {
Figure f = new Square(1);
f.moveTo(2, 3);
f.getArea();
// f.show();
if (f instanceof Square) {
((Square) f).show(); // analog: (double)17
}
System.out.println("Flaecheninhalt: " + f.getArea());
f = new Circle(10);
System.out.println("Flaecheninhalt: " + f.getArea());
}
}
// Bindung
+27
View File
@@ -0,0 +1,27 @@
public class Buch extends Printmedia {
public Buch(int currentPage, int maxPage) {
super(currentPage, maxPage);
}
public static void main(String[] args) {
Buch lotr1 = new Buch(0, 448);
try {
lotr1.read(500);
} catch (RuntimeException e) {
System.out.println("Fehler beim lesen: " + e.getMessage());
}
System.out.println("Aktuelle Seiten nach dem Leseversuch: " + lotr1.getCurrentPage());
try {
lotr1.read(100);
} catch (RuntimeException e) {
System.out.println("Fehler beim lesen: " + e.getMessage());
}
System.out.println("Aktuelle Seiten nach dem Leseversuch: " + lotr1.getCurrentPage());
lotr1.maxPage = 531;
System.out.println("Aktuelle Seiten nach dem Leseversuch: " + lotr1.getMaxPage());
}
}
@@ -0,0 +1,41 @@
package figure;
public class Circle extends Figure {
private int radius;
public Circle() {
super(0, 0);
this.radius = 0;
}
public Circle(int radius) {
super(0, 0);
this.radius = radius;
}
public Circle(int x, int y, int radius) {
super(x, y);
this.radius = radius;
}
@Override
public int getSize() {
return radius;
}
@Override
public void setSize(int radius) {
this.radius = radius;
}
@Override
public double getArea() {
return 3.14 * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * 3.14 * radius;
}
}
@@ -0,0 +1,22 @@
public class Display {
static void display(int n) {
int m = 11;
System.out.printf("A1: m = %d, n = %d\n", m, n);
}
public static void main(String[] args) {
int a = 12;
int m = 1;
int n = 2;
display(a);
if (m == 1) {
int n2 = 22;
System.out.printf("A2: m = %d, n = %d\n", m, n2);
}
System.out.printf("A3: m = %d, n = %d\n", m, n);
}
}
@@ -0,0 +1,39 @@
package figure;
public abstract class Figure {
private Point pos;
// only visible to subclasses
protected Figure() {
this.pos = new Point();
}
protected Figure(int x, int y) {
this.pos = new Point(x, y);
}
// public methods
public String getPos() {
return this.pos.toString();
}
public void moveTo(int x, int y) {
this.pos.moveTo(x, y);
}
public void moveBy(int x, int y) {
this.pos.moveBy(x, y);
}
// abstract methods
public abstract int getSize();
public abstract void setSize(int size);
public abstract double getArea();
public abstract double getPerimeter();
}
+26
View File
@@ -0,0 +1,26 @@
class Gcd{
public static int gcd(int num, int denom){
int x = num;
int y = denom;
if (x == 0)
return y;
if (y == 0)
return x;
if (x < 0)
x = -x;
if (y < 0)
y = -y;
while (x != y) {
if (x > y)
x = x - y;
else
y = y - x;
}
return x;
}
}
@@ -0,0 +1,21 @@
public abstract class Geschirr{
protected int durchmesser;
protected int hoehe;
protected int gewicht;
protected char function;
public Geschirr(int durchmesser, int hoehe, int gewicht, char function){
this.durchmesser = durchmesser;
this.hoehe = hoehe;
this.gewicht = gewicht;
this.function = function;
}
public int getGewicht(){
return gewicht;
}
public void setGewicht(int gewicht){
this.gewicht = gewicht;
}
}
@@ -0,0 +1,20 @@
public class Geschirrschrank{
private int kapazitaet;
public Geschirrschrank(){
this.kapazitaet = 0;
}
public Geschirrschrank(int kapazitaet){
this.kapazitaet = kapazitaet;
}
public void einraeumen(Geschirr pGeschirr){
if (pGeschirr.getGewicht() <= kapazitaet) {
kapazitaet -= pGeschirr.getGewicht();
System.out.println("Geschirr eingeräumt. Verbleibende Kapazität: " + kapazitaet + " g");
} else {
System.out.println("Nicht genug Platz im Schrank!");
}
}
}
+5
View File
@@ -0,0 +1,5 @@
public class Glas extends Geschirr{
public Glas(int durchmesser, int hoehe, int gewicht, char function){
super(durchmesser, hoehe, gewicht, function);
}
}
@@ -0,0 +1,16 @@
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> baume = new HashSet<>();
baume.add("Aal");
baume.add("Tanne");
baume.add("Birke");
baume.add("Baum");
for (String baum : baume) {
System.out.println(baum);
}
}
}
+63
View File
@@ -0,0 +1,63 @@
public class List<T> {
private ListElement<T> head;
public void insert(ListElement<T> elem) {
elem.next = head;
head = elem;
}
public void insert(ListElement<T> newElem, int i) {
if (i == 0)
insert(newElem);
else {
ListElement<T> tmp = head;
ListElement<T> prev = null;
int l = 0;
// Aufsuchen des i-ten Elements
while (l < i) {
prev = tmp;
tmp = prev.next;
l++;
} // l == i ist erreicht
prev.next = newElem;
newElem.next = tmp;
}
}
public boolean delete() {
if (head == null) {
return false;
}
head = head.next;
return true;
}
public boolean isEmpty() {
return head == null;
}
public int length() {
int count = 0;
ListElement<T> current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}
public void show() {
ListElement<T> current = head;
if (current == null) {
System.out.println("List is empty.");
return;
}
System.out.print("List: ");
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}
@@ -0,0 +1,30 @@
public class ListElement<T> {
public T data;
public ListElement<T> next;
public ListElement(T data) {
this.data = data;
this.next = null;
}
public ListElement(T data, ListElement<T> next) {
this.data = data;
this.next = next;
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public ListElement<T> getNext() {
return this.next;
}
public void setNext(ListElement<T> next) {
this.next = next;
}
}
@@ -0,0 +1,21 @@
public class Lokomotive extends Zugteil {
private int id;
private String name;
private int maxWaggons;
public Lokomotive(int laenge, boolean status, int id, String name, int maxWaggons) {
super(laenge, status);
this.id = id;
this.name = name;
this.maxWaggons = maxWaggons;
}
public int getMaxWaggons() {
return maxWaggons;
}
@Override
public String toString() {
return "<" + id + ", " + name + ", " + getLaenge() + ">";
}
}
+47
View File
@@ -0,0 +1,47 @@
import figure.Square;
import figure.Circle;
public class Main {
public static void main(String[] args) {
Square square = new Square(0, 0, 10);
System.out.println(square.getSize());
square.setSize(20);
System.out.println(square.getSize());
System.out.println(square.getArea());
System.out.println(square.getPerimeter());
System.out.println(square.getPos());
square.moveTo(1, 1);
System.out.println(square.getPos());
square.moveBy(1, 1);
System.out.println(square.getPos());
Circle circle = new Circle(0, 0, 10);
System.out.println(circle.getSize());
circle.setSize(20);
System.out.println(circle.getSize());
System.out.println(circle.getArea());
System.out.println(circle.getPerimeter());
System.out.println(circle.getPos());
circle.moveTo(1, 1);
System.out.println(circle.getPos());
circle.moveBy(1, 1);
System.out.println(circle.getPos());
// ue10
System.out.println("\nue10\n");
Square square1 = new Square(1, 2, 3);
square1.show();
System.out.println(square1);
Square square2 = new Square(square1);
square2.show();
System.out.println(square2);
square2.moveTo(99, 99);
square2.setSize(42);
square1.show();
square2.show();
}
}
@@ -0,0 +1,5 @@
public class Mueslischale extends Geschirr{
public Mueslischale(int durchmesser, int hoehe, int gewicht, char function){
super(durchmesser, hoehe, gewicht, char function);
}
}
+143
View File
@@ -0,0 +1,143 @@
/*
* Name: Joaquin Gottlebe
* Matrikelnummer: 829101
*/
import java.util.List;
import java.util.Queue;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.HashSet;
import java.util.Set;
/**
* A graph node that can store a tag, info,
* and connections to neighboring nodes.
*/
public class Node<T, I> implements Taggable<T> {
// Private member variables
private T tag;
private I info;
private List<Node<T, I>> neighbors;
// Constructor
public Node(T tag, I info) {
this.tag = tag;
this.info = info;
this.neighbors = new ArrayList<>();
}
// Set tag.
@Override
public void setTag(T tag) {
this.tag = tag;
}
// Get tag.
public T getTag() {
return tag;
}
// Get info.
public I getInfo() {
return info;
}
// Set info.
public void setInfo(I info) {
this.info = info;
}
// Get neighbors.
public List<Node<T, I>> getNeighbors() {
return neighbors;
}
// Connects this node to another node.
public void connect(Node<T, I> other) {
if (!neighbors.contains(other)) {
neighbors.add(other);
other.connect(this);
}
}
// Disconnects this node from another node.
public void disconnect(Node<T, I> other) {
if (neighbors.contains(other)) {
neighbors.remove(other);
other.disconnect(this);
}
}
// Breadth-first traversal of the network starting from this node. Returns nodes
// in a list.
public List<Node<T, I>> traverse() {
List<Node<T, I>> visitedOrder = new ArrayList<>();
Set<Node<T, I>> visited = new HashSet<>();
Queue<Node<T, I>> queue = new LinkedList<>();
queue.add(this);
visited.add(this);
while (!queue.isEmpty()) {
Node<T, I> current = queue.poll();
visitedOrder.add(current);
for (Node<T, I> neighbor : current.getNeighbors()) {
if (!visited.contains(neighbor)) {
queue.add(neighbor);
visited.add(neighbor);
}
}
}
return visitedOrder;
}
// Prints this nodes tag and info.
public void printNode() {
System.out.println("Node: " + tag + ", Info: " + info);
System.out.println();
}
// Prints neighbours of this node.
public void printNeighbors() {
System.out.print("Neighbors of " + tag + ": ");
if (neighbors.isEmpty()) {
System.out.println("no neighbors\n");
} else {
for (Node<T, I> neighbor : neighbors) {
System.out.print(neighbor.getTag() + " ");
}
System.out.println('\n');
}
}
// Uses traverse() to print the network of this node. Avoids edge duplications.
public void printNetwork() {
List<Node<T, I>> networkNodes = traverse();
Set<String> printedEdges = new HashSet<>();
for (Node<T, I> node : networkNodes) {
for (Node<T, I> neighbor : node.getNeighbors()) {
// Canonicalize edge to avoid duplicates
String canonicalEdge = node.getTag().toString().compareTo(neighbor.getTag().toString()) <= 0
? node.getTag().toString() + "-" + neighbor.getTag().toString()
: neighbor.getTag().toString() + "-" + node.getTag().toString();
if (!printedEdges.contains(canonicalEdge)) {
System.out.println(
node.getTag().toString() + node.getInfo().toString() +
" - " +
neighbor.getTag().toString() + neighbor.getInfo().toString());
printedEdges.add(canonicalEdge);
}
}
}
System.out.println();
}
}
+32
View File
@@ -0,0 +1,32 @@
public class Pair<X extends Number, Y extends Number> {
private X first;
private Y second;
public Pair(X first, Y second) {
this.first = first;
this.second = second;
}
public X getFirst() {
return first;
}
public void setFirst(X first) {
this.first = first;
}
public Y getSecond() {
return second;
}
public void setSecond(Y second) {
this.second = second;
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
@@ -0,0 +1,41 @@
public class PairComparable<X extends Number & Comparable<X>, Y extends Number>
implements Comparable<PairComparable<X, Y>> {
private X first;
private Y second;
public PairComparable(X first, Y second) {
this.first = first;
this.second = second;
}
public X getFirst() {
return first;
}
public void setFirst(X first) {
this.first = first;
}
public Y getSecond() {
return second;
}
public void setSecond(Y second) {
this.second = second;
}
@Override
public int compareTo(PairComparable<X, Y> other) {
double thisFraction = this.first.doubleValue() / this.second.doubleValue();
double otherFraction = other.first.doubleValue() / other.second.doubleValue();
return Double.compare(thisFraction, otherFraction);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
@@ -0,0 +1,24 @@
import java.util.ArrayList;
import java.util.Collections;
public class PairComparableTest {
public static void main(String[] args) {
ArrayList<PairComparable<Integer, Integer>> pairs = new ArrayList<>();
pairs.add(new PairComparable<>(5, 100));
pairs.add(new PairComparable<>(2, 50));
pairs.add(new PairComparable<>(8, 200));
pairs.add(new PairComparable<>(3, 75));
System.out.println("Vor dem Sortieren:");
for (PairComparable<Integer, Integer> pair : pairs) {
System.out.println(pair);
}
Collections.sort(pairs);
System.out.println("\nNach dem Sortieren (nach erstem Element):");
for (PairComparable<Integer, Integer> pair : pairs) {
System.out.println(pair);
}
}
}
@@ -0,0 +1,6 @@
public class PairTest {
public static void main(String[] args) {
Pair<Integer, Integer> intPair = new Pair<>(10, 20);
System.out.println(intPair);
}
}
+37
View File
@@ -0,0 +1,37 @@
package figure;
public class Point {
private int x;
private int y;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void moveTo(int x, int y) {
this.x = x;
this.y = y;
}
public void moveBy(int x, int y) {
this.x += x;
this.y += y;
}
public String toString() {
return this.x + ", " + this.y;
}
}
@@ -0,0 +1,27 @@
public class Printmedia implements Readable {
private int currentPage;
protected int maxPage;
public Printmedia(int currentPage, int maxPage) {
this.currentPage = currentPage;
this.maxPage = maxPage;
}
public int getCurrentPage() {
return currentPage;
}
public int getMaxPage() {
return maxPage;
}
@Override
public void read(int amount) {
if (currentPage + amount > maxPage) {
throw new RuntimeException(
"Cannot read because currentPage would exceed maxPage");
}
currentPage += amount;
}
}
@@ -0,0 +1,57 @@
class Rational{
private int num;
private int denom;
public Rational(){
this.num = 0;
this.denom = 1;
}
public Rational(int num){
this.num = num;
this.denom = 1;
}
public Rational(int num, int denom){
this.num = num;
this.denom = denom;
}
public void reduce(){
int gcd = Gcd.gcd(this.num, this.denom);
this.num = this.num / gcd;
this.denom = this.denom / gcd;
}
public void extent(int extent){
this.num = this.num * extent;
this.denom = this.denom * extent;
}
public String toString(){
return this.num + "/" + this.denom;
}
public String toStringReduced(){
reduce();
return toString();
}
public Rational mult(Rational number){
Rational r = new Rational();
r.num = this.num * number.num;
r.denom = this.denom * number.denom;
r.reduce();
return r;
}
public static void main(String[] args){
Rational rat = new Rational(12, 24);
System.out.println(rat.toString());
System.out.println(rat.toStringReduced());
rat.extent(12);
System.out.println(rat.toString());
}
}
@@ -0,0 +1,3 @@
public interface Readable {
public void read(int amount);
}
@@ -0,0 +1,6 @@
class SimpleOutputDemo{
public static void main(String[] args){
for(int i = 0; i < args.length; i++)
System.out.println(args[args.length - i - 1]);
}
}
@@ -0,0 +1,55 @@
package figure;
public class Square extends Figure {
private int edgeLength;
public Square() {
super(0, 0);
this.edgeLength = 0;
}
public Square(int edgeLength) {
super(0, 0);
this.edgeLength = edgeLength;
}
public Square(int x, int y, int edgeLength) {
super(x, y);
this.edgeLength = edgeLength;
}
public Square(Square other) {
String[] pos = other.getPos().split(",");
int x = Integer.parseInt(pos[0].trim());
int y = Integer.parseInt(pos[1].trim());
super.moveTo(x, y);
this.edgeLength = other.getSize();
}
@Override
public int getSize() {
return edgeLength;
}
@Override
public void setSize(int edgeLength) {
this.edgeLength = edgeLength;
}
@Override
public double getArea() {
return edgeLength * edgeLength;
}
@Override
public double getPerimeter() {
return edgeLength * 4;
}
public void show() {
System.out.println(
"Pos:" + this.getPos() + "edgeLength: " + this.getSize());
}
}
@@ -0,0 +1,55 @@
/** Static.java
*
* Eine Klasse, die Effekte mit Klassenvariablen demonstriert.
*/
class Static {
int n;
static int snum;
void increase() {
n++;
snum++;
}
void output() {
System.out.println("n = " + n + ", snum = " +snum);
}
static void set(int n) {
snum = n;
}
public static void main(String[] args) {
Static ex1 = new Static();
Static ex2 = new Static();
ex1.output();
ex2.output();
System.out.println();
ex1.increase();
ex1.output();
ex2.output();
Static.set(5); // Aufruf statische Methode; alternativ: Static.set(5);
Static ex3 = new Static();
System.out.println();
ex1.output();
ex2.output();
ex3.output();
}
}
// Static
@@ -0,0 +1,17 @@
/*
* Name: Joaquin Gottlebe
* Matrikelnummer: 829101
*/
/**
* The Taggable interface defines a generic type T
* that allows objects to set and get a tag of type T.
*
* @param <T> the type of the tag
*/
interface Taggable<T> {
void setTag(T tag);
T getTag();
}
+60
View File
@@ -0,0 +1,60 @@
/*
* Name: Joaquin Gottlebe
* Matrikelnummer: 829101
*/
import java.util.Arrays;
import java.util.List;
// Test class to test Node and Taggable class
public class Test {
public static void main(String[] args) {
// Create nodes with String tags and List<Integer> info
Node<String, List<Integer>> A = new Node<>("A", Arrays.asList(1, 2, 3));
Node<String, List<Integer>> B = new Node<>("B", Arrays.asList(4, 5, 6));
Node<String, List<Integer>> C = new Node<>("C", Arrays.asList(7, 8, 9));
Node<String, List<Integer>> D = new Node<>("D", Arrays.asList(10, 11, 12));
Node<String, List<Integer>> E = new Node<>("E", Arrays.asList(13, 14, 15));
Node<String, List<Integer>> F = new Node<>("F", Arrays.asList(16, 17, 18));
Node<String, List<Integer>> G = new Node<>("G", Arrays.asList(19, 20, 21));
// Print node
A.printNode();
// Build connections between nodes
A.connect(F);
A.connect(G);
G.connect(F);
G.connect(B);
F.connect(B);
F.connect(C);
C.connect(D);
D.connect(E);
// Print neighbors
A.printNeighbors();
// Print network
System.out.println("Graph 1:");
A.printNetwork();
// Change network
A.setTag("A2");
B.setTag("B2");
G.setTag("G2");
A.setInfo(Arrays.asList(23, 24, 25));
B.setInfo(Arrays.asList(5, 6));
G.setInfo(Arrays.asList(19, 20, 21, 22));
A.connect(B);
B.connect(D);
C.connect(E);
G.disconnect(F);
F.disconnect(C);
C.disconnect(D);
// Print network
System.out.println("Graph 2:");
A.printNetwork();
}
}
@@ -0,0 +1,16 @@
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> baume = new TreeSet<>();
baume.add("Aal");
baume.add("Tanne");
baume.add("Birke");
baume.add("Baum");
for (String baum : baume) {
System.out.println(baum);
}
}
}
@@ -0,0 +1,34 @@
import java.util.Scanner;
public class UseList {
public static void main(String[] args) {
List<Integer> list = new List<>();
list.insert(new ListElement<>(10));
list.insert(new ListElement<>(20));
list.insert(new ListElement<>(30));
list.show();
Scanner scanner = new Scanner(System.in);
System.out.print("Positive integer please: ");
int number = scanner.nextInt();
try:
list.insert(new ListElement<>(40), number);
catch:
System.out.println("Length: " + list.length());
list.delete();
list.show();
System.out.println("Is empty? " + list.isEmpty());
list.delete();
list.delete();
list.show();
System.out.println("Is empty? " + list.isEmpty());
}
}
@@ -0,0 +1,33 @@
/**
* UsePoint.java
*
* Ein Programm, das Objekte der Klasse Point erzeugt und manipuliert.
*/
class UsePoint {
public static void main(String[] args) {
// Erzeugen von zwei Exemplaren des Typs Point mit den Namen p und q;
// p soll an den Koordinaten (30,10) erzeugt werden,
// q mit dem parameterlosen Konstruktor am Koordinatenursprung.
Point p = new Point(30,10);
Point q = new Point();
// Verschieben von q auf die Koordinaten (40,40)
q.moveTo(40,20);
// Ausgabe der Attribute von p und q
System.out.println();
System.out.println(" x-Koordinate von p: " + p.getX());
System.out.println(" y-Koordinate von p: " + p.getY());
System.out.println();
System.out.println(" x-Koordinate von q: " + q.getX());
System.out.println(" y-Koordinate von q: " + q.getY());
System.out.println();
}
}
// UsePoint
@@ -0,0 +1,37 @@
// UseRational.java.1-3 (Version .1-3)
import java.util.Scanner;
class UseRational {
public static void main(String[] args) {
// Definitionen
Scanner scanner = new Scanner(System.in);
Rational r;
// Dialog
System.out.println();
System.out.print("Geben Sie den Zaehler ein: ");
int a = scanner.nextInt();
System.out.print("Geben Sie den Nenner ein: ");
int b = scanner.nextInt();
System.out.println();
// Rational-Objekt erzeugen
r = new Rational(a,b);
// Methodenaufrufe
System.out.println(r.toString()); // Bruch ausgeben
System.out.println(r.toStringReduced());
r.extent(12);
System.out.println(r.toString());
Rational rMult = new Rational(2,3);
Rational r2 = r.mult(rMult);
System.out.println(r2.toString());
}
}
// UseRational
@@ -0,0 +1,48 @@
/** VariablenAusgabe.java
*
* Ein Programm, das die Vereinbarung sowie
* die Ausgabe von Variablen einfacher Datentypen
* demonstriert.
*/
class VariablenAusgabe {
public static void main (String[] args) {
int num1 = 12;
int num2 = -4;
System.out.println(num1);
System.out.println(num2);
System.out.println();
System.out.println(5);
System.out.println(5 + num2);
System.out.println();
System.out.print(5);
System.out.println(num2);
System.out.println(num1 + " " + num2);
System.out.println("Wert von num1: " + num1);
String string = "Hello World!";
string = string.concat(" From Joaquin.");
string = string.replace('e', 'a');
string = string.toLowerCase();
string = string.toUpperCase();
System.out.println(string);
String[] split = string.split("! ", 2);
System.out.println(split[0]);
System.out.println(split[1]);
boolean stringsAreEqual = split[0].equals(split[1]);
System.out.println(stringsAreEqual);
}
}
// VariablenAusgabe
@@ -0,0 +1,65 @@
/**
* Verweise.java
*
* Ein Programm, das die Funktionsweise von Verweisen demonstriert.
*/
class Verweise {
public static void main(String[] args) {
// Definitionen
Point p1, p2;
// Initialisieren
p1 = null;
p2 = new Point();
System.out.println();
System.out.println("Die Werte der Referenzvariablen sind:");
System.out.println();
System.out.println(" p1 = " + p1);
System.out.println(" p2 = " + p2);
System.out.println();
// Das kann zur Zeit nicht gut gehen:
// System.out.println(" p1 = (" + p1.x + "," + p1.y + ")");
// Erzeugen von p1 und Verschieben von p2
p1 = new Point();
p2.moveTo(2, 3);
System.out.println();
System.out.println("Klassen sind Referenz-Datentypen:");
System.out.println();
System.out.println(" p1 = " + p1);
System.out.println(" p2 = " + p2);
System.out.println();
System.out.println(" p1 = (" + p1.x + "," + p1.y + ")");
System.out.println(" p2 = (" + p2.x + "," + p2.y + ")");
System.out.println();
System.out.println("Jetzt wird p2 = p1 gesetzt.");
System.out.println();
p2 = p1;
System.out.println(" p1 = " + p1);
System.out.println(" p2 = " + p2);
System.out.println();
System.out.println("Nach dem Verschieben von p1 nach (4,5):");
p1.moveTo(4, 5);
System.out.println();
System.out.println(" p1 = (" + p1.x + "," + p1.y + ")");
System.out.println(" p2 = (" + p2.x + "," + p2.y + ")");
System.out.println();
}
}
// Verweise
@@ -0,0 +1,28 @@
/**
* Vorlage.java
*
* Programmfragment, das Tastatureingaben ermoeglicht
*
*/
import java.util.Scanner;
// Klassenname MUSS = Dateiname sein
class Vorlage {
public static void main(String[] args) {
// Boilerplate Code - bitte erstmal einfach verwenden, Details folgen später
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
int i = scanner.nextInt();
// Methoden für weitere Datentypen existieren
// siehe API
}
}
// Vorlage
+17
View File
@@ -0,0 +1,17 @@
public class Wagen extends Zugteil {
private int kapazitaet;
public Wagen(int laenge, boolean status, int kapazitaet) {
super(laenge, status);
this.kapazitaet = kapazitaet;
}
public int getCap() {
return kapazitaet;
}
@Override
public String toString() {
return "[" + kapazitaet + ", " + getLaenge() + "]";
}
}
+125
View File
@@ -0,0 +1,125 @@
import java.util.LinkedList;
import java.util.Collections;
public class Zug {
private String name;
private LinkedList<Zugteil> zugteile;
public Zug(Lokomotive lok) {
zugteile = new LinkedList<>();
zugteile.add(lok);
}
public void addWagen(Wagen wagen) {
Zugteil firstteil = zugteile.getFirst();
if (firstteil instanceof Lokomotive) {
Lokomotive lok = (Lokomotive) firstteil;
if (lok.getMaxWaggons() > this.getNumberOfWaggons()) {
zugteile.add(wagen);
} else {
throw new IllegalStateException("max Wagen fuer lok erreicht.");
}
}
}
public void addWagen(Wagen wagen, int i) {
if (i <= 0) {
throw new IllegalArgumentException("Wagen dürfen nicht vor der Lokomotive eingefügt werden.");
}
zugteile.add(i, wagen);
}
public void print() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < zugteile.size(); i++) {
sb.append(zugteile.get(i).toString());
if (i < zugteile.size() - 1) {
sb.append(" - ");
}
}
System.out.println(sb.toString());
}
public int getNumberOfWaggons() {
int numWaggons = 0;
for (Zugteil zugteil : zugteile) {
if (zugteil instanceof Wagen) {
numWaggons++;
}
}
return numWaggons;
}
public int getPassengers() {
int cap = 0;
for (Zugteil zugteil : zugteile) {
if (zugteil instanceof Wagen) {
Wagen wagen = (Wagen) zugteil;
cap += wagen.getCap();
}
}
return cap;
}
public int getLength() {
int laength = 0;
for (Zugteil zugteil : zugteile) {
laength += zugteil.getLaenge();
}
return laength;
}
public void changeLoc(Lokomotive lok) {
if (zugteile.getFirst() instanceof Lokomotive) {
zugteile.removeFirst();
}
zugteile.addFirst(lok);
}
public Wagen removeCar(int i) {
if (zugteile.get(i) instanceof Wagen) {
return (Wagen) zugteile.remove(i);
}
return null;
}
public void relink(Zug other) {
if (this == other) {
throw new IllegalArgumentException("Ein Zug kann nicht an sich selbst angehängt werden.");
}
LinkedList<Wagen> wagonsToMove = new LinkedList<>();
for (int i = 1; i < other.zugteile.size(); i++) {
Zugteil zt = other.zugteile.get(i);
if (zt instanceof Wagen) {
wagonsToMove.add((Wagen) zt);
}
}
for (Wagen w : wagonsToMove) {
other.zugteile.remove(w);
}
for (Wagen w : wagonsToMove) {
this.addWagen(w);
}
}
public void revert() {
if (zugteile.isEmpty() || zugteile.size() <= 1) {
return;
}
Zugteil lok = zugteile.get(0);
LinkedList<Zugteil> wagons = new LinkedList<>(zugteile.subList(1, zugteile.size()));
java.util.Collections.reverse(wagons);
zugteile.clear();
zugteile.add(lok);
zugteile.addAll(wagons);
}
}
@@ -0,0 +1,42 @@
public class ZugTest {
public static void main(String[] args) {
// 1. Lokomotive „Big Chief“ mit Typ-ID 5311 und Länge 23m
Lokomotive bigChief = new Lokomotive(23, true, 5311, "Big Chief", 10); // maxWaggons auf 10 gesetzt
// 2. Zug „Santa Fe“ mit Lok „Big Chief“
Zug santaFe = new Zug(bigChief);
// 3. Drei Wagen an „Santa Fe“ anhängen
santaFe.addWagen(new Wagen(12, true, 50));
santaFe.addWagen(new Wagen(15, true, 75));
santaFe.addWagen(new Wagen(20, true, 100));
// 4. Lokomotive „Steel Horse“ mit Typ-ID 5409 und Länge 21m
Lokomotive steelHorse = new Lokomotive(21, true, 5409, "Steel Horse", 10);
// 5. Zug „Rio Grande Express“ mit Lok „Steel Horse“
Zug rioGrandeExpress = new Zug(steelHorse);
// 6. Zwei Wagen an „Rio Grande Express“ anhängen
rioGrandeExpress.addWagen(new Wagen(13, true, 60));
rioGrandeExpress.addWagen(new Wagen(18, true, 80));
// Ausgabe vor dem Übertragen der Wagen
System.out.println("Vor dem Übertragen:");
System.out.print("Santa Fe: ");
santaFe.print();
System.out.print("Rio Grande Express: ");
rioGrandeExpress.print();
// 7. Alle Wagen von „Santa Fe“ zu „Rio Grande Express“ übergeben
rioGrandeExpress.relink(santaFe);
// Ausgabe nach dem Übertragen
System.out.println("\nNach dem Übertragen:");
System.out.print("Santa Fe: ");
santaFe.print();
System.out.print("Rio Grande Express: ");
rioGrandeExpress.print();
}
}
@@ -0,0 +1,13 @@
public class Zugteil {
private int laenge;
private boolean status;
public Zugteil(int laenge, boolean status) {
this.laenge = laenge;
this.status = status;
}
public int getLaenge() {
return laenge;
}
}
+38
View File
@@ -0,0 +1,38 @@
#include <stdio.h>
int main()
{
int i;
int ar[4];
ar[0] = 10;
ar[1] = 20;
ar[2] = 30;
ar[3] = 40;
int arLen = (int)sizeof(ar) / sizeof(int);
printf("\nar: %p\t &ar[0]: %p", ar, &ar[0]);
printf("\n\nElemente von ar, indiziert:\n");
for (i = 0; i < arLen; i++){
printf("%d\t", ar[i]);
}
printf("\n\nAdressen:\n");
for (i = 0; i < arLen; i++){
printf("%p\t", &ar[i]);
}
printf("\n\nElemente von ar, referenziert:\n");
for (i = 0; i < arLen; i++){
printf("%d\t", *(ar + i));
}
printf("\n\nAdressen:\n");
for (i = 0; i < arLen; i++){
printf("%p\t", ar + i);
}
printf("\n\n");
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#include <stdio.h>
int main()
{
int i;
int ar[5];
ar[0] = 10;
ar[1] = 20;
ar[2] = 30;
ar[3] = 40;
int arLen = (int)sizeof(ar) / sizeof(int) + 2;
printf("\nar: %p \t &ar[0]: %p\n", ar, &ar[0]);
printf("\n\nElemente von ar, indiziert:\n");
for (int i = 0; i < arLen; i++){
printf("%d\t", ar[i]);
}
printf("\n\nAdressen:\n");
for (int i = 0; i < arLen; i++){
printf("%p\t", &ar[i]);
}
printf("\n\nElemente von ar, referenziert:\n");
for (int i = 0; i < (sizeof(ar)/sizeof(int)) + 2; i++){
printf("%d\t", *(ar + i));
}
printf("\n\nAdressen:\n");
for (int i = 0; i < (sizeof(ar)/sizeof(int)) + 2; i++){
printf("%p\t", ar+i);
}
printf("\n\n");
return 0;
}
@@ -0,0 +1,258 @@
/*
* Name: Joaquin Gottlebe
* Matrikelnummer: 829101
*/
// Import dependencies
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Defines Constants
#define N 5
// Defines structs
struct le {
int value[N];
struct le *next;
};
// Defines type definitions
typedef struct le listelement;
typedef listelement *list;
// Defines functions
void insert(int ar[], list *l);
void delete_all(list *l);
void print_list(list l);
int compare(int ar[], list l, int pos);
int insertBehind(int new[], list *l, int ar[]);
list reverse(list l);
// Implement functions
// Takes an array and a list
// Inserts array as a new element in the list
// Returns void
void insert(int ar[], list *l) {
listelement *new;
new = malloc(sizeof(listelement));
memcpy(new->value, ar, sizeof(int) * N);
new->next = *l;
*l = new;
}
// Takes a list
// Frees the memory for the list
// Returns void
void delete_all(list *l) {
if (l == NULL) {
printf("List empty.\n");
return;
} else {
list next;
while (*l != NULL) {
next = (*l)->next;
free(*l);
*l = next;
}
}
}
// Takes a list
// Prints it properly formatted
// Returns void
void print_list(list l) {
if (l == NULL) {
printf("List empty\n");
return;
} else {
while (l != NULL) {
printf("[");
for (int i = 0; i < N; i++) {
printf("%d", l->value[i]);
if (i < N - 1) {
printf(",");
}
}
printf("]");
if (l->next != NULL)
printf(",");
l = l->next;
}
}
printf("\n\n");
}
// Takes an array and a list and a position in the list
// Compares array with the array in the list at the given position
// If the arrays doesnt equal it returns the index where it first differs -1 if
// they are equal, returns -2 if pos is longer then the list or list is empty
int compare(int ar[], list l, int pos) {
if (l == NULL) {
printf("List empty.\n");
return -2;
} else {
int index = 0;
while (l != NULL) {
if (index == pos) {
for (int i = 0; i < N; i++) {
if (l->value[i] != ar[i]) // If arrays arent equal
return i;
}
return -1; // Success
}
l = l->next;
index++;
}
}
return -2; // pos is bigger then list or list is empty
}
// Takes a new array and an array of a list and the list itself
// Inserts behind the lists array
// Returns 0 if successfull otherwise returns -1
int insertBehind(int new[], list *l, int ar[]) {
if (l == NULL) {
printf("List empty.\n");
return -1;
} else {
int pos = 0;
for (list curr = *l; curr; curr = curr->next, pos++) {
if (compare(ar, *l, pos) == -1) {
listelement *new_elem = malloc(sizeof(*new_elem));
if (!new_elem) {
perror("malloc");
exit(1);
}
memcpy(new_elem->value, new, sizeof(int) * N);
new_elem->next = curr->next;
curr->next = new_elem;
return 0; // success
}
}
return -1; // array not in list
}
}
// Takes a list
// Reverses the order of the elements and also the order of the order inside the
// elements. Returns a reversed list
list reverse(list l) {
list new_list = NULL;
if (l == NULL) {
printf("List empty.\n");
} else {
while (l != NULL) {
int reversed[N];
for (int i = 0; i < N; i++) {
reversed[i] = l->value[N - 1 - i];
}
insert(reversed, &new_list);
l = l->next;
}
}
return new_list;
}
// Takes int array
// Prints it
// Returns void
void print_array(int ar[]) {
printf("[");
for (int i = 0; i < N; i++) {
if (i == N - 1) {
printf("%d", ar[i]);
} else {
printf("%d, ", ar[i]);
}
}
printf("]");
}
// Takes void
// Main function
// Returns 0 if successfull
int main(void) {
// Initialising lists
list testList = NULL;
list emptyList = NULL;
// Initialising arrays
int arr1[N] = {1, 2, 3, 4, 5};
int arr2[N] = {6, 7, 8, 9, 10};
int arr3[N] = {11, 12, 13, 14, 15};
int arrCompare[N] = {6, 7, 8, 9, 10};
int arrNew[N] = {100, 101, 102, 103, 104};
int arrNotInList[N] = {90, 91, 92, 93, 94};
// Insert arrays into lists
insert(arr1, &testList);
insert(arr2, &testList);
insert(arr3, &testList);
// Print after insert
printf("\nInserted three arrays into testList: ");
print_list(testList);
// Compare testList at position 1 with arrCompare and print result
int pos = 1;
int compareResult = compare(arrCompare, testList, pos);
printf("Compare array ");
print_array(arrCompare);
printf(" at position %d of testList: %d\n\n", pos, compareResult);
// Insert new array into list behind arr2 and print new list
int insertResult1 = insertBehind(arrNew, &testList, arr2);
if (insertResult1 == 0) {
printf("Inserted ");
print_array(arrNew);
printf(" behind ");
print_array(arr2);
printf(" of testList.\n");
printf("testList after insertBehind: ");
print_list(testList);
} else {
print_array(arrNew);
printf(" not found in testList\n\n");
}
// Insert arrNotInList into testList behind
int insertResult2 = insertBehind(arrNew, &testList, arrNotInList);
if (insertResult2 == 0) {
printf("Inserted ");
print_array(arrNotInList);
printf(" behind ");
print_array(arr2);
printf(" of testList.\n");
printf("testList after insertBehind: ");
print_list(testList);
} else {
print_array(arrNotInList);
printf(" not found in testList\n\n");
}
// Print reversed testList
list reversedList = reverse(testList);
printf("reversedList of testList:");
print_list(reversedList);
// Test functions with empty list
print_list(emptyList);
compare(arrCompare, emptyList, 1);
insertBehind(arrNew, &emptyList, arr2);
reverse(emptyList);
// Free memory
delete_all(&testList);
delete_all(&reversedList);
delete_all(&emptyList);
return 0;
}
@@ -0,0 +1,37 @@
/* char_array.c
*
* Entscheidung, ob eine Zeichenkette ein 'a' enthaelt
*/
#include <stdio.h>
#include <string.h>
#define MAX 40
int main() {
int index;
char eingabe [MAX];
printf("Bitte String eingeben (max. %d Zeichen): ", MAX-1);
fgets(eingabe, MAX, stdin);
size_t eingabeLen = strlen(eingabe);
for (int i = 0; i < eingabeLen; i++)
{
if (eingabe[i] == 'a'){
printf("Position von 'a': %d\n", i);
} else {
printf("Der String enthält kein ’a’.\n");
return 0;
}
}
printf("\nEingabe: %s", eingabe);
for (index = 0; eingabe[index] != '\0'; index++)
if (eingabe[index] == 'a')
break;
return 0;
}
+11
View File
@@ -0,0 +1,11 @@
#include <stdio.h>
#include "date.h"
Date createDate(int year){
Date date = {.day = 1, .month = 1, .year = year};
return date;
}
void printDate(Date date){
printf("%d.%d.%d", date.day, date.month, date.year);
}
+13
View File
@@ -0,0 +1,13 @@
#ifndef DATE_H
#define DATE_H
typedef struct{
int day;
int month;
int year;
} Date;
Date createDate(int year);
void printDate(Date date);
#endif // DATE_H
+12
View File
@@ -0,0 +1,12 @@
#include <stdio.h>
unsigned long long explode(unsigned int m, unsigned short n){
return m << n;
}
int main(){
unsigned int m = 3;
unsigned short n = 4;
unsigned long long x = explode(m, n);
printf("%llu\n", x);
}
@@ -0,0 +1,19 @@
#include <stdio.h>
int main(void){
int celsius_round;
float celsius_exact;
int fahrenheit=0;
int max_fahrenheit = 300;
int steps = 20;
printf("\n\nFahrenheit \t Celsius(exakt) \t Celsius(gerundet) \n");
while(fahrenheit <= max_fahrenheit){
celsius_exact = (5.0/9.0) * (fahrenheit - 32.0);
printf("%i \t\t %f \t\t\t %i \n", fahrenheit, celsius_exact, (int)celsius_exact);
fahrenheit+=steps;
}
return 0;
}
+30
View File
@@ -0,0 +1,30 @@
/* fehler.c
*
* Ein Programm, dass Compilerfehler,
* Laufzeitfehler und logische Fehler demonstriert.
*/
#include <stdio.h>
int main() {
int num1,num2;
num1 = 0;
num2 = 1;
printf("Der Quotient der Variablen ist: ");
printf("%d\n", num1/num2);
printf("\n"); // Leerzeile
printf("Jetzt werden die Variablenwerte vertauscht.\n");
// Dies muss korrigiert werden. (logischer Fehler!!!)
int temp = num1;
num1 = num2;
num2 = temp;
printf("Der Quotient der Vaiablen ist nun: ");
printf("%d\n", num1/num2);
return 0;
}
+25
View File
@@ -0,0 +1,25 @@
#include <stdio.h>
int main(void){
printf("\n Die geraden Zahlen von 12 bis 0: ");
for(int i = 12; i >= 0; i-=2){
printf("%i, ",i);
}
printf("\n Die ungeraden Zahlen von -1 bis -13: ");
for(int i = -1; i >= -13; i-=2){
printf("%i, ", i);
}
printf("\n Die ersten 10 Quadratzahlen: ");
for(int i = 0; i <= 9; i++){
printf("%i, ", i*i);
}
printf("\n");
}
@@ -0,0 +1,11 @@
#include <stdio.h>
int main(){
int i = 66;
double x = .000007;
double y = 123.45;
printf("\ni:\n%d \n%o \n%x \n %X\n", i, i, i, i);
printf("\nx:\n%f \n%e \n%E \n%g \n%G\n", x, x, x, x, x);
printf("\ny:\n%g \n%G\n\n", y, y);
return 0;
}
@@ -0,0 +1,27 @@
#include <stdio.h>
#include "highscore.h"
#include "date.h"
Highscore createHighscore(Date date, int value){
Highscore highscore = { .date = date, .value = value};
return highscore;
}
void printHighscore(Highscore highscore){
if (firstYear){
printf("Scores ab: %d\n", firstYear);
}
printDate(highscore.date);
printf(": %d\n", highscore.value);
}
#ifdef TEST_HIGHSCORE
int main(){
Highscore highscore = createHighscore(createDate(1997),16);
printHighscore(highscore);
}
#endif
@@ -0,0 +1,18 @@
#ifndef HIGHSCORE_H
#define HIGHSCORE_H
#include "date.h"
int firstYear;
typedef struct {
Date date;
int value;
} Highscore;
Highscore createHighscore(Date date, int value);
void printHighscore(Highscore highscore);
#endif //HIGHSCORE_H
@@ -0,0 +1,64 @@
#include <stdio.h>
#define seperator printf("-----------------------\n")
void insertionSort(int arr[], int len){
int i, val, pos;
for(i = 0; i < len; i++) {
val = arr[i];
pos = i;
while((pos > 0) && (arr[pos - 1] > val)){
arr[pos] = arr[pos - 1];
pos = pos - 1;
}
if (pos != i)
arr[pos] = val;
}
}
void prettyprint(int arr[],int len){
int i;
if (len == 0){
printf("leer\n");
return;
}
for(i=0;i<len-1;i++) {
printf("%d, ",arr[i]);
}
printf("%d\n",arr[len-1]);
}
int main() {
int a1[] = {3,2,1,3,4,5,3,7,6,8,3};
int a2[] = {1};
int a3[] = {1,2,3,4};
int a4[] = {4,3,2,1};
int a5[] = {};
prettyprint(a1,11);
insertionSort(a1,11);
prettyprint(a1,11);
seperator;
prettyprint(a2,1);
insertionSort(a2,1);
prettyprint(a2,1);
seperator;
prettyprint(a3,4);
insertionSort(a3,4);
prettyprint(a3,4);
seperator;
prettyprint(a4,4);
insertionSort(a4,4);
prettyprint(a4,4);
seperator;
prettyprint(a5,0);
insertionSort(a5,0);
prettyprint(a5,0);
printf("\n");
return 0;
}
@@ -0,0 +1,19 @@
#include <stdio.h>
int main() {
double pi = 3.14159265359;
int r;
printf("Geben Sie den Radius ein: ");
scanf("%d", &r);
double f = pi * r * r;
double u = 2 * pi * r;
printf("Für einen Kreis mit Radius %d gilt:\n", (short)r);
printf("Fläche: %f\n", f);
printf("Umfang: %f\n", u);
return 0;
}
+7
View File
@@ -0,0 +1,7 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
int number = atoi(argv[1]);
printf("My number: %d\n", number);
}
+27
View File
@@ -0,0 +1,27 @@
#include <stdio.h>
struct point {
float x;
float y;
};
int main() {
struct point p1, p2;
struct point * ptr;
ptr = &p1;
p1.x = 3;
ptr->y = 4;
printf("\nx-Koordinate von p1: %f", ptr->x);
printf("\ny-Koordinate von p1: %f", (*ptr).y);
p2 = p1;
printf("\nx-Koordinate von p2: %f", p2.x);
printf("\ny-Koordinate von p2: %f", (&p2)->y);
printf("\n\n");
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
#include <stdio.h>
typedef struct {
float x;
float y;
} Point;
void movePoint(Point *p1, Point p2){
p1->x = p2.x;
p1->y = p2.y;
}
int main() {
Point p1, p2;
Point * ptr;
ptr = &p1;
p1.x = 3;
ptr->y = 4;
printf("\nx-Koordinate von p1: %f", ptr->x);
printf("\ny-Koordinate von p1: %f", (*ptr).y);
p2 = p1;
printf("\nx-Koordinate von p2: %f", p2.x);
printf("\ny-Koordinate von p2: %f", (&p2)->y);
Point p3;
p3.x = 10;
p3.y = 20;
movePoint(&p1, p3);
printf("\nx-Koordinate von p1: %f", p1.x);
printf("\nx-Koordinate von p1: %f", p1.y);
printf("\n\n");
return 0;
}
+41
View File
@@ -0,0 +1,41 @@
#include <stdio.h>
#include <stdlib.h>
struct point {
float x;
float y;
};
void move(struct point * punkt, float dx, float dy) {
punkt->x += dx;
punkt->y += dy;
}
int main() {
struct point * ptr;
ptr = malloc(sizeof(struct point)); // impl. Typcast des Pointers
if (ptr != NULL) {
ptr->x = 10;
ptr->y = 20;
printf("\nx-Koordinate von p: %f", ptr->x);
printf("\ny-Koordinate von p: %f", ptr->y);
free(ptr);
printf("\n");
printf("\nnach free():");
// Dangling Pointer!
printf("\nx-Koordinate von p: %f", ptr->x);
printf("\ny-Koordinate von p: %f", ptr->y);
printf("\n\n");
}
return 0;
}
+136
View File
@@ -0,0 +1,136 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
float x;
float y;
}Point;
typedef struct Listelement Listelement;
struct Listelement {
Point pnt;
Listelement *next;
};
typedef struct {
char* name;
Listelement *first;
} Polygon;
void append(Polygon * pz, Point pnt) {
Listelement * new = malloc(sizeof(Listelement));
if (!new) {
perror("Malloc failed.");
exit(1);
}
new->pnt = pnt;
new->next = NULL;
if (pz->first == NULL){
pz->first = new;
} else {
Listelement * tmp = pz->first;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new;
}
}
void polyPrint(Polygon *pz){
if (pz == NULL || pz->first == NULL){
printf("Kein Polygon.");
return;
}
printf("%s\n",pz->name);
Listelement *le = pz->first;
while(le != NULL){
printf("(%f, %f)\n", le->pnt.x, le->pnt.y);
le = le->next;
}
}
void shorten(Polygon *pz){
if (pz == NULL || pz->first == NULL){
printf("Kein Polygon.");
}
Listelement *le = pz->first;
while(le->next->next != NULL){
le = le->next;
}
free(le->next);
le->next = NULL;
}
Polygon mirror(Polygon *pz){
Polygon newPZ;
newPZ.first = NULL;
if (pz == NULL || pz->first == NULL){
newPZ.name = NULL;
printf("Kein Polygon.");
return newPZ;
}
const char *prefix = "Copy of ";
size_t newNameLen = strlen(prefix) + strlen(pz->name) + 1;
char *newName = malloc(newNameLen);
if (!newName) {
perror("Malloc failed");
exit(1);
}
strcpy(newName, prefix);
strcat(newName, pz->name);
newPZ.name = newName;
Listelement *le = pz->first;
while (le != NULL) {
Listelement *newElem = malloc(sizeof(Listelement));
if (!newElem) {
perror("Malloc failed");
exit(1);
}
newElem->pnt = le->pnt;
newElem->next = newPZ.first;
newPZ.first = newElem;
le = le->next;
}
return newPZ;
}
int main() {
Point pnt = (Point){.x = 10, .y = 20};
Point pnt2 = (Point){.x = 20, .y = 30};
Listelement first = {.pnt = pnt, .next = NULL};
Polygon pz;
pz.name = "Mein Polygon";
pz.first = &first;
append(&pz, pnt2);
polyPrint(&pz);
shorten(&pz);
polyPrint(&pz);
append(&pz, (Point){.x = 30, .y = 40});
append(&pz, (Point){.x = 50, .y = 40});
append(&pz, (Point){.x = 60, .y = 40});
append(&pz, (Point){.x = 70, .y = 40});
polyPrint(&pz);
Polygon pzMirror = mirror(&pz);
polyPrint(&pzMirror);
return 0;
}
+6
View File
@@ -0,0 +1,6 @@
#include <stdio.h>
int main(void){
printf("\nIch kenne die Formatelemente zu 100 %%.\n");
return 0;
}
+15
View File
@@ -0,0 +1,15 @@
#include <stdio.h>
int main(){
int i;
int *ptr;
ptr = &i;
i = 1;
printf("%i\n", *ptr);
printf("%p\n", ptr);
printf("%i\n", i);
*ptr = 2;
printf("%i\n", i);
}
+39
View File
@@ -0,0 +1,39 @@
#include <stdio.h>
#include <stdlib.h>
int y;
int func(int a, int b){
if (b == 0){
return -1;
}
else {
return (2 * (a * a)) / b;
}
}
int main (void){
int x = 4;
printf("Geben Sie eine ganze Zahl ein: ");
scanf("%i", &y);
int result = func(x,y);
if(result == -1){
printf("Ein Fehler ist aufgetreten.\n");
} else {
printf("Berechneter Wert: %i\n", result);
}
for(int i = 0; i <= 30; i++){
y = i;
result = func(x,y);
if(result == -1){
printf("Ein Fehler ist aufgetreten.\n");
} else {
printf("x: %i, y: %i, z: %i\n", x,y, result);
}
}
}
@@ -0,0 +1,26 @@
#include <stdio.h>
void decr(int n);
void rec_out(int n);
void decr(int n)
{
rec_out(--n);
}
void rec_out(int n)
{
static int count = 1;
printf("Die %d. Ausgabe.\n", count);
count++;
if (n > 1)
{
decr(n);
}
}
int main()
{
rec_out(6);
return 0;
}
@@ -0,0 +1,38 @@
#include <stdio.h>
int main() {
int i;
printf("\n");
// 12, 10, ... , 0
for(i = 12; i >= 0; i = i - 2) {
printf("%d", i);
if (i > 0)
printf(", ");
}
printf("\n\n");
// -1, -3, ..., -13
i = -1;
while (i > -14) {
printf("%d", i);
if (i > -13)
printf(", ");
i = i-2;
}
printf("\n\n");
// Quadratzahlen 0 ... 81
do {
printf("%d", i*i);
if (i < 9)
printf(", ");
i++; // Inkrementiere i
} while(i<=9);
printf("\n\n");
return 0;
}
+7
View File
@@ -0,0 +1,7 @@
#include "highscore.h"
int main(){
firstYear = 1997;
Highscore score = createHighscore(createDate(1997), 69);
printHighscore(score);
}
@@ -0,0 +1,19 @@
#include <stdio.h>
#define NL printf("\n");
#define ARROWS 3
#define ARCOLUMNS 4
int main()
{
int ar[ARROWS][ARCOLUMNS] = {
{0, 1, 2, 3},
{10, 11, 12},
{0}
};
for (int i = 0; i < ARROWS; i++){
for (int j = 0; j < ARCOLUMNS; j++){
printf("%d\t", ar[i][j]);
}
NL
}
}
@@ -0,0 +1,39 @@
#include <stdio.h>
#define NL printf("\n");
#define LENGTH 10
void writing_squarenumbers_array(int *array, int size){
printf("Writing square numbers to Array...");
for (int i = 0; i < size; i++){
array[i] = i * i;
}
NL
}
void print_array(int *array, int size){
printf("Printing Array: ");
for (int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
NL
}
void print_array_rev(int *array, int size){
printf("Printing Array (reversed): ");
for (int i = 0; i < size; i++){
printf("%d ", array[size - 1 - i]);
}
NL
}
int main(){
int array[LENGTH];
writing_squarenumbers_array(array, LENGTH);
print_array(array, LENGTH);
print_array_rev(array, LENGTH);
}
@@ -0,0 +1,44 @@
#include <stdio.h>
#define NL printf("\n");
#define LENGTH 1000
void writing_squarenumbers_array(int *array, int size){
printf("Writing square numbers to Array...");
for (int i = 0; i < size; i++){
array[i] = i * i;
}
NL
}
int main(){
int array[LENGTH];
int input;
writing_squarenumbers_array(array, LENGTH);
while(1){
printf("Geben Sie eine Zahl ein zwischen 1 und %d: \n", LENGTH);
int result = scanf("%d", &input);
if (result != 1){
printf("Ungültige Eingabe. Bitte geben Sie eine ganze Zahl ein.\n");
while (getchar() != '\n'); // Eingabepuffer leeren
continue;
}
if (input == 0) {
printf("Programm beendet.\n");
break;
}
if (input < 1 || input > 1000) {
printf("Fehler: Zahl außerhalb des gültigen Bereichs!\n");
continue;
}
printf("Deine Quadratzahl ist: %d\n", array[input]);
break;
}
return 0;
}
+33
View File
@@ -0,0 +1,33 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
// Static string
char statS[50] = "Hallo PdP!";
// Dynamic string
char *dynS = malloc(11);
strcpy(dynS, "Hallo PdP!");
// Print
printf("Static string [1]: %c \n", statS[1]);
printf("Dynamic string [1]: %c \n", dynS[1]);
// Neuzuweisung
statS[1] = 'e';
dynS[1] = 'e';
// Print
printf("Static string [1]: %c \n", statS[1]);
printf("Dynamic string [1]: %c \n", dynS[1]);
// Neuzuweisung 2
strcpy(statS,"neuer String");
dynS = "neuer String";
// Print
printf("Static string: %s \n", statS);
printf("Dynamic string: %s \n", dynS);
}
+16
View File
@@ -0,0 +1,16 @@
#include <stdio.h>
void swap(int* value1, int* value2){
int buffer = *value1;
*value1 = *value2;
*value2 = buffer;
}
int main(){
int x = 4;
int y = 5;
printf("x:%i y:%i\n", x, y);
swap(&x, &y);
printf("swap!\n");
printf("x:%i y:%i\n", x, y);
}
+20
View File
@@ -0,0 +1,20 @@
#include <stdio.h>
#include <stdlib.h>
#define NL printf("\n");
int main(void){
int ar[3][4] = {
{0, 1, 2, 3},
{10, 11, 12}
};
for(int i = 0; i < sizeof(ar)/sizeof(ar[0]);i++){
for(int j = 0; j < sizeof(ar[0])/sizeof(int);j++){
printf("%i\t", ar[i][j]);
}
NL
}
}
@@ -0,0 +1,37 @@
/* typengroesse.c
*
* Bestimmung der Groesse der einfachen typen mit sizeof
*/
#include <stdio.h>
int main() {
char c = 127;
unsigned char uc = 255;
printf("\n");
printf("char: \t\t\t%2d\n", (int) sizeof c);
printf("unsigned char: \t\t%2d\n", (int) sizeof uc);
printf("short: \t\t\t%2d\n", (int) sizeof(short));
printf("unsigned short: \t%2d\n", (int) sizeof(unsigned short));
printf("int: \t\t\t%2d\n", (int) sizeof(int));
printf("unsigned int: \t\t%2d\n", (int) sizeof(unsigned int));
printf("long: \t\t\t%2d\n", (int) sizeof(long));
printf("unsigned long: \t\t%2d\n", (int) sizeof(unsigned long));
printf("long long: \t\t%2d\n", (int) sizeof(long long));
printf("unsigned long long: \t%2d\n", (int) sizeof(unsigned long long));
printf("float: \t\t\t%2d\n", (int) sizeof(float));
printf("double: \t\t%2d\n", (int) sizeof(double));
printf("long double: \t\t%2d\n", (int) sizeof(long double));
printf("_Bool: \t\t\t%2d\n", (int) sizeof(_Bool)); // C99-Boolescher Typ
printf("\n");
return 0;
}
@@ -0,0 +1,25 @@
#include <stdio.h>
#include <stdlib.h>
int main() {
float n;
int rvalue;
int c;
while(1){
printf("Geben Sie eine Zahl ein: ");
rvalue = scanf("%f", &n);
if (rvalue == 1){
break;
} else {
printf("Fehler: Bitte geben Sie eine gueltige Zahl ein.\n");
if (rvalue == 0) {
do {
c = getchar();
} while (c != '\n');
}
}
}
printf("Die Zahl ist %f\n", n);
return 0;
}
+29
View File
@@ -0,0 +1,29 @@
#include <stdio.h>
int main(void){
printf("\n Die geraden Zahlen von 12 bis 0: ");
int i = 12;
while(i>=0){
printf("%i, ",i);
i-=2;
}
printf("\n Die ungeraden Zahlen von -1 bis -13: ");
i = -1;
while(i>=-13){
printf("%i, ", i);
i-=2;
}
printf("\n Die ersten 10 Quadratzahlen: ");
i = 0;
do{
printf("%i, ", i*i);
i++;
} while(i<=9);
}
@@ -0,0 +1,39 @@
#include <stdio.h>
#include <string.h>
#define STRING_LENGHT 50
int main(){
char s1[STRING_LENGHT];
char s2[STRING_LENGHT];
printf("Bitte geben Sie einen Vornamen ein: \n");
scanf("%49s", s1);
printf("Bitte geben Sie einen Nachnamen ein: \n");
scanf("%49s", s2);
if (strcmp(s1, s2))
{
printf("Vor- und Nachname sind verschieden\n");
}
else
{
printf("Vor- und Nachname sind gleich.\n");
}
for (int i = 0; s2[i] != '\0'; i++){
if (s2[i] >= 'a' && s2[i] <= 'z'){
s2[i] = s2[i] - ('a'-'A');
}
}
char name[STRING_LENGHT * 2];
strcat(name, s1);
strcat(name, " ");
strcat(name, s2);
int name_laenge = (int)(strlen(s1) + strlen(s2));
printf("name: %s, Laenge: %i\n", name, name_laenge);
}